Click on notification not launching the app - android

When push notification is received while the app is not running and the user presses on notification, it just disappears and the log says:
2019-10-22 12:42:45.747 23260-23260/de.app.test.staging E/FirebaseMessaging: Notification pending intent canceled
Here is the SplashActivity that is supposed to be launched as a Launcher Activity:
<activity
android:name="de.app.test.login.SplashActivity"
android:screenOrientation="portrait"
android:exported="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
What can the issue be here?

For anyone looking for an answer, the back-end was sending the "click_action" to notification, therefore there was no intent filter for that Activity.
For me the click_action is "OPEN_ACTIVITY_1" so I just added one more intent-filter to my SplashActivity like this:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

you need to set pendingIntent object in notificationBuilder instance like
mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
Intent intent = new Intent(context, TargetActivity.class));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
Please note that CHANNEL_ID is for build version greater or equal to Oreo
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CHANNEL_ID = createNotificationChannel(CHANNEL_ID, "channelName");
}
#RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(String channelId, String channelName) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
String description = "description";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
mNotificationManager.createNotificationChannel(channel);
return channelId;
}

Forground app:
You need a PendingIntent to open app.
Try this:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
If Activity is in background or closed then notification message is shown in the notification center for app launcher activity.
You can use a BroadcastReceiver class. When you close the app, broadcast can listen this action. So, if you create a BroadcastReceiver class, you don't take this problem.
public class ClosedBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, HomePage.class));
} else {
context.startService(new Intent(context, HomePage.class));
}
}
}
More Information:
https://firebase.google.com/docs/cloud-messaging/android/receive

Related

Clicking on Notification in background not open my App?

I am a newbie in android development.
I create a background service for receive pushNotification (with our own socket service, not FCM).
And now my device receive message and show notification successfully. But when I click the notification, it not return to my app.
When I click notification, show the error below:
ActivityManager: Unable to start service Intent { cmp=com.my.app/package.name.AppActivity } U=0: not found
Here is my code:
public static void setNotification(Service service, String message) {
NotificationManager manager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE);
String appName = service.getString(R.string.app_name);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
.setContentTitle(appName)
.setContentText(message)
.setContentIntent(getDefaultIntent(service))
.setWhen(System.currentTimeMillis())
.setOngoing(false)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(BitmapFactory.decodeResource(service.getResources(), R.drawable.icon))
.setSound(alarmSound);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(1, notification);
}
private static PendingIntent getDefaultIntent(Service service) {
Intent intent = new Intent(service, AppActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return pendingIntent;
}
}
MainActivity setting in AndroidManifest.xml
<activity android:name="package.name.AppActivity" android:configChanges="orientation|screenSize" android:label="#string/app_name" android:launchMode="singleTask" android:screenOrientation="landscape" android:theme= "#android:style/Theme.NoTitleBar.Fullscreen" android:enabled="true" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
Please guide me what I am missing or doing wrong in this code. Many thanks.
I pass same id in padding intent and manager.notify(0, notification);
And use PendingIntent.getActivity instead of PendingIntent.getService
it works!
I got the problem you only cancel the current notification thats why Intent is not firing the activity Change your Pending intent
from
PendingIntent.FLAG_CANCEL_CURRENT);
to
PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);

Opening app on receiving notification Android 10 [duplicate]

