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);
Related
I want to start a foreground notification from a service.Here is my code:
Manifest :
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
Broadcast Receiver :
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Charger connected (#)", Toast.LENGTH_SHORT).show();
Intent startIntent = new Intent(context, NotificationService.class);
startIntent.setAction("a_abhi_apps.batterychargenotifier.action.startforeground");
context.startService(startIntent);
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
Toast.makeText(context, "Charger disconnected (#)", Toast.LENGTH_SHORT).show();
stopIntent.setAction("a_abhi_apps.batterychargenotifier.action.stopforeground");
}
}
NotificationService.java :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.startforeground")) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Charging ")
.setContentText("Phone is charging");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.notify(0, builder.build());
startForeground(0, builder.build());
} else if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.stopforeground")) {
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
I have declared broadcast receiver in manifest as it receives power state changed.So there is no related code in MainActivity.
I have commented this line in NotificationService.java :
manager.notify(0, builder.build());
I get notification if i remove the comment.But i would like to make it stick to the notification space,so that i can use that service to perform some other actions.
But i am unable to make it as a foreground notification.
You have to change your notification id in startForeground(0, builder.build()).
You can't use 0 as your notification id.
From here:
The identifier for this notification as per NotificationManager.notify(int, Notification); must not be 0.
Try this
mNotificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder note = new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.name))
.setSmallIcon(R.drawable.quantum_ic_refresh_white_24);
note.setOnlyAlertOnce(true);
note.setOngoing(true);
note.setWhen( System.currentTimeMillis() );
note.setAutoCancel(false);
note.setContentText(getString(R.string.downloading_new_teachkits));
Notification notification = note.build();
mNotificationManager.notify(notifyID, notification );
You can follow below Code :-
private static int notification_id=1001;
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher3)
.setContentTitle(title)
.setContentText(DeviceName)
.setSubText(timestamp)
.setVisibility(visibility)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(vibrate)
.setOngoing(true)
.setFullScreenIntent(null, true);
Intent resultIntent = new Intent(this, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManagerCompat mNotificationManager = (NotificationManagerCompat) NotificationManagerCompat.from(this);
Notification notification = mBuilder.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(notification_id, notification);
startForeground (notification_id, notification)
notification_id = notification_id + 1;
Okay so what I am doing right now is getting a push notification through FCM that's been going well. Now I'm able to change the activity when application is on foreground, but how do I change it when I tap the notification in notification panel? Need help.
My Code:
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.mipmap.ic_launcher;
// on click activity for the notification !!!!!!!!!!
intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(mContext, TestActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long notificatioId = System.currentTimeMillis();
Intent intent = new Intent(getApplicationContext(), TestActivity.class); // Here pass your activity where you want to redirect.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, 0);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
currentapiVersion = R.mipmap.ic_notification_lolipop;
} else{
currentapiVersion = R.mipmap.ic_launcher;
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(currentapiVersion)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setContentIntent(contentIntent);
mNotificationManager.notify((int) notificatioId, notificationBuilder.build());
}
I have used in this manner to start a specific activity:
FireBaseMessagingService.java
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//The message will contain the Push Message
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
//title for the notification.
String title = remoteMessage.getData().get("title");
//action string to perform the action e.g. open activity
String action = remoteMessage.getData().get("click_action");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
//method for functioning the notification --->
sendNotification(message, title, bitmap, action);
}
private void sendNotification(String messageBody, String title, Bitmap image, String action) {
Intent intent = new Intent(this, SpecificActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("title", title);
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
intent.putExtra("img", image);
intent.putExtra("msg", messageBody);
intent.putExtra("click_action", action);
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, "Default")
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.mipmap.app_icon)
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_HIGH)
.setChannelId("Default")
.setVibrate(new long[]{1000, 1000})
.setContentIntent(pendingIntent);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
After this Add the following lines in the specificActivity.java part in the AndroidManifest.xml file:
<activity
android:name=".SpecificActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY" />
<!-- Add this OPEN_ACTIVITY string into your data payload while sending the notification from server side. -->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
After this get the intent in the specific activity you are starting i.e. SpecificActivity.java file's onCreate() method.
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet())
{
String value = getIntent().getExtras().getString(key);
if (key.equals("click_action")) {
//perform the action you want to do with the key.
}
After adding these you are good to check the notifications from your mobile end.
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(mContext,ACTIVITY_TO_BE_DISPLAYED.class); // Replace ACTIVITY_TO_BE_DISPLAYED to Activity to which you wanna show
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
.setAutoCancel(true)
.setTicker("YOUR_TICKER_MSG")
.setSmallIcon(R.drawable.ic_notification_icon)
.setLargeIcon(icon)
.setContentTitle("YOUR_TITLE")
.setContentText("YOUR_TEXT")
.setContentIntent(intent);
notificationManager.notify(10, builder.build());
<!-- MainActivity is the parent for ResultActivity -->
<activity
android:name=".ResultActivity"
/>
Dont forget to adjust Manifest with child activity declaration
Pass your Activity you want to open when clicked into Intent.
Intent notificationIntent = new Intent(context, XYZActivity.class);
complete code:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, XYZActivity.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);
I want to resume my app, exactly at where I left from notification icon in bar. Then I used this code:
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_speed)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.txt_welcome))
.setAutoCancel(true).setDefaults(Notification.DEFAULT_LIGHTS).setWhen(System.currentTimeMillis())
.setOngoing(true);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
It works well, the issue is when I press the icon in notification bar, it disappears, I need it to stay there.
Of course, if I delete these three lines:
resultIntent.setAction(Intent.ACTION_MAIN);
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in manifest.xml
<activity android:name=".MainActivity"
android:launchMode="singleInstance"
android:screenOrientation="portrait"/>
the icon won't disappear after clicking on it, but I always redirect to MainActivity, not the same place I left (when app got into pause).
any idea?
Try setting :
setAutoCancel(false)
Reference : https://developer.android.com/reference/android/app/Notification.Builder.html#setAutoCancel(boolean)
Hope it helps !
Edit :
As per discussion, need to set in manifest :
android:launchMode="singleTop"
This will deliver new intent to "onNewIntent" function which can be used to do further actions in case your activity was already running.
Notification should be onGoing
mBuilder.setOngoing(true); //this will make ongoing notification
Try this code..!
void notifyme(String string){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns);
int icon = R.drawable.notification_icon; // icon from resources
CharSequence tickerText = string + " Program Running..."; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context = getApplicationContext(); // application Context
CharSequence contentTitle = *********; // expanded message title
CharSequence contentText = string + " Program Running...";//expanded msg text
Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, notificationIntent, 0);
// the next two lines initialize the Notification, using the configurations
// above
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
After add this
final Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
please refer below example and please let me know if it is not working
private static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager = null;
private NotificationCompat.Builder mNotificationBuilder;
if (mNotificationManager == null) {
mNotificationManager = (android.app.NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
if (mNotificationBuilder == null) {
mNotificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.app_icon_96x96)
.setContentText(getContentString(false, 0))
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_MAX)
.setOngoing(true)
.setCategory(NOTIFICATION_SERVICE);
}
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());
I have a service running, and would like to send a notification. Too bad, the notification object requires a Context, like an Activity, and not a Service.
Do you know any way to by pass that ? I tried to create an Activity for each notification but it seems ugly, and I can't find a way to launch an Activity without any View.
Both Activity and Service actually extend Context so you can simply use this as your Context within your Service.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);
This type of Notification is deprecated as seen from documents:
#java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }
public Notification(android.os.Parcel parcel) { /* compiled code */ }
#java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }
Better way
You can send a notification like this:
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.
So if your minimum target API level is 4+ (Android 1.6+) use this:
import android.support.v4.app.NotificationCompat;
-------------
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mylogo)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification()
{
NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0);
//set
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.cal_icon);
builder.setContentText("Contents");
builder.setContentTitle("title");
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_ALL);
Notification notification = builder.build();
nm.notify((int)System.currentTimeMillis(),notification);
}
Well, I'm not sure if my solution is best practice. Using the NotificationBuilder my code looks like that:
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
Manifest:
<activity
android:name=".MainActivity"
android:launchMode="singleInstance"
</activity>
and here the Service:
<service
android:name=".services.ProtectionService"
android:launchMode="singleTask">
</service>
I don't know if there really is a singleTask at Service but this works properly at my application...
If none of these work, try getBaseContext(), instead of context or this.