How to add tap action on notification? - android

I want to add a tap action (exit (finish)) to a notification.
I'm making a simple app with several classes, and I want them all finished when I tap the notification.
Here is my notification code:
mMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n = new Notification();
n.icon = R.drawable.ic_launcher;
n.tickerText = "Tap this notification to exit";
n.when = System.currentTimeMillis();
Intent nid = new Intent(MainActivity.this, stopservice.class);
PendingIntent ci = PendingIntent.getActivity(this, 0, nid,PendingIntent.FLAG_UPDATE_CURRENT);
CharSequence ct = "TAP";
CharSequence tt = "Tap here to exit";
n.setLatestEventInfo(this,ct,tt,ci);
mMN.notify(NOTIFICATION_ID, n);
I'm making a reference to stopservice class (where it is my stop service code) on Intent nid, but I'm not quite sure if it's a correct reference.
hope that my question is clear.

You should be using a notification builder:
mMN = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent nid = new Intent(MainActivity.this, stopservice.class);
// If you were starting a service, you wouldn't using getActivity() here
PendingIntent ci = PendingIntent.getActivity(MainActivity.this, NOTIFICATION_ID, nid, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(MainActivity.this);
builder.setContentTitle("TAP")
.setContentText("Tap here to exit")
.setTicker("Tap this notification to exit")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(ci)
.setAutoCancel(true); // auto cancel means the notification will remove itself when pressed
mMN.notify(NOTIFICATION_ID, builder.getNotification());
Your code is set to launch the Activity "stopservice" (which technically should be "StopService" with naming conventions), are you sure that class is an Activity?
Also, make sure your Activity is registered in your app's manifest:
<activity android:name="[package-name].stopservice" android:label="#string/app_name"/>

Related

custom notification button click

In my application I have a notification to show.
Let's say when notification is show I want press 'Yes' to go an Activity and hide notification, press 'No' do nothing just hide notification.
I tried this code but instead of onclick is onClckPendingIntent and I can't do anything that I want.
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_push_layout);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(remoteViews)
.setAutoCancel(true);
Intent intent = new Intent(this,GPSTrackingActivity.class);
final Intent yesIntent = new Intent(intent);
final Intent noIntent = new Intent(this, GPSTrackingActivity.class);
TaskStackBuilder yesStackBuilder = TaskStackBuilder.create(this);
yesStackBuilder.addParentStack(MainActivity.class);
yesStackBuilder.addNextIntent(yesIntent);
TaskStackBuilder noStackBuilder = TaskStackBuilder.create(this);
noStackBuilder.addParentStack(MainActivity.class);
noStackBuilder.addNextIntent(noIntent);
PendingIntent yesPendingIntent = yesStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent noPendingIntent = noStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.btn_yes, yesPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.btn_no, noPendingIntent);
mNotificationManager.notify(100, mBuilder.build());
How could I do this ?
I know it's kinda late, but I managed to get things done via receiver.
you should:
create a receiver
create two intents to the receiver -
String SHOULD_OPEN = "should_open_intent"
Intent yes = new Intent(this, MyReceiver.class);
yes.putBooleanExtra(SHOULD_OPEN, true);
and same on Intent "no"
wrap them with PendingIntent
in you receiver, at the function "onReceive" get that data out using intent.getBooleanExtra(SHOUOLD_OPEN, DEFAULT_VALUE_DOESNT_MATTER)
and handle it accordingly
check this out -
https://stackoverflow.com/a/26486425/3339597

Resume an activity when clicked on a notification

