notification buttons (.addaction) not launching activity - android

I'm attempting to make a notification that has two buttons which do two different things by running two different activities. The notification and its buttons appear on the notification bar fine, however pressing on either of the buttons fails to launch the designated activity.
Here is the code:
private void addNotification() {
int requestID = (int) System.currentTimeMillis();
NotificationCompat.Builder builder = (android.support.v7.app.NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ibutton)
.setContentTitle("Timer running..")
.setContentText(timerString);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
//Add buttons to notification
//First make the intent
Intent pauseIntent = new Intent(this, pauseActivity.class);
//Wrap it in pending intent to trigger later
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
//Same again for stop button
Intent stopIntent = new Intent(this, stopActivity.class);
PendingIntent stopPendingIntent = PendingIntent.getActivity(this, requestID, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.stop, "Stop", stopPendingIntent);
// Add as notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mNotificationId = 001;
notificationManager.notify(mNotificationId, builder.build());
}
EDIT: An example of one of the activities I am trying to launch:
public class stopActivity {
public stopActivity() {
MainActivity.stopped = true;
}
}
If there is any easier way of simply changing the value of a variable in MainActivity from the button in the notification bar then I am also keen to hear that but as far as I can tell the only option is to launch a new activity

EDIT: An example of one of the activities I am trying to launch:
public class stopActivity { public stopActivity() {
MainActivity.stopped = true; } }
This is not an Activity. An Activity extends Activity!
This is just a POJO class and you cannot start it by putting it in a PendingIntent the way you are doing.
You would be better off by just using an Intent for MainActivity with an "extra" to change a value in it. Here's an example:
Intent pauseIntent = new Intent(this, MainActivity.class);
pauseIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
pauseIntent.putExtra("pause", true);
PendingIntent pausePendingIntent = PendingIntent.getActivity(this, requestID, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Then add the action to your notification
builder.addAction(R.drawable.pause, "Pause", pausePendingIntent);
Then, in MainActivity.onNewIntent():
if (intent.hasExtra("pause")) {
this.paused = true; // whatever you want to do when "pause" is pressed
}

Related

shutting the app by removing notification

#RequiresApi(api = Build.VERSION_CODES.M)
public void showNotification(int playPauseBtn) {
Intent intent = new Intent(this, ExoActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
Intent prevIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PREVIOUS);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, prevIntent,
PendingIntent.FLAG_MUTABLE);
Intent playIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_PLAY);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, playIntent,
PendingIntent.FLAG_MUTABLE);
Intent nextIntent = new Intent(this, NotificationReceiver.class).setAction(ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, nextIntent,
PendingIntent.FLAG_MUTABLE);
Bitmap picture = BitmapFactory.decodeResource(getResources(), HelperClass.getlist().get(position).getImg());
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
.setSmallIcon(HelperClass.getlist().get(position).getImg()) //get thumbnail will have small icon pic
.setLargeIcon(picture)
.setContentTitle(HelperClass.getlist().get(position).getName())
.addAction(R.drawable.ic_baseline_skip_previous_24, "Previous", prevPendingIntent)
.addAction(R.drawable.ic_baseline_play_arrow_24, "Play", playPendingIntent)
.addAction(R.drawable.ic_baseline_skip_next_24, "Next", nextPendingIntent)
//.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
//.setMediaSession(mediaSession.getSessionToken()))
.setPriority(Notification.PRIORITY_HIGH)
.setC`your text`ontentIntent(contentIntent)
.setOnlyAlertOnce(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
This code creates Notification wherever this 'showNotification()' function is called but what if I want to shut the app by removing the notification?
use setDeleteIntent method - when notification is removed you can send some broadcast to all your "contextual" ojects (e.g. Activity, Service)
note that there is also setOngoing method, which will stick your notification and user won't be able to remove it "manually". then you can provide "kill" action button for this notification, which may behave exacly same as one created for setDeleteIntent. in that case don't forget to remove notification when user just leave/exit your app, when "kill" action pressed or in any other "usual" way

Pending Intent not receiving the putExtraBudle for different notificationId

I am using the code of PingService.java https://github.com/android/platform_development/blob/master/samples/training/notify-user/src/com/example/android/pingme/PingService.java
PingService.Java
/**
* PingService creates a notification that includes 2 buttons: one to snooze the
* notification, and one to dismiss it.
*/
public class PingService extends IntentService {
private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
public PingService() {
// The super call is required. The background thread that IntentService
// starts is labeled with the string argument you pass.
super("com.example.android.pingme");
}
#Override
protected void onHandleIntent(Intent intent) {
// The reminder message the user set.
mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
// The timer duration the user set. The default is 10 seconds.
mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
CommonConstants.DEFAULT_TIMER_DURATION);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
// This section handles the 3 possible actions:
// ping, snooze, and dismiss.
if(action.equals(CommonConstants.ACTION_PING)) {
issueNotification(intent, mMessage);
} else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
// Sets a snooze-specific "done snoozing" message.
issueNotification(intent, getString(R.string.done_snoozing));
} else if (action.equals(CommonConstants.ACTION_DISMISS)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Sets up the Snooze and Dismiss action buttons that will appear in the
// expanded view of the notification.
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Constructs the Builder object.
builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
/*
* Sets the big view "big text" style and supplies the
* text (the user's reminder message) that will be displayed
* in the detail area of the expanded notification.
* These calls are ignored by the support library for
* pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.addAction (R.drawable.ic_stat_dismiss,
getString(R.string.dismiss), piDismiss)
.addAction (R.drawable.ic_stat_snooze,
getString(R.string.snooze), piSnooze);
/*
* Clicking the notification itself displays ResultActivity, which provides
* UI for snoozing or dismissing the notification.
* This is available through either the normal view or big view.
*/
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
startTimer(mMillis);
}
private void issueNotification(NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Including the notification ID allows you to update the notification later on.
mNotificationManager.notify(CommonConstants.NOTIFICATION_ID, builder.build());
}
private void startTimer(int millis) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
}
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
issueNotification(builder);
}
}
Intent mServiceIntent = new Intent(context.getApplicationContext(), PingService.class);
mServiceIntent.putExtra(Const.EXTRA_MESSAGE, "" + msg);
mServiceIntent.putExtra(Const.ID, reminder_id);
startService(mServiceIntent);
And passing the data to issueNotification method for Action Button intent like
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
dismissIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
snoozeIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
But i am not getting the ID at the time of Click event of the Action button from issueNotification and passing the intent in onHandleIntent method
It is automatically set to 1 after Notification generation and i am not able to cancel that notification due to wrong notification id set into putExtra of PendingIntent
I am trying with passing different flag like
PendingIntent piDismiss = PendingIntent.getService(this, 0, taken_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Please help me out i am trying it since long time but not getting the correct id.
My putExtra is override with 1 somehow....
Thank you in advnace
After so much reasearching finally got a solution that i need to pass different code in pending intent like
PendingIntent piDismiss = PendingIntent.getBroadcast(this, CommonConstants.NOTIFICATION_ID, dismissIntent, 0);
which is dynamic one and unique one in each Action Button case.
Use Broadcast receiver to achieve this instead of Service ( getBroadcast ).
Thank you.

Android - create notifications

I have question about notifications. I want to build an app with one buttons called (add notification) when I press add notification a notification is created Then, if I press the notification it takes me back to the activity.
I managed to create a notification but when i press on it, it makes nothing. What do I have to add so the notification sends me back to the activity?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
NotificationManager nmanger;
static int id=1;
public void buclick(View view) {
NotificationCompat.Builder nbuild= (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setSmallIcon(R.drawable.amule);
nmanger =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nmanger.notify(id,nbuild.build());
id++;
}
Create PendingIntent, then set it to builder:
Intent intent = new Intent(this, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder nbuild = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Danger")
.setContentText("the raining is comming soon")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.amule);
Try this code
Intent intent = new Intent(this, NameOfClassYouWantToOpen.class);
// Create pending intent and wrap our intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
try {
// Perform the operation associated with our pendingIntent
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
http://codetheory.in/android-pending-intents/
What is an Android PendingIntent?

How to clear or close notification from notification bar click on close button in android

I use below code how to achieve my motto, I want to close or clear notification from notification bar click on close button
Intent moreNewsIntent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(AppService.this, 0, moreNewsIntent, 0);
// expanded view of the notification.
/* Intent close = new Intent(this, AppService.class);
close.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, close, 0);*/
int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, AppService.this);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setTicker("News Notification")
.setContentText(getString(R.string.lbl_notification_title_news))
.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE)
.setLights(0xff00ff00, 300, 100)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setContentIntent(pIntent)
.addAction (R.drawable.news_negative,getString(R.string.btn_more_nes), pIntent)
.addAction (R.drawable.close,getString(R.string.btn_close), dismissIntent)
.setAutoCancel(true);
NotificationActivity.java
public class NotificationActivity extends Activity {
public static final String NOTIFICATION_ID = "001";
#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
<activity android:name=".NotificationActivity" android:taskAffinity="" android:excludeFromRecents="true">
Thanx in advance help would be greatly appreciated
Call cancel() with the same id you initialized the notification with.
If you are asking how to get a PendingIntent to do a cancel() call, it looks like you were on the right track with PendingIntent.getService(). A better approach would probably be to use PendingIntent.getBroadcast(), register a receiver in the manifest, and do the call from there.

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?

Categories

Resources