UPDATE 3: RESOLVED!
problem was not connected with FirebaseService, settings or payload. Problem was in application code... Our code had such thing (inheritance from Application):
ParentDroidApplication : Application
In that class in OnCreate method select which activity to use and Call "StartActivity". I moved this switch to MainActivity and problem was solved.
UPDATE 2:
Android Manifest (deleted service tag):
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.visma.vfsmobileparentapp" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:theme="#style/Theme.AppCompat.Light" android:label="Min skole" android:icon="#drawable/ic_launcher" android:name="Min skole">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#drawable/ic_launcher" />
</application>
</manifest>
Payload (added content_available and priority):
{
"to" : "token",
"collapse_key" : "type_a",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"content_available": true,
"priority": "high"
}
result same: app is opening automatically after remote notification :(
UPDATE:
I added intent with my main activity, default sounds and Miliseconds as int for notification number in OnMessaggeReceive method (you can see in the code below).
I tried to delete
<service android:name=".MyFirebaseMessagingService" android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
I didn't receive any notifications but app is still opening. it seems that Firebase is working as it should work. But application it self doing magic
I tried to downgrade Firebase to version 42.1021.1. Result is same
QUESTION
We are developing mobiles apps with Xamarin. We need notifications and we started to use Firebase Cloud messaging. All messages (notifications) are working, receiving, even updating badges in iOS, but... one problem with Android:
If app is closed (swiped from app list) and receiving remote notification it is opening automatically. I want to avoid this. Background or foreground modes are working as expecting.
My Andoroid manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app" android:versionName="1.0" android:installLocation="internalOnly" android:versionCode="46">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="true" android:theme="#style/Theme.AppCompat.Light" android:label="App" android:icon="#drawable/ic_launcher" android:name="App">
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#drawable/ic_launcher" />
</application>
<service android:name=".MyFirebaseMessagingService" android:stopWithTask="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</manifest>
My FirebaseMessagingService.cs:
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public override void OnMessageReceived(RemoteMessage message)
{
SendNotification("title", "body"); //just for testing
}
public void SendNotification(string title, string body)
{
var intent = new Intent(this, typeof(LoginActivity));
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var defaultSoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
var style = new Android.Support.V4.App.NotificationCompat.BigTextStyle();
style.BigText(body);
Bitmap largeIcon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_launcher);
var notificationBuilder =
new Android.Support.V4.App.NotificationCompat.Builder(this)
.SetLargeIcon(largeIcon)
.SetSmallIcon(Resource.Drawable.ic_launcher)
.SetContentTitle(title)
.SetContentText(body)
.SetStyle(style)
.SetAutoCancel(true)
.SetSound(defaultSoundUri)
.SetContentIntent(pendingIntent)
.SetVisibility((int)NotificationVisibility.Public);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(DateTime.Now.Millisecond, notificationBuilder.Build());
}
}
I tried change manifest values, tried simulator, device, I sent different payloads:
both notification and data:
{
"to" : "token",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
}
}
only notification:
{
"to" : "token",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
}
}
only data:
{
"to" : "token",
"data" : {
"body" : "First Notification",
"title": "Collapsing A"
}
}
in all cases notification is receiving and opening app automatically when app is closed. How to avoid that auto opening? I need only notification. Any ideas what I can do?
nuget packages:
Xamaring.Firebase.Messaging - 60.1142.1
Xamarin.Firebase.Code - 60.1142.1
Xamarin.Firebase.Common - 60.1142.1
tested in Android 6 and Android 7 devices (Samsung)
You need to define here Activity, which has to open when you tap notification.
var intent = new Intent(this, typeof(YourActivity));
intent.AddFlags(ActivityFlags.ClearTop);
//sent RemoteMessage message data to your activity if you need
//intent.PutExtra("User", JsonConvert.SerializeObject(user));
var pendingIntent = PendingIntent.GetActivity(this, GenerateRandom(), intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.myIcon)
.SetContentTitle(user.Organization)
.SetSubText(myModuleName)
.SetContentText(BodyText)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.Build();
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
//this is for sound of notification
var mp = MediaPlayer.Create(ApplicationContext, notification);
mp.Start();
notificationManager.Notify(GenerateRandom(), notificationBuilder);
To just give unique Id to notifications so that they wont overlap
private int GenerateRandom()
{
var rn = new Java.Util.Random();
int n = 1000 - 1233 + 1;
int i = rn.NextInt() % n;
return 1000 + i;
}
My understanding of the situation tells me that since you have not given the notification a pending intent it is directly opening your application:
Workaround to this problem :
Intent intent = new Intent(this, typeof(MainAcitivity)); //Activity you want to open
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), intent, PendingIntentFlags.OneShot);
In case you want default sounds :
Notification notify = new Notification();
notify.Defaults = NotificationDefaults.Sound;
notify.Defaults = NotificationDefaults.Vibrate;
Using the NotificationCompat to push the notification(For backward Compatibility)
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.Icon)
.SetContentTitle(messageTitle)
.SetContentText(messageBody)
.SetSound(Settings.System.DefaultNotificationUri)
.SetVibrate(new long[] { 1000, 1000 })
.SetLights(Color.AliceBlue, 3000, 3000)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
Then notifying the system that a notification is thrown from your application:
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(RandomGenerator(), notificationBuilder.Build());
Also, Random numbers so that the notifications don't switch places when a new one is thrown :
private int RandomGenerator()
{
return new Random().Next( int.MinValue, int.MaxValue );
}
And for Android Oreo channel compatibility as you can see official docs, you need to add the following metadata element in your AndroidManifest.xml within the application component:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
This default channel will be used when notification message has no specified channel, or if the channel provided has not yet been created by the app.
Related
it's been weeks since i have this problem. i can already generate the FCM token and subscribe topics.
the problem that i am having is when i click the notification, nothing is happening it is not even going to the application and i still can't get the body and title of the notification. i know that the notification do not have a relationship with the actual application that i have, i already followed the documentation on handling the receive messages but still nothing is happening.
here is the link that i followed. https://firebase.google.com/docs/cloud-messaging/android/receive
Here is the code that i have.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
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());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(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.
}
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eperformax.eplife">
<uses-permission android:name="android.permission.INTERNET" />
<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>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
i already saw some related question here but nothing solves my problem. i just followed the documentation and still this is happening.
Can anyone help me this is really stressing me out. Any help would be really appreciated.
I'm using Android O Emulator and want to get notification from Firebase console.It is working fine on every device except Android O. I'm getting this Error in Log.
W/Notification: Use of stream types is deprecated for operations other than volume control
W/Notification: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
I know that I have to specify Channel id for that .
So What I have done so far
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/attach" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="my_notification_channel" />
<service android:name=".Helper.FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".Helper.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<my all activities...>
I've also specify channel id in FirebaseMessagingService like this
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "my_notification_channel";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText(remoteMessage.getNotification().getBody())
.setOngoing(true)
.setChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
So after doing all this . I still got that error message in log and can't receive notification from console.Any Help would be appreciable.
When an FCM message contains no data payload, only a notification payload, and your app is in the background, Firebase generates the notification directly and does not call onMessageReceived(). This is explained in the documentation.
For Android O, a notification channel must be created. You are correctly defining the default notification channel in your manifest, but the channel is created in the onMessageReceived() code, which does not execute when the app is in the background.
Move the code that creates the channel somewhere that you can be certain it will execute before a notification is received.
Also, as indicated in the Firebase Release Notes, support for notification channels was added in version 10.2.6. You must build with at least that version.
I'm trying to send push notification from my app server to my app using Google cloud Messaging the app working well on Android Emulator but some devices not getting notification
here is FCMMessagingService.java
public class FCMMessagingService extends FirebaseMessagingService {
String title;String message;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null){
title = remoteMessage.getNotification().getTitle();
message = remoteMessage.getNotification().getBody();
Log.d("Message body", remoteMessage.getNotification().getBody().toString());
}
Map<String, String> data = remoteMessage.getData();
title = data.get("company");
message = data.get("message");
Log.d("Message body", remoteMessage.getData().toString());
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);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
super.onMessageReceived(remoteMessage);
}
}
here is Manifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<service android:name=".FcmInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
</intent-filter>
</service>
<service
android:name=".FCMMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
If you getting the notification when your app is in foreground the it's ok you just use a data payload instead of notification payload you can use both together but data payload works when app in background or even close. I recommend you for only use the data payload because it's work 100% time. One of my app didn't get notification when app is closed but I used both payload then I just changed it to only data payload and it worked fine.
I am checking Firebase Cloud Messaging to send notification. Have implemented it already and its receiving notification when app is in open state. But if I close app, its no longer gives notification. Is there any solution for this.
Code:
WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));
string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";
Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse wResponse = wRequest.GetResponse();
Messaging service-
public class MessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
public void showMessage(Map<String, String> serverData) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
}
private void sendNotification(Map<String, String> serverData) {
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_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
}
}
Main activity-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
}
}
Manifest-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.com.firebasenotify">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<service android:name=".MessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".InstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
There was no issue with the code. I was using Mi note 4, and somehow it does not show notification in Mi4 when app is closed. I tested with other android device and its working fine.
Thanks to Tim Castelijns and Frank van Puffelen for participating in the conversation.
There's good solution and explanation about that issue here. You need to set high priority for notification to tell android react immediately, otherwise it takes couple of minutes to display received notification.
I used Legacy Server Key instead of Server Key it had worked for me.
adding time_to_live key in your POST Payload will solve this problem.The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which FCM stores and attempts to deliver the message. "time_to_live" : 3 Refer Firebase Docs
As per FCM docs onMessageReceived() won't be called when app is in the background. You should send a notification object on order to show it up in the system tray and when user clicks it the launcher activity will be open with data as extras with the intent. For payloads you should use data object. see docs and Receive Messages in an Android App
After a Push Notification is received, I want to open an Àctivity when the Notification is pressed.
Here are my Services:
public class GCMIntentService extends GcmListenerService {
#Override
public void onMessageReceived(String from, Bundle data) {
String title = data.getString("title");
String message = data.getString("message");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setTicker(message)
.setAutoCancel(true);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
Intent myIntent = new Intent(this, MyActivity.class);
PendingIntent intent2 = PendingIntent.getBroadcast(this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(intent2);
notificationManager.notify(1, mBuilder.build());
}
public class GCMIDListenerService extends InstanceIDListenerService {
#Override
public void onTokenRefresh() {
InstanceID instanceID = InstanceID.getInstance(this);
String token;
try {
token = instanceID.getToken(Resources.getSystem().getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (IOException e) {
e.printStackTrace();
}
//TODO:send token to the server
}
}
I just did everything following the Google documentation. I implemented that feature for another project sometime ago but it was a bit different, I used my own 'BroadcastReceiver' instead of the 'com.google.android.gms.gcm.GcmReceiver' provides by Google.
Here is my Manifest:
<application>
...
<!-- GCM Push Notifications Config -->
<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="gcm" />
</intent-filter>
</receiver>
<service
android:name=".push.GCMIntentService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".push.GCMIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
</application>
Any ideas? Am I missing something?
Here some documentation I have follow:
Google official documentation
CGM tutorial By Dustin Rothwell
And of course I have researched a lot here at stackoverflow.
Thanks!
You have done one minor mistake. You are writing this code for opening activity.
PendingIntent intent2 = PendingIntent.getBroadcast(this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(intent2);
As you want to open activity you need to create pending intent using getActivity method instead of getBroadcast method.
Hope this will help.