I am trying to create a notification with a cancel button, but when I click on it nothing happens. This is my code:
private NotificationCompat.Builder notificationBuilder;
public void createNotification() {
notificationBuilder = new NotificationCompat.Builder(service);
notificationBuilder.setProgress(100, 0, false);
notificationBuilder.setAutoCancel(true);
Intent intent = OrderProcessingService_.intent(service).actionCancelUpload(basket.getPhotobook_id()).get();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setSmallIcon(R.drawable.ic_action_file_cloud_upload);
NotificationCompat.Action cancelAction = new NotificationCompat.Action(R.drawable.ic_action_navigation_close, service.getString(R.string.cancel_upload), pendingIntent);
notificationBuilder.setContentTitle(service.getString(R.string.notification_upload_title));
notificationBuilder.setContentText(service.getString(R.string.notification_uploading_subtext, Util.getTitle(basket.getPhotobook())));
notificationBuilder.addAction(cancelAction);
addBigPicture(notificationBuilder);
service.startForeground(1, notificationBuilder.build());
}
You will have to keep notification id and then call
NotificationManager nMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancel(notification );
I am glad to post it! After working all night I found something. So, here we go!
Create an xml layout file for your notification.
Create the notification using the Notification.Builder. After adding everything you want (icons, sounds, etc) do this:
//R.layout.notification_layout is from step 1
RemoteViews contentView=new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);
setListeners(contentView);//look at step 3
notification.contentView = contentView;
Create a method setListeners. Inside this method you have to write this:
//HelperActivity will be shown at step 4
Intent radio=new Intent(ctx, packagename.youractivity.class);
radio.putExtra("AN_ACTION", "do");//if necessary
PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
//R.id.radio is a button from the layout which is created at step 2
view.setOnClickPendingIntent(R.id.radio, pRadio);
//Follows exactly my code!
Intent volume=new Intent(ctx, tsapalos11598712.bill3050.shortcuts.helper.HelperActivity.class);
volume.putExtra("DO", "volume");
//HERE is the whole trick. Look at pVolume. I used 1 instead of 0.
PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
view.setOnClickPendingIntent(R.id.volume, pVolume);
For my requirements I used a HelperActivity which responds to the intents. But for you I don't think it is necessary.
If you want the full source code you can browse it or download it from my git repo. The code is for personal use, so don't expect to read a gorgeous code with a lot of comments. https://github.com/BILLyTheLiTTle/AndroidProject_Shortcuts
ALL THE ABOVE, ANSWERS THE QUESTION OF CATCHING EVENT FROM DIFFERENT BUTTONS.
About canceling the notification I redirect you here
How to clear a notification in Android
Just remember to use the id you parsed at the notify method when you called the notification for fist time
Source : Android notification with buttons on it
Related
I have an app which associates some entities with a unique ID and notifies about the entities to the user, which I'm gonna use notificationID to be the same as entity ID.
I have built a notification with a dismiss action based on the following sample solution exactly without any modification.
So far things are going well until I try to create 2 notifications with different ID using the sample.
A problem arises in that the dismiss button only receives the notificationID of the first notification:
The first notification behaves normally as expected.
But the second notification's getExtra() in BroadcastReceiver takes the notificationID of the FIRST notification instead and cancelling the notification just keeps cancelling the first notification.
My create Notification function, I just call this function twice with different IDs:
void createNoti(int NOTIFICATION_ID){
Intent buttonIntent = new Intent(context, ButtonReceiver.class);
buttonIntent.putExtra("notificationId", NOTIFICATION_ID);
PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);
NotificationCompat.Builder mb = new NotificationCompat.Builder(getBaseContext());
mb.addAction(R.drawable.ic_Action, "My Action", btPendingIntent);
manager.notify(NOTIFICATION_ID, mb.build());
}
BroadcastReceiver class:
public class ButtonReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
}
I believe the issue is in passing in 0 into PendingIntent:
PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, buttonIntent, 0);
I had the same issue until I started passing in the notification id as the 2nd argument; so instead of passing in 0, pass in the id of the notification:
PendingIntent btPendingIntent = PendingIntent.getActivity(getApplicationContext(), NOTIFICATION_ID, buttonIntent, 0);
After I made that change, I noticed that when clicking on individual notifications (especially notifications in a group) everything worked as intended.
I'm currently doing some notifications for my app. Now I've successfully created a notification but problem is that each of my notification doesn't pass different extras on click.
Well what happen is that I only have a loop that calls the createNotification method per loop and also I assign different ID's for those for the notification to appear in different stack.
here's my code:
private void createNotification(String record_name, String file_path, String status, int id) {
/*must pass:
* record_name, (get the record name in DB using the id create a new query method)
* record_status, (simple part just match if equivalent to ready to download for the JSON data then show notif if true)
* record_path *full path* (this one can be get using the record name itself add the path and extension name)*/
/*this will jump from the current activity into the target activity class just do some workarounds here*/
Intent intent = new Intent(this, RecordEditActivity.class);
intent.putExtra("record_name", record_name);
intent.putExtra("record_path", file_path);
intent.putExtra("record_status", status);
PendingIntent pIntent = PendingIntent.getActivity(this,0, intent, 0);
/*build the notification here this is only supported for API 11. Since we've targeted API 11 there will be no problem on this*/
NotificationCompat.Builder notify = new NotificationCompat.Builder(this)
.setContentTitle(record_name + " is ready for download")
.setContentText("Click to view or download recording")
.setAutoCancel(true)
.setSmallIcon(R.drawable.notif_icon)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher))
.setTicker("Echo: your file is ready for download")
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT<16){
/*build notification for HoneyComb to ICS*/
notificationManager.notify(id, notify.getNotification());
}if(Build.VERSION.SDK_INT>15){
/*Notification for Jellybean and above*/
notificationManager.notify(id, notify.build());
}
}
I think the problem is in the PendingIntent part since I don't know which flags should I use for this but I'm not that sure about it.
Got it! what needed is for me to assign an ID for my pendingIntent requestCode what I did is assign the same ID I used for my notificationManager.
More info here.
Just use this one line of code-
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
And for more detail see this answer:
GCM android Push Notification shows old message always. Intent received incorrect
I am trying to create a custom notification with the help of remote view with a button on it. I want to write onclick listener for this button but the problem is that the notification container is catching the touch event and button is not being clicked. My question is Is there any way to disable this notification and let the button to be clicked. My code is something like below:
Notification notification = new Notification(R.drawable.applogo,
"Apps activated", System.currentTimeMillis());
Intent notificationIntent = new Intent(getBaseContext(), AppsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(),
0, notificationIntent , 0);
notification.contentIntent = pendingIntent;
//Remoteview and intent for my button
RemoteViews remoteView = new RemoteViews(getBaseContext().getPackageName(),
R.layout.customnotification);
Intent mIntent = getPackageManager().getLaunchIntentForPackage(c.getString(1));//starting some application through package
PendingIntent pintent = PendingIntent.getActivity(this, 0,
mIntent, 0);
remoteView.setOnClickPendingIntent(R.id.button1,
pintent);
notification.contentView = remoteView;
notificationManager.notify(CUSTOM_NOTIFICATION_ID, notification);
I am working on api 7.
Thanks
Unfortunately, clickable buttons within notification layout available only with Custom notifications for API >= 11.
Also, for API >= 16 you can use Notification Actions to provide buttons within notification.
I have edited the code by using setOnClick pending intent, and this code works for ImageView and notifications text seperate as I want, but I still need some help.
I want to pause or play mediaplayer from my service class, so how could I access the stop or play method of service from Notification pending intent?
Some says broadcast receivers will help you, but I don't get exactly how it's going to work.
I have managed to open a web browser from the pause button from notification, but I don't know how to access service methods. Share any sample code if you have some.
#SuppressWarnings("deprecation")
void showNotification() {
int pendingRequestCode = 0;
int pendingFlag = 0;
final Resources res = getResources();
final NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pi= PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_search)
.setAutoCancel(true)
.setTicker("this is notification")
.setContentIntent(pi);
// Sets a custom content view for the notification, including an image button.
RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent clickIntent = new Intent(Intent.ACTION_VIEW, Uri_myBlog);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),pendingRequestCode, clickIntent, pendingFlag);
layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent);
builder.setContent(layout);
// Notifications in Android 3.0 now have a standard mechanism for displaying large
// bitmaps such as contact avatars. Here, we load an example image and resize it to the
// appropriate size for large bitmaps in notifications.
Bitmap largeIconTemp = BitmapFactory.decodeResource(res,
R.drawable.pause);
Bitmap largeIcon = Bitmap.createScaledBitmap(
largeIconTemp,
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
false);
largeIconTemp.recycle();
builder.setLargeIcon(largeIcon);
notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
}
PendingIntent getDialogPendingIntent(String dialogText) {
return PendingIntent.getActivity(
this,
dialogText.hashCode(), // Otherwise previous PendingIntents with the same
// requestCode may be overwritten.
new Intent(ACTION_DIALOG)
.putExtra(Intent.EXTRA_TEXT, dialogText)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
0);
}
You did not tell what version of Android you target, but in general it is not possible until Android 3.x (Honeycomb). So if you want that to happen on 2.x, then sorry - you are out of luck.
For Honeycomb, you simply have to provide a custom layout and assign PendingIntent to each button you need, by calling setOnClickPendingIntent(). If you got the SDK's samples downloaded, then see MainActivity of the HoneycombGallery app (shall be in your <SDK>\samples\android-XX\HoneycombGallery\ folder. XX is anything from 14 (or higher).
Check Bound Services using Messenger
http://developer.android.com/guide/components/bound-services.html
Also you can check this question
Binding to a local Service from a BroadcastReceiver
I'm trying to get my Notification to not cancel when the user presses "Clear All" So far I have the intent working properly on everything except this:
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.addFlags(Notification.FLAG_ONGOING_EVENT);
intent.addFlags(Notification.FLAG_NO_CLEAR);
PendingIntent contentIntent = PendingIntent.getActivity(
getBaseContext(), 0, intent, 0);
The question I have at this point is: Are my flags correct?
Yes, your flags look pretty much correct, although I don't know if you even need the FLAG_NO_CLEAR. I currently have an app which creates an ongoing (non-cancellable) notification - I only use the FLAG_ONGOING_EVENT and it works fine for me. I pretty much just copied it from a tutorial and then added the ongoing event flag.
Here's some sample code:
String text = "notification";
Notification notification = new Notification(R.drawable.icon, text,
System.currentTimeMillis());
//launch the activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent().setComponent(ComponentName.unflattenFromString("com.example/com.example.MyActivity")), 0);
// set the label and text...
notification.setLatestEventInfo(this, getText(R.string.notification_label),
text, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT;
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
NotificationManager mNM;
mNM.notify(R.string.notification_label, notification);