Android - not getting GCM token - android

I call RegistrationIntentService:
if (checkPlayServices()) {
Log.i("udazzT", "check servicies");
// Start IntentService to register this application with GCM.
Intent intent2 = new Intent(this, RegistrationIntentService.class);
startService(intent2);
}
But I cannot see any of the logs in RegistrationIntentService:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private static final String[] TOPICS = {"global"};
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i("udazzT", "setting token");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// In the (unlikely) event that multiple refresh operations occur simultaneously,
// ensure that they are processed sequentially.
synchronized (TAG) {
// [START register_for_gcm]
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
// [START get_token]
Log.i("udazzT", "setting token 2");
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// [END get_token]
Log.i(TAG, "GCM Registration Token: " + token);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(token);
// Subscribe to topic channels
subscribeTopics(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();
// [END register_for_gcm]
}
} 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);
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
/**
* Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
*
* #param token GCM token
* #throws IOException if unable to reach the GCM PubSub service
*/
// [START subscribe_topics]
private void subscribeTopics(String token) throws IOException {
for (String topic : TOPICS) {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
// [END subscribe_topics]
}

Make sure that it is registered in your manifest.
<service android:name=".RegistrationIntentService"
android:exported="false" />

Did you think to add all is needed like here googlesamples

Just add this
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="<PACKAGE-NAME>" />
</intent-filter>
in manifest.xml of "GcmReceiver" & "MyGcmListenerService" in my code it is looks like below.
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="<PACKAGE-NAME>" />
</intent-filter>
</receiver>
<!-- [END gcm_receiver] -->
<!-- [START gcm_listener] -->
<service
android:name="<PACKAGE-NAME>.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="<PACKAGE-NAME>" />
</intent-filter>
</service>
<!-- [END gcm_listener] -->
<!-- [START instanceId_listener] -->
In my case it is working... May be it will be helpful to you. Best Of Luck

check if you have added below line in receivers intent filter
Since its mentioned in GCM doc as:
If you want to support pre-4.4 KitKat devices, add the following action to the intent filter declaration for the receiver:
https://developers.google.com/cloud-messaging/android/client#manifest

Related

Push notification not works in firebase

I have created one new app for push notification in https://console.firebase.google.com. I have followed all steps mentioned at last it shows -unknown app- under the head Targeting user segment.
How to test push notification in firebase?
AndroidManifest.xml
`
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
`
First, for using firebase push notifications add the dependencies
dependencies {
compile 'com.google.firebase:firebase-messaging:11.6.2' // this line must be included to use FCM
}
Add a service that extends FirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
In your Manifest add this
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Add a service that extends FirebaseInstanceIdService
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
Add it into the AndroidManifest.xml file, this makes sure that the service is loaded
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
You are done implementing firebase push notifications !
Test and send your first push notification from firebase console !
hope it helped
For more info check this: https://firebase.google.com/docs/cloud-messaging/android/client?hl
happy coding !

Fetch old notification from fcm Android

I am using FCM for notification and it is working good in all scenarios in Foreground and background. My problem is when I am logout from my application and another user send me message, I am not getting any notification as I am logout which is fine, but when I again login in my application I want to receive that old unread notification so how to do this any help would be appreciated following is the code I used
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
Context ctx = this;
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
try {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Log.e("remote", remoteMessage.getData().get("type") + "");
Log.e("remoteMessage", remoteMessage.getData() + "");
Log.e("remoteMessagebody", remoteMessage.getData().get("body") + "");
// handling other data also according to my app which i am not mentioning
}
}
I have used this code for fetching old notification but didnot worked
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
and in manifest
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
and in gradle
compile 'com.google.firebase:firebase-messaging:9.2.1'
An FCM message has its own lifetime -- 4 weeks default, could be modified by setting time_to_live in your payload. After that time, the message would be discarded.
What you could do is implement that each notif is saved in a your Server DB, if it is not read yet and you detect that the user re-logs in, re-send them as push notifications, or simply retrieve them in your app and display them as notifications.

How to ensure that the Firebase Messaging sample implementation is notified even if app process is dead?