I've made an app which manage sms, I've created the notifications but when I click on them it starts another activity, I would like to know how to check if an activity has been stopped and resume it.
Here is the code used to create the pendingintent:
private void createNotification(SmsMessage sms, Context context){
final NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String contentTitle = "";
// construct the Notification object.
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(contentTitle)
.setContentText(sms.getMessageBody())
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(getIconBitmap())
.setNumber(nmessages);
builder.setAutoCancel(true);
//(R.drawable.stat_sample, tickerText,
// System.currentTimeMillis());
// Set the info for the views that show in the notification panel.
//notif.setLatestEventInfo(this, from, message, contentIntent);
/*
// On tablets, the ticker shows the sender, the first line of the message,
// the photo of the person and the app icon. For our sample, we just show
// the same icon twice. If there is no sender, just pass an array of 1 Bitmap.
notif.tickerTitle = from;
notif.tickerSubtitle = message;
notif.tickerIcons = new Bitmap[2];
notif.tickerIcons[0] = getIconBitmap();;
notif.tickerIcons[1] = getIconBitmap();;
*/
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, BasicActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// Ritardo in millisecondi
builder.setContentIntent(resultPendingIntent);
nm.notify(R.drawable.ic_drawer, builder.build());
You need to set flags in your PendingIntent's ...like FLAG_UPDATE_CURRENT.
Here is all on it.
http://developer.android.com/reference/android/app/PendingIntent.html
Edit 1: I misunderstood the question.
Here are links to topics that had the same issue but are resolved:
resuming an activity from a notification
Notification Resume Activity
Intent to resume a previously paused activity (Called from a Notification)
Android: resume app from previous position
Please read the above answers for a full solution and let me know if it works.
Add this line to the corresponding activity in manifest file of your app.
android:launchMode="singleTask"
eg:
<activity
android:name=".Main_Activity"
android:label="#string/title_main_activity"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode="singleTask" />
Try with this.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(mContext.getString(R.string.notif_title))
.setContentText(mContext.getString(R.string.notif_msg));
mBuilder.setAutoCancel(true);
// Set notification sound
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
Intent resultIntent = mActivity.getIntent();
resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resultIntent.setAction(Intent.ACTION_MAIN);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
The only solution that actually worked for me after doing a lot of search is to do the following :
here you are simply launching of the application keeping the current stack:
//here you specify the notification properties
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).set...(...).set...(..);
//specifying an action and its category to be triggered once clicked on the notification
Intent resultIntent = new Intent(this, MainClass.class);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//building the notification
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
If the aforementioned solution didn't work, try to change the activity launch mode in your androidManifest.xml file from standard to singleTask.
<activity>
...
android:launchMode="singleTask
...
</activity>
This will prevent the activity from having multiple instances.

How to check if Activity start from notification

I have problem my MainActivity can be created by 3 ways:
1) standart launch App
2) from Service
3) from notification click.
How I can check when it starts from notification click?
Notification code:
private void createNotification()
{
Log.d("service createNotification",MainActivity.TAG);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(this,MainActivity.class);
intent.putExtra(AppNames.IS_NOTIFICATION_INTENT,true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(this.getString(R.string.notification_title))
.setContentText(this.getString(R.string.notification_text))
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher);
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(AppNames.APP_NOTIFICATION, builder.getNotification());
}
add
intent.putExtra("started_from","notification");
to the code that starts the intent from the notifications, and the same thing to the other startActivity calls just change the value, then inside your activity
String startedFrom = getIntent().getStringExtra("started_from");
for more refer to this question: How do I get extra data from intent on Android?

How to add a Dynamic image instead of notification icon in android?

I used below code for displaying notification in notification Bar.
it worked fine.
But i need to display notification icon dynamically that will come from web service.
How i can do?
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.image,"status message", System.currentTimeMillis());
Intent in = new Intent(Notify.this,CommentU.class);
PendingIntent pi = PendingIntent.getActivity(Notify.this, 0, in, 0);
note.setLatestEventInfo(Notify.this,"NotificationTitle", "You have a new Commentio", pi);
note.number = ++count;
note.vibrate = new long[] { 500l, 200l, 200l, 500l };
note.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTIFY_ME_ID, note);
Thanks in Advance.
I have one suggestion for you: you have to download that image which you want to show and then you can set that as bitmap: check below code. I have created one BITMAP.
its look link :
for this you have to add android-support-v4.jar
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification").setLargeIcon(BITMAP)
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, test.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(test.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFY_ME_ID, mBuilder.build());
for more detail chekc this link.
Removing notifications
Notifications remain visible until one of the following happens:
The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared).
The user clicks the notification, and you called setAutoCancel() when you created the notification.
You call cancel() for a specific notification ID. This method also deletes ongoing notifications.
You call cancelAll(), which removes all of the notifications you previously issued.
Edited: just replace this.
mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification").setLargeIcon(BITMAP)
.setAutoCancel(true)
.setContentText("Hello World!");
just add some icons in your resource folder and then
int myIcon = R.drawable.image;
your logic goes here ....
and change value of icon according to your logic like myIcon = R.drawable.somenewimage;
and then finally set your notification
Notification note = new Notification(myIcon,"status message", System.currentTimeMillis());

