Clicking on Notification in background not open my App? - android

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);

Related

Click on notification not launching the app

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

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.

background service to send a notification and when the user clicks the notification it must launch the appropriate activity

I am developing a small app in which I want a background service to send a notification and when the user clicks the notification it must launch the appropriate activity. I am posting the code here for the notification and my problem is that the notification gets displayed on the status bar but when i click it it does not launch the required activity(instead it is launching the mainactivity). Can somebody suggest where I am going wrong. Please help.
Intent intent = new Intent(this, IncidentDetail.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getService(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
//here i tried with both getService and getActivity
/*PendingIntent pendingIntent = PendingIntent.getActivity(this,0
, intent,PendingIntent.FLAG_UPDATE_CURRENT);*/
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
;
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Below is my manifest file
<service android:name=".MyFirebaseMessagingService" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".IncidentDetail"
android:label="#string/title_activity_incident_detail"
android:exported="true"
android:launchMode="singleTop">
</activity>
Problem in this line.
PendingIntent pendingIntent = PendingIntent.getService(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
It shoule be.
PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* Request code */
, intent,PendingIntent.FLAG_UPDATE_CURRENT);
Cause Intent is calling an activity not a service .

Open activity when GCM notification was clicked

I'm making a gcm application, and now I can receive the notification
But when I click the notification, it just open the app.
I need to open another activity instead of Mainactivity
is there any way to do this?
final Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.set...;
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Please read this for detail about creating a Notification http://developer.android.com/guide/topics/ui/notifiers/notifications.html.
Depend on http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse, there are two general situations of starting Activity from your notification – Regular activity and Special activity.
Methods below are the example of start 2 type of Activity:
Regular activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = null;
ComponentName componentName = intent.getComponent();
if (componentName != null) {
// 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) <== This comment must be wrong!
stackBuilder.addParentStack(componentName);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
resultPendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE_START_ACTIVITY, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
} else {
resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
}
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Usage :
Intent intent = new Intent(this, SignInActivity_.class);
sendNotification(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title, message, intent);
The manifest XML should look like this
<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=".SignInActivity_"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Special activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Note:
Because I use setDefaults(DEFAULT_ALL), the vibrate permission is require <uses-permission android:name="android.permission.VIBRATE" />
Yes, it's possible. You must set the "exported" flag of the activity in the manifest.xml to true.
Hope it helps.
Use this:
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(context,YourActivity.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0);
Notification notification;
if (Build.VERSION.SDK_INT < 11) {
notification = new Notification(icon, "Title", when);
notification.setLatestEventInfo(
context,
"Title",
"Text",
pending);
} else {
notification = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText(
"Text").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pending).setWhen(when).setAutoCancel(true)
.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
nm.notify(0, notification);

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