I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity based on the answer of CommonsWare:
Intent i = new Intent(context, AlarmNotificationActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10...
Log.d("Debug", "This is android 10");
// Start the alert via full-screen intent.
PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String CHANNEL_ID = "my_channel_02";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.notification_channel_name_second),
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(startAlarmPendingIntent, true);
Log.d("Debug", "Try to load screen");
notificationManager.notify(0, builder.build());
}
The log shows that I am getting to the notify command but nothing happens. I am asking for USE_FULL_SCREEN_INTENT permission on the manifest so I should be able to use full-screen intents.
My app is useless now because of that issue. Does anyone know how to solve it?
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:
val pi = PendingIntent.getActivity(
appContext,
0,
Intent(appContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(pi, true)
val mgr = appContext.getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
mgr.createNotificationChannel(
NotificationChannel(
CHANNEL_WHATEVER,
"Whatever",
NotificationManager.IMPORTANCE_HIGH
)
)
}
mgr.notify(NOTIF_ID, builder.build())
You can use SYSTEM_ALERT_WINDOW to force launch activity window in android 10, refer to this settingsuperposition setting:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<activity
android:name=".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>
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
in launched app check permissions:
private void RequestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
} else {
//Permission Granted-System will work
}
}
}
you will can user intent as android older versions
public class OnBootReceiver extends BroadcastReceiver {
private static final String TAG = OnBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
try {
Intent activity = new Intent(context, MainActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
} catch (Exception e){
Log.d(TAG,e.getMessage()+"");
}
}
}
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
So you need to have a high-level notification and when the user clicks on the notification your activity will be opened notifications
public class UIExampleReceiver extends BroadcastReceiver {
public static final String TAG_NOTIFICATION = "NOTIFICATION_MESSAGE";
public static final String CHANNEL_ID = "channel_1111";
public static final int NOTIFICATION_ID = 111111;
private static final String TAG = "Receiver";
#Override
public void onReceive(Context context, Intent intent) {
try {
// If android 10 or higher
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
{
startActivityNotification(context,NOTIFICATION_ID,context.getResources().getString(R.string.open_app), context.getResources().getString(R.string.click_app));
}
else
{
// If lower than Android 10, we use the normal method ever.
Intent activity = new Intent(context, ExampleActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
}
} catch (Exception e)
{
Log.d(TAG,e.getMessage()+"");
}
}
// notification method to support opening activities on Android 10
public static void startActivityNotification(Context context, int notificationID,
String title, String message) {
NotificationManager mNotificationManager =
(NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Create GPSNotification builder
NotificationCompat.Builder mBuilder;
//Initialise ContentIntent
Intent ContentIntent = new Intent(context, ExampleActivity.class);
ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent ContentPendingIntent = PendingIntent.getActivity(context,
0,
ContentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setColor(context.getResources().getColor(R.color.colorPrimaryDark))
.setAutoCancel(true)
.setContentIntent(ContentPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
"Activity Opening Notification",
NotificationManager.IMPORTANCE_HIGH);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setDescription("Activity opening notification");
mBuilder.setChannelId(CHANNEL_ID);
Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
}
Objects.requireNonNull(mNotificationManager).notify(TAG_NOTIFICATION,notificationID,
mBuilder.build());
}
}

Can't start activity from BroadcastReceiver on android 10

I updated my OS version to android 10 last night, and since then the startActivity function inside the broadcast receiver is doing nothing. This is how I try to start the activity based on the answer of CommonsWare:
Intent i = new Intent(context, AlarmNotificationActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // This is at least android 10...
Log.d("Debug", "This is android 10");
// Start the alert via full-screen intent.
PendingIntent startAlarmPendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
String CHANNEL_ID = "my_channel_02";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
context.getString(R.string.notification_channel_name_second),
NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(startAlarmPendingIntent, true);
Log.d("Debug", "Try to load screen");
notificationManager.notify(0, builder.build());
}
The log shows that I am getting to the notify command but nothing happens. I am asking for USE_FULL_SCREEN_INTENT permission on the manifest so I should be able to use full-screen intents.
My app is useless now because of that issue. Does anyone know how to solve it?
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
Use a high-priority notification, with an associated full-screen Intent, instead. See the documentation. This sample app demonstrates this, by using WorkManager to trigger a background event needing to alert the user. There, I use a high-priority notification instead of starting the activity directly:
val pi = PendingIntent.getActivity(
appContext,
0,
Intent(appContext, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(appContext, CHANNEL_WHATEVER)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Um, hi!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setFullScreenIntent(pi, true)
val mgr = appContext.getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mgr.getNotificationChannel(CHANNEL_WHATEVER) == null
) {
mgr.createNotificationChannel(
NotificationChannel(
CHANNEL_WHATEVER,
"Whatever",
NotificationManager.IMPORTANCE_HIGH
)
)
}
mgr.notify(NOTIF_ID, builder.build())
You can use SYSTEM_ALERT_WINDOW to force launch activity window in android 10, refer to this settingsuperposition setting:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<activity
android:name=".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>
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
in launched app check permissions:
private void RequestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
} else {
//Permission Granted-System will work
}
}
}
you will can user intent as android older versions
public class OnBootReceiver extends BroadcastReceiver {
private static final String TAG = OnBootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
try {
Intent activity = new Intent(context, MainActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
} catch (Exception e){
Log.d(TAG,e.getMessage()+"");
}
}
}
Android 10's restriction on background activity starts was announced about six months ago. You can read more about it in the documentation.
So you need to have a high-level notification and when the user clicks on the notification your activity will be opened notifications
public class UIExampleReceiver extends BroadcastReceiver {
public static final String TAG_NOTIFICATION = "NOTIFICATION_MESSAGE";
public static final String CHANNEL_ID = "channel_1111";
public static final int NOTIFICATION_ID = 111111;
private static final String TAG = "Receiver";
#Override
public void onReceive(Context context, Intent intent) {
try {
// If android 10 or higher
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P)
{
startActivityNotification(context,NOTIFICATION_ID,context.getResources().getString(R.string.open_app), context.getResources().getString(R.string.click_app));
}
else
{
// If lower than Android 10, we use the normal method ever.
Intent activity = new Intent(context, ExampleActivity.class);
activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activity);
}
} catch (Exception e)
{
Log.d(TAG,e.getMessage()+"");
}
}
// notification method to support opening activities on Android 10
public static void startActivityNotification(Context context, int notificationID,
String title, String message) {
NotificationManager mNotificationManager =
(NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Create GPSNotification builder
NotificationCompat.Builder mBuilder;
//Initialise ContentIntent
Intent ContentIntent = new Intent(context, ExampleActivity.class);
ContentIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent ContentPendingIntent = PendingIntent.getActivity(context,
0,
ContentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setColor(context.getResources().getColor(R.color.colorPrimaryDark))
.setAutoCancel(true)
.setContentIntent(ContentPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID,
"Activity Opening Notification",
NotificationManager.IMPORTANCE_HIGH);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setDescription("Activity opening notification");
mBuilder.setChannelId(CHANNEL_ID);
Objects.requireNonNull(mNotificationManager).createNotificationChannel(mChannel);
}
Objects.requireNonNull(mNotificationManager).notify(TAG_NOTIFICATION,notificationID,
mBuilder.build());
}
}

