I have a GCMIntentService where I am setting details for the intent and all when the user clicks on the notification. My code snippet relevant to this is below:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, CustomTabActivity.class);
if (noteId != null && value != null) {
notificationIntent.putExtra("noteId", noteId);
notificationIntent.putExtra("value", value);
}
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification updateComplete = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(msg)
.setTicker(title)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon)
.build();
notificationManager.notify(100, updateComplete);
Whenever CustomTabActivity.class is opened, the getExtras() call is always null. Why is it that I am not able to get the values from intent?
I read the following for this and was not able to solve it:
Pass a String from one Activity to another Activity in Android
Android - how can I send a GCM push notification with instructions of which activity to load?
I found the bulk of the problem here. Turns out that since I had singleTop for the activity, the intent from getIntent() was the old one. This code works:
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getExtras() != null) {
String noteId = intent.getExtras().getString("noteId");
String value = intent.getExtras().getString("value");
}
}
onNewIntent gets called when the user clicks the notification.
Try This :
private static int count = 1;
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, (int)(Math.random() * 100), new Intent(),PendingIntent.FLAG_UPDATE_CURRENT);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, gcmData.getString("message"), when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.setLatestEventInfo(mContext, gcmData.getString("type"), intent.getExtras().getString("message"), contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(count, notification);
count = count + 1;
Related
Here is my Notification Builder :
public void CustomNotification() {
// Using RemoteViews to bind custom layouts into Notification
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.customnotification);
// Set Notification Title
String strtitle = getString(R.string.customnotificationtitle);
// Set Notification Text
String strtext = getString(R.string.customnotificationtext);
Intent intent = new Intent(this, Main2Activity.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// Set Icon
.setSmallIcon(R.mipmap.ic_launcher)
// Set Ticker Message
.setTicker(getString(R.string.customnotificationticker))
// Dismiss Notification
.setOngoing(true)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Set RemoteViews into Notification
.setContent(remoteViews);
// Locate and set the Images
remoteViews.setImageViewResource(R.id.imagenotileft, R.mipmap.ic_launcher);
remoteViews.setImageViewResource(R.id.imagenotiright, R.mipmap.ic_launcher);
remoteViews.setTextViewText(R.id.title, getString(R.string.customnotificationtitle));
remoteViews.setTextViewText(R.id.text, getString(R.string.customnotificationtext));
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
Now the question is :
Is it possible to launch homescreen (device home) when the notification is clicked (or the user is taken back to the homescreen when the notification is clicked) ? If yes, then How?
Hey use this code to this will solve your issue mention your Activity in pendingIntent.
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.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;
//notification.sound = Uri.parse(
"android.resource://"
+ context.getPackageName()
+ "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
here this the complete tutorial http://androidexample.com/Android_Push_Notifications_using_Google_Cloud_Messaging_GCM/index.php?view=article_discription&aid=119&aaid=139
I successfully created an activity which starts a service which by turn shows a notification like this
public int onStartCommand(Intent intent, int flags, int startId){
String notificationText = "working"
myNotification = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("test")
.setContentText(notificationText)
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
//FOLLOWING TECHNIQUE IS DEPRECATED
/* PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
myNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); */
myNotification.flags |= Notification.FLAG_NO_CLEAR;
myNotification.flags = Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(1, myNotification);
return START_STICKY;
}
I know there are other questions related to this one BUT they all use setLatestEventInfo which is deprecated
And this is what I call from another activity:
protected void beginBackgroundSer(){
intentService = new Intent(this, Service.class);
intentService.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.startService(intentService);
}
So what I'd like is to resume the activity whenever I click the notification by non-deprecated methods. Thank you very much for your help.
You can create a notification by using the following steps.
Create a notification id for the future reference to update the notification by notification manager.
// Notification ID to allow for future updates
private static final int MY_NOTIFICATION_ID = 1;
Create the text elements for the notification.
// Notification Text Elements
private final CharSequence tickerText = "This is a Really, Really, Super Long Notification Message!";
private final CharSequence contentTitle = "Notification";
private final CharSequence contentText = "You've Been Notified!";
Define the notification Action elements i.e. when the user clicks on the view in the notification drawer what action happens? We use intents for handling this.
// Notification Action Elements
private Intent mNotificationIntent;
private PendingIntent mContentIntent;
You can also define sound and vibration for this notification.
// Notification Sound and Vibration on Arrival
private Uri soundURI = Uri
.parse("android.resource://com.examples.Notification.StatusBarWithCustomView/"
+ R.raw.alarm_rooster);
private long[] mVibratePattern = { 0, 200, 200, 300 };
Create the notification using the Notification.Builder class. Do this in your onCreate()
mNotificationIntent = new Intent(getApplicationContext(),
YourActivity.class);
mContentIntent = PendingIntent.getActivity(getApplicationContext(), 0,
mNotificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Build the Notification
Notification.Builder notificationBuilder = new Notification.Builder(
getApplicationContext())
.setTicker(tickerText)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setAutoCancel(true)
.setContentIntent(mContentIntent)
.setSound(soundURI)
.setVibrate(mVibratePattern)
.setContent(mContentView);
// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
From the documentations
public NotificationCompat.Builder setContentIntent (PendingIntent intent) - Supply a PendingIntent to send when the notification is clicked. If you do not supply an intent, you can now add PendingIntents to individual views to be launched when clicked by calling RemoteViews.setOnClickPendingIntent(int,PendingIntent). Be sure to read Notification.contentIntent for how to correctly use this.
So you can use setContentIntent(PendingIntent intent) method something like
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
myNotification = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("test")
.setContentText(notificationText)
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(contentIntent) //added this new line
.build();
notificationManager.notify(1, myNotification);
In my notification, I want to start current activity when click in pending intent. In google, many ways found and I tried many times, it didn't work. here is my code,
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
String startTime = intent.getStringExtra("Strar_time");
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
long when = System.currentTimeMillis(); // notification time
Notification notification = new Notification(R.drawable.ic_launcher, "reminder", when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= notification.FLAG_AUTO_CANCEL;
notification.vibrate = new long[]{100, 200, 100, 500};
notification.defaults = Notification.DEFAULT_ALL;
Intent notificationIntent = new Intent(this, Goo.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP/* | Intent.FLAG_ACTIVITY_SINGLE_TOP*/);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent , 0);
notification.setLatestEventInfo(getApplicationContext(), "It's about time", "Your time is "+startTime, contentIntent);
notification.contentIntent=contentIntent;
nm.notify(NOTIF_ID, notification);
NOTIF_ID++;
Log.i("NotiID",NOTIF_ID+"");
}
Try this function given below,
private static void generateNotification(Context context, String message) {
int icon = R.drawable.launch_icon;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = null;
notificationIntent = new Intent(context, Main.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
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);
}
Only one working way I found so far is to make a dummy activity, start it and finish it in onRusume(). However this technique only bring application to front and do not start application when it is closed.
Then I used following workaround to bring application on front if it is alive in background otherwise start it.
Manifest:
<application>
.
.
.
<activity
android:name=".DummyActivity"
/>
.
.
</application>
In code:
public class DummyActivity{
public static boolean isAppAlive;
#Override
protected void onResume() {
// start application if it is not alive
if(!isAppAlive){
PackageManager pmi = getPackageManager();
Intent intent = pmi.getLaunchIntentForPackage(Your applications package name);
if (intent != null){
startActivity(intent);
}
}
finish();
}
In your main activity's onCreateMethod.
#Override
public void onCreate(Bundle savedInstanceState) {
DummyActivity.isAppAlive = true;
}
It is obvious that when your application is fully closed, isAppAlive will restore to its default value which is false. Thus application will be start.
I wanted to create something like an instant messaging application. How do I display multiple messages all in one notification? I can create a notification that appear when user receive a single notification. But when the user receive more than one message how can I update the notification with the previous message? Should I save the messages into a database and display it out if the user did not cancel the notification? Or is there any other way that I can handle this?
Below is my notification code.
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, "IMTest- A new event is created" , when);
Intent notificationIntent = new Intent(context, IM_Chat.class);
notificationIntent.putExtra("topicId", topicId);
notificationIntent.putExtra("sender", sender);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 1, notificationIntent, Intent.FLAG_ACTIVITY_MULTIPLE_TASK | PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, topicName, "A new event ["+eventName+"] is added in "+topicName, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.ledARGB |= 0xff0000ff;
notification.ledOffMS |= 1000;
notification.ledOnMS |= 300;
notificationManager.notify(CommunitiesappConstant.NOTIFICATION_ID, notification);
You can update notification using same id and builder
http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Updating
private NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
private mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Different Id's will show up as different notifications
private int mNotificationId = 1;
//Some things we only have to set the first time.
private boolean firstTime = true;
private updateNotification(String message, int progress) {
if (firstTime) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("My Notification")
.setOnlyAlertOnce(true);
firstTime = false;
}
mBuilder.setContentText(message)
.setProgress(100, progress, true);
mNotificationManager.notify(mNotificationId, mBuilder.build());
}
I want to put an icon in the status bar when ever my application is running, including when it is running in the background. How can I do this?
You should be able to do this with Notification and the NotificationManager. However getting a guaranteed way to know when your application is not running is the hard part.
You can get the basic functionality of what you are desiring by doing something like:
Notification notification = new Notification(R.drawable.your_app_icon,
R.string.name_of_your_app,
System.currentTimeMillis());
notification.flags |= Notification.FLAG_NO_CLEAR
| Notification.FLAG_ONGOING_EVENT;
NotificationManager notifier = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notifier.notify(1, notification);
This code must be somewhere where you are sure will get fired when your application starts. Possibly in your application's custom Application Object's onCreate() method.
However after that things are tricky. The killing of the application can happen at anytime. So you can try to put something in the onTerminate() of the Application class too, but it's not guaranteed to be called.
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
will be what is needed to remove the icon.
For new API you can use NotificationCompat.Builder -
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title");
Intent resultIntent = new Intent(this, MyActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(NOTIFICATION_ID, notification);
It will show as long as your application is running and someone manually closes your application. You can always cancel your notification by calling -
mNotifyMgr.cancel(NOTIFICATION_ID);
Take a look at the Dev Guide "Creating Status Bar Notifications".
One way to achieve the goal of keeping the icon there only when the application is running is to initialize the notification in onCreate() and call cancel(int) in your onPause() method only if isFinishing() returns true.
An example:
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notificationManager.notify(NOTIFICATION_EX, notification);
}
#Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
notificationManager.cancel(NOTIFICATION_EX);
}
}
It really works.
I created a method out of the example above:
private void applyStatusBar(String iconTitle, int notificationId) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(iconTitle);
Intent resultIntent = new Intent(this, ActMain.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notification);}
It should be called like: applyStatusBar("Statusbar Test", 10);