I am a beginner in android,My Application send empty GCM registration ID to server . The call is correct because the server accepts it, no error, and add a row in the database but the regid string is empty. I studied all the answers but I can not find out what is wrong.
and tag is null as in this picture
MainActivity.java
package
com.inducesmile.androidgooglecloudmessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
private TextView registrationStatus;
private Button clickToRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registrationStatus = (TextView)findViewById(R.id.is_register);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken =
sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER,
false);
if (sentToken) {
registrationStatus.setText(getString(R.string.gcm_send_message));
} else {
registrationStatus.setText(getString(R.string.token_error_message));
}
}
};
clickToRegister = (Button)findViewById(R.id.register_push);
clickToRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
/**
*
Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK
from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
MyInstanceIDListenerService.java
package com.inducesmile.androidgooglecloudmessaging;
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
@Override
public void onTokenRefresh() {
//super.onTokenRefresh();
// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
MyGcmListenerService.java
package com.inducesmile.androidgooglecloudmessaging;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
//super.onMessageReceived(from, data);
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("GCM Message Received")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
RegistrationIntentService.java
package khd.test.nk.gcm;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class RegistrationIntentService extends IntentService {
EditText editText;
private static final String TAG = "RegistrationIntentService";
private static final String pathToServer = "http://cars.heliohost.org/gcmm/insertuser.php";
public RegistrationIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// Initially this call goes out to the network to retrieve the token, subsequent calls are local.
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(TAG, "GCM Registration Token: " + token);
sendRegistrationToServer(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/******************************************************************************************************/
private void sendRegistrationToServer(String token) {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, bowlingJson(token));
Request request = new Request.Builder()
.url(pathToServer)
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.d(TAG, String.valueOf(response));
Log.d(TAG, "Response" + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
private String bowlingJson(String token) {
return "{'registrationId': " + token + "}";
}
}
php
<?php
include_once './db_functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
$registration_id = $_POST["registrationId"];
$res = $db->insertUser($registration_id);
echo " RegId ".$registration_id ;
if(isset($_POST['registrationId'])) {
echo "GCM Reg Id bas been shared successfully with Server";
} else {
echo "Error occured while sharing GCM Reg Id with Server web app"; ;
}
?>
<?php
class DB_Functions {
private $db;
function __construct() {
include_once './db_connect.php';
// Connect to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Insert new user
*
*/
public function insertUser($registration_id) {
// Insert user into database
$result = mysql_query("insert into user (gcm_regid, created_at) values ('$registration_id', NOW())");
if ($result) {
return true;
} else {
return false;
}
}
/**
* Select all user
*
*/
public function getAllUsers() {
$result = mysql_query("select * FROM user");
return $result;
}
/**
* Get GCMRegId
*
*/
public function getGCMRegID($id){
$result = mysql_query("SELECT gcm_regid FROM user WHERE id = "."'$id'");
return $result;
}
}
?>
thanks in advance
php config.php
<?php
define("DB_HOST","localhost");
define("DB_USER","root");
define("DB_PASSWORD","30501001515");
define("DB_NAME","clients");
define("GOOGLE_API_KEY","AIzaSyBv_v_UAb1JpbDw8rwgQgMzqS3DyPoQCFA");
?>
registeruser.php
<?php
if(isset($_POST['registrationId'])){
$registration_id = $_POST['registrationId'];
include_once 'userregistration.php';
$UserRegistrationClass = new UserRegistrationFromDevice();
$UserRegistrationClass->saveNewRegisteredUser($registration_id);
}
?>
Database.php
<?php
include_once 'db.php';
class DatabaseLayer{
private $tables;
public function __constructor(){
$this->tables = "user";
}
public function insertUserRegistrationId($registration_id){
if(!$this->getAllRegisteredUsers($registration_id)){
$com = new DbConnect();
$sql = "insert into user (gcm_regid, created_at) values ('$registration_id', NOW())";
mysqli_query($com->getDb(), $sql);
}
}
public function getAllRegisteredUsers($registration_id){
$com = new DbConnect();
$sql = "Select * from user where gcm_regid = " + $registration_id;
$result = mysqli_query($com->getDb(), $sql);
if(count($result) == 1){
return true;
}
return false;
}
public function getRegistrationId(){
$com = new DbConnect();
$sql = "select gcm_regid from user limit 1";
$result = mysqli_query($com->getDb(), $sql);
$row = mysqli_fetch_row($result);
//print_r($row[0]);
if(count($row) == 1){
return $row[0];
}
return false;
}
}
?>
table
CREATE TABLE IF NOT EXISTS `user` (
`gcm_regid` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`id` int(8) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;