How to dismiss notification after action has been clicked

Since API level 16 (Jelly Bean), there is the possibility to add actions to a notification with
builder.addAction(iconId, title, intent);
But when I add an action to a notification and the action is pressed, the notification is not going to be dismissed.
When the notification itself is being clicked, it can be dismissed with
notification.flags = Notification.FLAG_AUTO_CANCEL;
or
builder.setAutoCancel(true);
But obviously, this has nothing to with the actions associated to the notification.
Any hints? Or is this not part of the API yet? I did not find anything.
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
Found this to be an issue when using Lollipop's Heads Up Display notification. See design guidelines. Here's the complete(ish) code to implement.
Until now, having a 'Dismiss' button was less important, but now it's more in your face.
Building the Notification
int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
.setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
.setSmallIcon(R.drawable.ic_action_refresh) // Required!
.setContentTitle("Message from test")
.setContentText("message")
.setAutoCancel(true)
.addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
.addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);
// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());
NotificationActivity
public class NotificationActivity extends Activity {
public static final String NOTIFICATION_ID = "NOTIFICATION_ID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
}
public static PendingIntent getDismissIntent(int notificationId, Context context) {
Intent intent = new Intent(context, NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(NOTIFICATION_ID, notificationId);
PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return dismissIntent;
}
}
AndroidManifest.xml (attributes required to prevent SystemUI from focusing to a back stack)
<activity
android:name=".NotificationActivity"
android:taskAffinity=""
android:excludeFromRecents="true">
</activity>
I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.
You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.
Also if you start a broadcast receiver from the button, the notification drawer doesn't close.
I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.
I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.
In new APIs don't forget about TAG:
notify(String tag, int id, Notification notification)
and correspondingly
cancel(String tag, int id)
instead of:
cancel(int id)
https://developer.android.com/reference/android/app/NotificationManager
In my opinion using a BroadcastReceiver is a cleaner way to cancel a Notification:
In AndroidManifest.xml:
<receiver
android:name=.NotificationCancelReceiver" >
<intent-filter android:priority="999" >
<action android:name="com.example.cancel" />
</intent-filter>
</receiver>
In java File:
Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action actions[] = new NotificationCompat.Action[1];
NotificationCancelReceiver
public class NotificationCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Cancel your ongoing Notification
};
}
You will need to run the following code after your intent is fired to remove the notification.
NotificationManagerCompat.from(this).cancel(null, notificationId);
NB: notificationId is the same id passed to run your notification
You can always cancel() the Notification from whatever is being invoked by the action (e.g., in onCreate() of the activity tied to the PendingIntent you supply to addAction()).
Just put this line :
builder.setAutoCancel(true);
And the full code is :
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
builder.setContentTitle("Notifications Title");
builder.setContentText("Your notification content here.");
builder.setSubText("Tap to view the website.");
Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder.setAutoCancel(true);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
Just for conclusion:
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Intent intent = new Intent(context, MyNotificationReceiver.class);
intent.putExtra("Notification_ID", 2022);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
...);
Notification notification = new NotificationCompat.Builder(...)
...
.addAction(0, "Button", pendingIntent)
.build();
notificationManager.notify(2022, notification);
and for dismiss the notification, you have two options:
approach 1: (in MyNotificationReceiver)
NotificationManager manager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
manager.cancel(intent.getIntExtra("Notification_ID", -1));
approach 2: (in MyNotificationReceiver)
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.cancel(intent.getIntExtra("Notification_ID", -1));
and finally in manifest:
<receiver android:name=".MyNotificationReceiver" />
builder.setAutoCancel(true);
Tested on Android 9 also.

Categories

Resources