Pending Intent opens wrong activity

I am using the FirebaseMessagingService for getting notifications and opening the app upon clickng the notification. But everytime i click the notification the app opens the MainActivity instead of the intended ResultActivity. I also followed docs from the PendingIntent docs and still does the same.
private void createNotification( String messageBody) {
Intent intent = new Intent( this , ResultActivity.class );
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
// PendingIntent resultPending = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
.setContentTitle("VERA")
.setContentText(messageBody)
.setAutoCancel( true )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
Here is my Manifest.
<activity
android:name=".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>
<activity android:name=".ResultActivity"
android:launchMode="singleTask"
android:excludeFromRecents="true"
android:taskAffinity=""></activity>
EDIT: I tried to pass some extra strings, but the main activity is not even receiving anything. Is it possible that the notif is only triggering its default method to launch the app?
Create an Intent that starts the Activity.
Set the Activity to start in a new, empty task by calling setFlags() with the flags FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK.
Create a PendingIntent by calling getActivity().
Like,
Intent notifyIntent = new Intent(this, ResultActivity.class);
// Set the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Create the PendingIntent
PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0,
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Then you can pass the PendingIntent to the notification as usual:
NotificationCompat.Builder mNotificationBuilder= new NotificationCompat.Builder(this, "CHANNEL_ID");
builder.setContentIntent(notifyPendingIntent);
...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, mNotificationBuilder.build());
Apparently there is no way to trigger the onMessageReceived by using the FCM console only. It will only be triggered if i use other ways to send data messages.

Clicking on Notification is not starting intended activity?

I am using GCM in my application and also using NotificationManager to Create a Notification whenever GCM message is received.Till now everything is working perfectly and GCM message is showing correctly in Notification area, but when I click on the notification it should start an activity of my application which will display the message detail which is not happening. Every-time I click on notification it does not start any activity and it remains as is.My code for creating Notification is :
private void sendNotification(String msg) {
SharedPreferences prefs = getSharedPreferences(
DataAccessServer.PREFS_NAME, MODE_PRIVATE);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, WarningDetails.class);
Bundle bundle = new Bundle();
bundle.putString("warning", msg);
bundle.putInt("warningId", NOTIFICATION_ID);
intent.putExtras(bundle);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(WarningDetails.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.weather_alert_notification)
.setContentTitle("Weather Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
String selectedSound = prefs.getString("selectedSound", "");
if (!selectedSound.equals("")) {
Uri alarmSound = Uri.parse(selectedSound);
mBuilder.setSound(alarmSound);
} else {
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
}
if (prefs.getBoolean("isVibrateOn", false)) {
long[] pattern = { 500, 500, 500, 500, 500, 500, 500, 500, 500 };
mBuilder.setVibrate(pattern);
}
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
I updated my code to support Preserving Navigation when Starting an Activity just like it happens in Gmail application using the Android developers website since then it stopped working.Someone Please guide me what I am missing or doing wrong in this code.
My problem got solved I just have to add PendingIntent.FLAG_ONE_SHOT flag as well , so I replaced :
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
to
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
I encountered the same issue and resolved it by adding android:exported="true" to the activity declaration in AndroidManifest.xml.
Here you just passed your Intent into pendingintent: see below
Intent notificationIntent = new Intent(context, Login.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
and set this contentintent into your Notification:
Notification noti = new NotificationCompat.Builder(context)
.setSmallIcon(icon_small)
.setTicker(message)
.setLargeIcon(largeIcon)
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setContentIntent(**contentIntent**)
.setAutoCancel(true).build();
This may help you.
if you launch the intended activity using Action String dont forget to add
<intent-filter>
<action android:name="YOUR ACTION STRING"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
inside <activity></activity> tag
The activity that you want to launch has to be designated as a LAUNCHER activity in your manifest - otherwise it won't launch via a Pending Intent. Add the following to your in the AndroidManifext.xml
<activity
...
android:exported="true">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Otherwise you will need to use an Activity that is already designated as a LAUNCHER (such as your MAIN activity)
Do some thing like this on generateNotification() method ..
Replace your activity with Splash.Java class in it.
/**
* Issues a notification to inform the user that server has sent a message.
*/
#SuppressWarnings("deprecation")
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
//message = "vivek";
// Log.d("anjan", message.split("~")[0]);
//Toast.makeText(context, message, Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Log.d("anjan1", title);
String text_message = context.getString(R.string.title_activity_main);
Log.d("anjan1", text_message);
Intent notificationIntent = new Intent(context, Splash.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Try this instead of the last line :
mNotificationManager.notify(0, mBuilder.getNotification());

Categories

Resources