I am working on an app where I have a service that should always run in the background. This service is responsible for a Notification bar that should always be visible. The notification bar has 2 buttons, where the 1st one is for grabbing some data and storing it and the 2nd one should open an activity that will show all the data. I encountered a problem where when I close the application and then press the notification button that starts an activity after that activity starts, my notification buttons stop responding. Note that both buttons work fine before the point where the 2nd button click starts the activity.
Here is a template code for my notification service and for notification bar button handler
service that handles the Notification bar
public class NotificationBarService extends Service {
private int notificationID;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
notificationID = new Random().nextInt();
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
contentView.setTextViewText(R.id.title, "Custom notification");
contentView.setTextViewText(R.id.text, "This is a custom layout");
//Handle the button for showing bookmarks on custom notification
Intent buttonsIntent2 = new Intent(this, NotificationBarButtonActivityHandler.class);
buttonsIntent2.putExtra(PENDING_ACTION, SHOW_BOOKMARKS);
contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, PendingIntent.getActivity(this, 0, buttonsIntent2, 0));
//Handle the button for adding bookmark on custom notification
Intent buttonsIntent = new Intent(this, NotificationBarButtonActivityHandler.class);
buttonsIntent.putExtra(PENDING_ACTION, REGISTER_BOOKMARK);
contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, PendingIntent.getActivity(this, 1, buttonsIntent, 0));
RemoteViews notificationView = new RemoteViews(getPackageName(),
R.layout.custom_notification);
Intent switchIntent = new Intent(this, NotificationBarService.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0,
switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton,
pendingSwitchIntent);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setContent(contentView)
.setSmallIcon(R.drawable.notification_small_icon)
.setOngoing(true);
Notification notification = mBuilder.build();
startForeground(notificationID, notification);
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
stopForeground(true);
}
}
Class that handles the button press on Notification bar
public class NotificationBarButtonActivityHandler extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String action = (String) getIntent().getExtras().get(NotificationBarService.PENDING_ACTION);
if (action != null) {
if (action.equals(NotificationBarService.REGISTER_BOOKMARK)){
CustomLogger.log("---------------- BUTTON FOR COLLECT DATA WAS PRESSED!!!");
//Does something here
}
else if(action.equals(NotificationBarService.SHOW_BOOKMARKS)){
CustomLogger.log("---------------- BUTTON FOR SHOW DATA WAS PRESSSED!!!");
//Notification bar buttons start not responding right after
//this is executed. Note that this problem only occurs if I close the app
//and press the notification button to execute this code.
//Otherwise this works just fine.
Intent intent2;
intent2 = new Intent(this, BookmarkDisplayActivity.class);
startActivity(intent2);
}
}
finish();
}
}
So basically if I close the application and remove the code that starts the activity, both buttons work as expected but as soon as I start the activity, both buttons stop working.
Ok, I finally solved the issue that I was having with changing the way that I handle button presses. This is what I got now and it works as expected.
In NotificationBarService this is how I handle the listeners for the buttons
Intent addBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
addBookmarkIntent.setAction(ADD_BOOKMARK_ACTION);
PendingIntent pendingAddBookmarkIntent = PendingIntent.getBroadcast(this, 0, addBookmarkIntent, 0);
contentView.setOnClickPendingIntent(R.id.notificationBarAddBookmarkFromChromeButton, pendingAddBookmarkIntent);
Intent showBookmarkIntent = new Intent(this, NotificationBarButtonListener.class);
showBookmarkIntent.setAction(SHOW_BOOKMARK_ACTION);
PendingIntent pendingShowBookmarkIntent = PendingIntent.getBroadcast(this, 0, showBookmarkIntent, 0);
contentView.setOnClickPendingIntent(R.id.notificationBarShowBookmarksButton, pendingShowBookmarkIntent);
and then I receive a broadcast even and handle it like this
public static class NotificationBarButtonListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(ADD_BOOKMARK_ACTION)){
CustomLogger.log("---------------- BUTTON FOR REGISTER BOOKMARK WAS PRESSED!!! ");
}
else if(action.equals(SHOW_BOOKMARK_ACTION)){
CustomLogger.log("---------------- BUTTON FOR SHOW BOOKMARK WAS PRESSSED!!!");
}
}
}
Note that this required me to add the following line to my manifest
<receiver android:name=".NotificationBarService$NotificationBarButtonListener"/>
Related
I have a notification that, when I click on it, opens up my app. But my app opens up in the background and the notification drawer is still visible. My notification itself is canceled and removed, but the drawer still exists on top of everything.
The notification class looks like this:
public MyNotification(final Context context) {
this.context = context;
remoteView = new RemoteViews(context.getPackageName(), R.layout.notification);
notification = new Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.build();
notification.flags = Notification.FLAG_NO_CLEAR;
notification.priority = Notification.PRIORITY_MAX;
remoteView.setOnClickPendingIntent(R.id.container, getIntent(ACTION_OPEN_APP));
notification.bigContentView = remoteView;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, notification);
}
private PendingIntent getIntent(String action) {
Intent receiveIntent = new Intent(context, NotificationReceiver.class);
receiveIntent.setAction(action);
return PendingIntent.getBroadcast(context, 0, receiveIntent, 0);
}
And my receiver looks like this:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equalsIgnoreCase(AudioPlayerNotification.ACTION_OPEN_APP)) {
Intent openAppIntent = new Intent(context, MyActivity.class);
openAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(openAppIntent);
}
}
I also have a base Activity that removes the notification when launching the activity. What am I missing?
Prathibhas suggested solution did not the trick, but pointed me in the right direction. The trick was to send the broadcast
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
since I'm using a broadcast receiver for the actions on the notification. The answer was provided here:
Clicking Android Notification Actions does not close Notification drawer
how to set notification with play/pause, next and previous button in android.!
I am new with Android & also at stack overflow. So please bear with me.
I set notification when song is start to play like below :
`
#SuppressLint("NewApi")
public void setNotification(String songName){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.god_img, null, System.currentTimeMillis());
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_mediacontroller);
//the intent that is started when the notification is clicked (works)
Intent notificationIntent = new Intent(this, AudioBookListActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentView = notificationView;
notification.contentIntent = pendingNotificationIntent;
notification.flags |= Notification.FLAG_NO_CLEAR;
//this is the intent that is supposed to be called when the button is clicked
Intent switchIntent = new Intent(this, AudioPlayerBroadcastReceiver.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
notificationManager.notify(1, notification);
}
`
I have create BroadcastReceiver like below :
`
private class AudioPlayerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("intent action = " + action);
long id = intent.getLongExtra("id", -1);
if(Constant.PLAY_ALBUM.equals(action)) {
//playAlbum(id);
} else if(Constant.QUEUE_ALBUM.equals(action)) {
//queueAlbum(id);
} else if(Constant.PLAY_TRACK.equals(action)) {
//playTrack(id);
} else if(Constant.QUEUE_TRACK.equals(action)) {
//queueTrack(id);
} else if(Constant.PLAY_PAUSE_TRACK.equals(action)) {
// playPauseTrack();
System.out.println("press play");
} else if(Constant.HIDE_PLAYER.equals(action)) {
// hideNotification();
System.out.println("press next");
}
else {
}
}
}`
Now, I set custom notification successfully but how can i handle notification buttons and its events like play/pause, previous and next... etc. I also try using broadcast receiver but could not get any response.
Seeking solution and guidance from experts, please help me out.
Thanks in advance.
You need to set a custom intent action, not the AudioPlayerBroadcastReceiver component class.
Create a Intent with custom action name like this
Intent switchIntent = new Intent("com.example.app.ACTION_PLAY");
Then, register the PendingIntent Broadcast receiver
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 100, switchIntent, 0);
Then, set a onClick for the play control , do similar custom action for other controls if required.
notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
Next,Register the custom action in AudioPlayerBroadcastReceiver like this
<receiver android:name="com.example.app.AudioPlayerBroadcastReceiver" >
<intent-filter>
<action android:name="com.example.app.ACTION_PLAY" />
</intent-filter>
</receiver>
Finally, when play is clicked on Notification RemoteViews layout, you will receive the play action by the BroadcastReceiver
public class AudioPlayerBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){
// do your stuff to play action;
}
}
}
EDIT: how to set the intent filter for Broadcast receiver registered in code
You can also set the Custom Action through Intent filter from code for the registered Broadcast receiver like this
// instance of custom broadcast receiver
CustomReceiver broadcastReceiver = new CustomReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("com.example.app.ACTION_PLAY");
// register the receiver
registerReceiver(broadcastReceiver, intentFilter);
Problem
When the user presses Send "Button 1"(scroll down to see the construction of the app) a new Notification is created from the RefreshService. If the user presses this notification a MainActivity instance gets started and receives a String with the value Button 1 over the Intent.
This value gets displayed.
When the user presses now the Send "Button 2" a new Notification is created from the RefreshService. If the user presses this notification a MainActivity instance gets started and receives a String ALSO with the value Button 1 over the Intent.
So as you can guess, normally there should be the value Button 2.
When the first Button the user pressed was Send "Button 2" then there would allways Button 2 be sent.
The only sollution to get the value of the second button is to restart the phone and pressing the second button first. Even force close doesn't work.
I know that I also can change the UI in another way. But I need this approach in a app where I need to restart the 'MainActivity' with another Intent so the approach should be the same.
Construction
A Activity called MainActivity
A IntentService called RefreshService
MainActivity
public class MainActivity extends Activity implements View.OnClickListener {
public static final String RECEIVED = "received";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView)findViewById(R.id.textView_received)).setText(getIntent().getStringExtra(RECEIVED));
findViewById(R.id.button_1).setOnClickListener(this);
findViewById(R.id.button_2).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, RefreshService.class);
if(v.getId() == R.id.button_1){
intent.putExtra(RECEIVED, "Button 1");
Toast.makeText(this,"Sent \"Button 1\"",Toast.LENGTH_LONG).show();
}
else if(v.getId() == R.id.button_2){
intent.putExtra(RECEIVED, "Button 2");
Toast.makeText(this,"Sent \"Button 2\"",Toast.LENGTH_LONG).show();
}
startService(intent);
}
}
RefreshService
public class RefreshService extends IntentService {
public RefreshService() {
super("RefreshService");
}
#Override
protected void onHandleIntent(Intent intent) {
String received = intent.getStringExtra(MainActivity.RECEIVED);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra(MainActivity.RECEIVED, received);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle("IntentServiceRefresh").setContentText(received).setSmallIcon(R.drawable.ic_notification_small).setContentIntent(pendingIntent);
Notification notification = builder.build();
// Hide the notification after it's selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
App Layout
My suspicion is that, since the only thing changing in the Intent is the extras, the PendingIntent.getActivity(...) factory method is simply re-using the old intent as an optimization.
In RefreshService, try:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
See:
http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT
I'm using an android notification to alert the user once a service is finished (success or failure), and I want to delete local files once the process is done.
My problem is that in the event of failure - I want to let the user a "retry" option. and if he chooses not to retry and to dismiss the notification I want to delete local files saved for the process purposes (images...).
Is there a way to catch the notification's swipe-to-dismiss event?
DeleteIntent:
DeleteIntent is a PendingIntent object that can be associated with a notification and gets fired when the notification gets deleted, ether by :
User specific action
User Delete all the notifications.
You can set the Pending Intent to a broadcast Receiver and then perform any action you want.
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
Builder builder = new Notification.Builder(this):
..... code for your notification
builder.setDeleteIntent(pendingIntent);
MyBroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
.... code to handle cancel
}
}
A fully flushed out answer (with thanks to Mr. Me for the answer):
1) Create a receiver to handle the swipe-to-dismiss event:
public class NotificationDismissedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getExtras().getInt("com.my.app.notificationId");
/* Your code to handle the event here */
}
}
2) Add an entry to your manifest:
<receiver
android:name="com.my.app.receiver.NotificationDismissedReceiver"
android:exported="false" >
</receiver>
3) Create the pending intent using a unique id for the pending intent (the notification id is used here) as without this the same extras will be reused for each dismissal event:
private PendingIntent createOnDismissedIntent(Context context, int notificationId) {
Intent intent = new Intent(context, NotificationDismissedReceiver.class);
intent.putExtra("com.my.app.notificationId", notificationId);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context.getApplicationContext(),
notificationId, intent, 0);
return pendingIntent;
}
4) Build your notification:
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle("My App")
.setContentText("hello world")
.setWhen(notificationTime)
.setDeleteIntent(createOnDismissedIntent(context, notificationId))
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notification);
Another Idea:
if you create a notification normally you also need the actions one, two or 3 of them. I've created a "NotifyManager" it creates all notifications i need and also receive all Intent calls.
So i can manage all the actions AND also the catch the dismiss event at ONE place.
public class NotifyPerformService extends IntentService {
#Inject NotificationManager notificationManager;
public NotifyPerformService() {
super("NotifyService");
...//some Dagger stuff
}
#Override
public void onHandleIntent(Intent intent) {
notificationManager.performNotifyCall(intent);
}
to create the deleteIntent use this (in the NotificationManager):
private PendingIntent createOnDismissedIntent(Context context) {
Intent intent = new Intent(context, NotifyPerformMailService.class).setAction("ACTION_NOTIFY_DELETED");
PendingIntent pendingIntent = PendingIntent.getService(context, SOME_NOTIFY_DELETED_ID, intent, 0);
return pendingIntent;
}
and THAT i use to set the delete Intent like this (in the NotificationManager):
private NotificationCompat.Builder setNotificationStandardValues(Context context, long when){
String subText = "some string";
NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext());
builder
.setLights(ContextUtils.getResourceColor(R.color.primary) , 1800, 3500) //Set the argb value that you would like the LED on the device to blink, as well as the rate
.setAutoCancel(true) //Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
.setWhen(when) //Set the time that the event occurred. Notifications in the panel are sorted by this time.
.setVibrate(new long[]{1000, 1000}) //Set the vibration pattern to use.
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.ic_white_24dp)
.setGroup(NOTIFY_GROUP)
.setContentInfo(subText)
.setDeleteIntent(createOnDismissedIntent(context))
;
return builder;
}
and finally in the same NotificationManager is the perform function:
public void performNotifyCall(Intent intent) {
String action = intent.getAction();
boolean success = false;
if(action.equals(ACTION_DELETE)) {
success = delete(...);
}
if(action.equals(ACTION_SHOW)) {
success = showDetails(...);
}
if(action.equals("ACTION_NOTIFY_DELETED")) {
success = true;
}
if(success == false){
return;
}
//some cleaning stuff
}
I have a custom notification with a button. To set the notification and use the event OnClick on my button I've used this code:
//Notification and intent of the notification
Notification notification = new Notification(R.drawable.stat_notify_missed_call,
"Custom Notification", System.currentTimeMillis());
Intent mainIntent = new Intent(getBaseContext(), NotificationActivity.class);
PendingIntent pendingMainIntent = PendingIntent.getActivity(getBaseContext(),
0, mainIntent , 0);
notification.contentIntent = pendingMainIntent;
//Remoteview and intent for my button
RemoteViews notificationView = new RemoteViews(getBaseContext().getPackageName(),
R.layout.remote_view_layout);
Intent activityIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:190"));
PendingIntent pendingLaunchIntent = PendingIntent.getActivity(getBaseContext(), 0,
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationView.setOnClickPendingIntent(R.id.button1,
pendingLaunchIntent);
notification.contentView = notificationView;
notificationManager.notify(CUSTOM_NOTIFICATION_ID, notification);
With this code I've a custom notification with my custom layout...but I can't click the button! every time I try to click the button I click the entire notification and so the script launch the "mainIntent" instead of "activityIntent".
I have read in internet that this code doesn't work on all terminals. I have tried it on the emulator and on an HTC Magic but I have always the same problem: I can't click the button!
My code is right? someone can help me?
Thanks,
Simone
I am writing code in my MyActivity.java class that extends android.app.Activity
It creates a custom notification, when user click on the button it sends a broadcast.
There is a broadcast receiver that receives the broadcast.
private void createDownloadNotification() {
Intent closeButton = new Intent("Download_Cancelled");
closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, closeButton, 0);
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.widget_update_notification);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setTicker("Ticker Text").setContent(notificationView);
notificationView.setProgressBar(R.id.pb_progress, 100, 12, false);
notificationView.setOnClickPendingIntent(R.id.btn_close, pendingSwitchIntent);
notificationManager.notify(1, builder.build());
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Received Cancelled Event");
}
}
Register receiver in AndroidManifest.xml
<receiver android:name=".MainActivity$DownloadCancelReceiver" android:exported="false">
<intent-filter>
<action android:name="Download_Cancelled" />
</intent-filter>
</receiver>
Since it is inner class so have to use $ sign
Widget xml is here
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close Me" />
<ProgressBar
android:id="#+id/pb_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
check this out
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
it seems that setOnClickPendingIntent doesn't work when used inside collections.
So try setPendingIntentTemplate instead of setOnClickPendingIntent. for more information bellow android developer link...
Click here for More Detail - Goto Android Developer Site.
You need to create Service to detect on Click event: For example Create NotificationIntentService.class and put below code:
public class NotificationIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public NotificationIntentService() {
super("notificationIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
switch (intent.getAction()) {
case "left":
android.os.Handler leftHandler = new android.os.Handler(Looper.getMainLooper());
leftHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(),
"You clicked the left button", Toast.LENGTH_LONG).show();
}
});
break;
case "right":
android.os.Handler rightHandler = new android.os.Handler(Looper.getMainLooper());
rightHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "You clicked the right button", Toast.LENGTH_LONG).show();
}
});
break;
}
}
}
Add this metod to your activity:
private void sendNotification() {
RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.view_expanded_notification);
expandedView.setTextViewText(R.id.timestamp, DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
expandedView.setTextViewText(R.id.notification_message, mEditText.getText());
// adding action to left button
Intent leftIntent = new Intent(this, NotificationIntentService.class);
leftIntent.setAction("left");
expandedView.setOnClickPendingIntent(R.id.left_button, PendingIntent.getService(this, 0, leftIntent, PendingIntent.FLAG_UPDATE_CURRENT));
// adding action to right button
Intent rightIntent = new Intent(this, NotificationIntentService.class);
rightIntent.setAction("right");
expandedView.setOnClickPendingIntent(R.id.right_button, PendingIntent.getService(this, 1, rightIntent, PendingIntent.FLAG_UPDATE_CURRENT));
RemoteViews collapsedView = new RemoteViews(getPackageName(), R.layout.view_collapsed_notification);
collapsedView.setTextViewText(R.id.timestamp, DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// these are the three things a NotificationCompat.Builder object requires at a minimum
.setSmallIcon(R.drawable.ic_pawprint)
.setContentTitle(NOTIFICATION_TITLE)
.setContentText(CONTENT_TEXT)
// notification will be dismissed when tapped
.setAutoCancel(true)
// tapping notification will open MainActivity
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0))
// setting the custom collapsed and expanded views
.setCustomContentView(collapsedView)
.setCustomBigContentView(expandedView)
// setting style to DecoratedCustomViewStyle() is necessary for custom views to display
.setStyle(new android.support.v7.app.NotificationCompat.DecoratedCustomViewStyle());
// retrieves android.app.NotificationManager
NotificationManager notificationManager = (android.app.NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
it seems that setOnClickPendingIntent doesn't work when used inside collections:
http://developer.android.com/reference/android/widget/RemoteViews.html#setOnClickPendingIntent(int,%20android.app.PendingIntent)
Try using setPendingIntentTemplate instead.