When I build and run the Firebase Messaging Sample app (after obtaining and installing a custom google-services.json file from my Firebase Console, as described by the wizard within Android Studio), I can send a simple non-notification message to it with my test script, and it works.
... but only if the app has been started on the device.
If I fail to first start the app, or force-stop the app (from Settings | Apps) after it's been started, the message doesn't quite seem to get through. (I say that because I no longer see any logging output from my onMessageReceived method).
Some have reported that when a message is sent out, their app wakes up even if their app has not first been started -- which is great! Exactly what I want!
But I haven't been able to figure out what they're doing to make that happen.
What am I missing? How should I change this code to make sure that it receives the message even when the app has not been started, or after the app has been forcibly stopped?
Note: the code I'm running (below) is based very closely upon the Firebase Quickstarts for Android code which can be downloaded and built from within Android Studio (File | New | Import Sample ... and then find "Firebase Quickstarts for Android" within the list it populates). (I believe that Google hosts that same code on GitHub here: github.com/firebase/quickstart-android/tree/master/messaging‌​). I modified the logging output and comments slightly.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.firebase.quickstart.fcm">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<!-- [START fcm_default_icon] -->
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<!-- [END fcm_default_icon] -->
<activity
android:name="com.google.firebase.quickstart.fcm.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- [START firebase_service] -->
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<service android:name=".MyJobService"
android:exported="false">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
</application>
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "onMessageReceived: From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "onMessageReceived: Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "onMessageReceived: Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
bash test script
curl -X POST \
--Header "Authorization: key=<server key from Firebase Console>“ \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d " \
{ \
\"to\”:\”<token returned by FirebaseInstanceId.getInstance().getToken()>\”, \
\"priority\": \"high\" \
}"
echo
The behavior you are observing is the result of the app being in the "Stopped State". This behavior was introduced in Android 3.1 and is described here in the section Launch controls on stopped applications:
Applications are in a stopped state when they are first installed but
are not yet launched and when they are manually stopped by the user
(in Manage Applications)
When an app is in Stopped state, the system will not deliver Broadcast intents to it, which means it will not receive Firebase messages. As far as I know, you can't get around this; the user must start the app for the first time. This tells the system that the user wants the app to be operational and it is safe to deliver Broadcast intents to it.
Here are some SO questions/answers related to Stopped State.

FCM demo cannot get token

I created a project on Firebase console. I had register the package on the Firebase console, But I can`t get any token from the log even hit the LOG TOKEN button in the app.
Then I try to send message with Firebase console and set to target to my app package name.I didn't get any incoming message from the log.
Code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String TAG = "HelloJni";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
// [END handle_data_extras]
Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// [START subscribe_topics]
FirebaseMessaging.getInstance().subscribeToTopic("news");
// [END subscribe_topics]
// Log and toast
String msg = getString(R.string.msg_subscribed);
Log.d(TAG, msg + ", " + FirebaseInstanceId.getInstance().getToken());
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
RegistrationIntentService.java
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
String token = FirebaseInstanceId.getInstance().getToken();
Log.i(TAG, "FCM Registration Token: " + token);
}
}
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "oncreate.........");
}
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
#Override
public void onTokenRefresh() {
Log.e(TAG, "onTokenRefresh call...");
// Get updated InstanceID token.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
Log.d(TAG, " sendRegistrationToServer Refreshed token: " + token);
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "oncreate..........");
}
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name="com.example.hellojni.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name="MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name="RegistrationIntentService" ></service>
</application>
OnCreate() for MyFirebaseInstanceIDService and MyFirebaseMessagingService was not called, and the token returns null.
The log:
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing
02-20 18:05:28.273 23322-23322 D/HelloJni: Subscribed to news topic, null
The device or emulator you are testing on does not have Google Play Services or the Google Service Framework (GSF) installed. Most of the Firebase APIs use the capabilities of Google Play Services and will not run if it is not present on the device.
put this at last after dependency in your app level gradle.apply plugin: 'com.google.gms.google-services'
and put this into your project level gradle.classpath 'com.google.gms:google-services:3.0.0'
make sure you have puted google-service.json in app module.
you have to add .
apply plugin: 'com.google.gms.google-services'
in last line in your gradle file and .
classpath 'com.google.gms:google-services:3.0.0'
in your project level file . IntentService service class will called only ones when your app intralled so delete app every time and and intrall every time when you want to generate tocken
I see the reason. I run the app with Android phone made in China, and these phones has no google play service and store.

GCM client does not receive downstream messages

My app server is sending out messages to GCM successfully, however, in the client side, the messages are not being received, even though it has the token and it has been subscribed to different topics.
For listening to the incoming messages, I am using an extension of GcmListenerService. Since this is a service, it starts from the mainactivity. Bellow is the relevant part of the manifest:
<!-- [START gcm_permission] -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- [END gcm_permission] -->
<!-- [START gcm_receiver] -->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="my.app" />
</intent-filter>
</receiver>
<!-- [END gcm_receiver] -->
<!-- [START gcm_listener] -->
<service
android:name="my.app.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<!-- [END gcm_listener] -->
<!-- [START instanceId_listener] -->
<service
android:name="my.app.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<!-- [END instanceId_listener] -->
<service
android:name="my.app.RegisterIntentService"
android:exported="false">
</service>
The GCM listener is below:
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
// [START receive_message]
#Override
public void onMessageReceived(String from, Bundle 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.
//TOPICS = {"News","Updates","GeneralInfo"};
if (from.split("/")[2].equals("News")) {
....
As it was mentioned before, the GCM listener is being started from the mainactivity as a regular service.
//starting the listener service for messages
intentGCMListen = new Intent(this,MyGcmListenerService.class);
startService(intentGCMListen);
In the example (GCM quickstart) that I followed, which is basically the core of my deployment for GCM in this part, there is no such a start for the GCM listener service. I assumed that it should be started because it is a service.
Any ideas why the messages are not being downloaded from the GCM server?
UPDATE
The bash script that I am using for sending the messages from the server to GCM is:
#!/bin/bash
api_key=AIadasdasdsa
message=$1
topic=/topics/GeneralInfo
curl --header "Authorization: key=$api_key" --header Content-Type:"application/json" https://gcm-http.googleapis.com/gcm/send -d "{\"to\":\"$topic\",\"data\":{\"message\":\"$message\"}}"
I think you are missing the BroadcastReceiver in your code that serves the purpose of receiving the Broadcast that has been send by the GCM server for your app clients to process. You need to check for the following lines in the code:
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
// Showing received message
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
WakeLocker.release();
}
};
For more code description take a look at this tutorial.

Categories

Resources