This question already has answers here:
Android notification .addAction deprecated in api 23
(6 answers)
Closed 5 years ago.
I'm creating a notification like this.
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle(notifyMessage1)
.setContentText(notifyMessage2)
.setSmallIcon(R.mipmap.ic_launcher);
Notification notification = builder.build();
I want to add a action to my notification with
builder.addAction();
To realize addAction(icon, title, pendingIntent); is deprecated
My geal is to create a notification action without an icon, how can i achieve that?
You can't directly call methods when you click action buttons.
You require to use PendingIntent with BroadcastReceiver or Service to perform this.
Here is an example of Pending Intent with Broadcast Reciever.
First build a Notification
public static void createNotif(Context context){
...
//This is the intent of PendingIntent
Intent intentAction = new Intent(context,ActionReceiver.class);
//This is optional if you have more than one buttons and want to differentiate between two
intentAction.putExtra("action","actionName");
pIntentlogin = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.steeringwheel)
.setContentTitle("NoTextZone")
.setContentText("Driving mode it ON!")
//Using this action button I would like to call logTest
.addAction(R.drawable.smallmanwalking, "Turn OFF driving mode", pIntentlogin)
.setOngoing(true);
...
}
Now the receiver which will receive this Intent
public class ActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();
String action=intent.getStringExtra("action");
if(action.equals("action1")){
performAction1();
}
else if(action.equals("action2")){
performAction2();
}
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
}
public void performAction1(){
}
public void performAction2(){
}
}
Do not forget to declare BroadCast Receiver in Manifest
<receiver android:name=".ActionReceiver"></receiver>
Hope it helps you.
Use the NotificationCompat instead of Notification like this:
Notification.Action action = new NotificationCompat.Action(icon, title, pendingIntent);
Notification notification = new NotificationCompat.Builder(context)
.addAction(action)
.build();
Related
In my app, I am doing multiple upload requests using retrofit 2 and launching a new notification for each upload.
After going through a lot of similar questions, I am not sure how can I cancel the request using Call.cancel for a particular upload when its notification action cancel button clicked.
Thanks!
Define a Map object
Map<int,Call> callStack= new HashMap<>();
When called to your_call_object add this.
int notificationId = ((Double) (Math.random() * 10000)).intValue()
callStack.put(notificationId, your_call_object)
When you creating a notification object add that notificationId.
notificationManager.notify(notificationId, notification.build());
When clicked Cancel Button, find that notificationId and...
Call your_call_object = callStack.getObject(notificaitonId);
your_call_object.cancel();
please read this link. a very detail explanation is provided tailor it to your needs.https://futurestud.io/tutorials/retrofit-2-cancel-requests
try to connect your service notification with your activity or service upload with a broadcast, in your notification action cancel send the broadcaster:
//declare in your manifest your broadcast class
Intent intentBroadcast = new Intent();
intentBroadcast.setAction("CANCEL_RETROFIT_CALL");
intentBroadcast.putExtra("ID_CALL","upload_123");
LocalBroadcastManager.getInstance(this).sendBroadcast(intentBroadcast);
PendingIntent pendintAction = PendingIntent.getBroadcast(this, 0, intentBroadcast, PendingIntent.FLAG_UPDATE_CURRENT);
//then set the action setup
action = new NotificationCompat.Action.Builder(R.drawable.ic_action_cancel,
"cancel", pendintAction).build();
//launch your notification
NotificationCompat.Builder notificacion = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_noti_logo)
.setContentTitle(remoteMessage.getData().getAlert())
.setContentText(remoteMessage.getMessage())
.setAutoCancel(true)
.setSound(alarmSound)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000})
.addAction(action);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificacion.build());
//in your actionbroadcast class
public class ActionBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
LocalBroadcastManager broadcaster = LocalBroadcastManager.getInstance(context);
String accion = intent.getAction();
String id_call = intent.getStringExtra("ID_CALL");
if (accion.equals("CANCEL_RETROFIT_CALL")) {
switch (id_call) {
case callID:
intent = new Intent("CANCEL_RETROFIT_CALL");
intent.putExtra("id_call", id);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
break;
}
}
}
}
i hope that this conde can help u .. https://github.com/googlesamples/android-UniversalMusicPlayer
I have been searching for a few hours, but could not find any solution to my problem. Does anyone know how to make heads-up notification buttons call a broadcast? My code:
Alarm Receiver Notification Builder:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.alarmicon)
.setContentTitle("Alarm for " + timeString)
.setContentText(MainActivity.alarmLabel.getText().toString())
.setDefaults(Notification.DEFAULT_ALL) // must requires VIBRATE permission
.setPriority(NotificationCompat.PRIORITY_HIGH); //must give priority to High, Max which will considered as heads-up notification
//set intents and pending intents to call service on click of "dismiss" action button of notification
Intent dismissIntent = new Intent(context, notificationButtonAction.class);
dismissIntent.setAction(DISMISS_ACTION);
PendingIntent piDismiss = PendingIntent.getBroadcast(context, 0, dismissIntent, 0);
builder.addAction(R.drawable.alarmoff, "Dismiss", piDismiss);
//set intents and pending intents to call service on click of "snooze" action button of notification
Intent snoozeIntent = new Intent(context, notificationButtonAction.class);
snoozeIntent.setAction(SNOOZE_ACTION);
PendingIntent piSnooze = PendingIntent.getBroadcast(context, 0, snoozeIntent, 0);
builder.addAction(R.drawable.snooze, "Snooze", piSnooze);
// Gets an instance of the NotificationManager service
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//to post your notification to the notification bar with a id. If a notification with same id already exists, it will get replaced with updated information.
notificationManager.notify(0, builder.build());
notificationButtonAction:
public static class notificationButtonAction extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("notificationButtonAction Started");
String action = intent.getAction();
if (SNOOZE_ACTION.equals(action)) {
stopAlarm();
System.out.println("Alarm Snoozed");
MainActivity ma = new MainActivity();
ma.setAlarm(true);
}
else if (DISMISS_ACTION.equals(action)) {
stopAlarm();
System.out.println("Alarm Dismissed");
}
}
}
My print lines in notificationButtonAction do not print, not even the "notificationButtonAction Started."
I followed the tutorial from Brevity Software (http://www.brevitysoftware.com/blog/how-to-get-heads-up-notifications-in-android/), but their code didn't seem to work.
Any help is appreciated! Thanks!
Turns out, I didn't add the class to the manifest. My code was fine.
My Android notification Action buttons are not working at all. I have the following code in my service, and the receiver is NOT registered in the manifest because it makes no change. I can send the broadcast from another activity, and it works great, but there is a problem somewhere.
Here are the PendingIntents that pair with the buttons
Intent next = new Intent(getString(R.string.receiver_notification_media_change));
next.setAction(NOTIFICATION_MEDIA_CHANGE_NEXT);
PendingIntent pendingIntentNext = PendingIntent.getBroadcast(getApplicationContext(), 0, next, PendingIntent.FLAG_UPDATE_CURRENT);
Intent last = new Intent(getString(R.string.receiver_notification_media_change));
last.setAction(NOTIFICATION_MEDIA_CHANGE_BACK);
PendingIntent pendingIntentLast = PendingIntent.getBroadcast(getApplicationContext(), 0, last, PendingIntent.FLAG_UPDATE_CURRENT);
Notification:
Notification.Builder mBuilder = new Notification.Builder(getApplicationContext())
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(smallDrawableResId)
.addAction(R.drawable.icon1, "as", pendingIntentLast)
.addAction(R.drawable.icon2, "asdf", pendingIntentNext)
.setContentTitle(title)
.setContentText("title")
.setLargeIcon(icon)
.setContentIntent(pendingIntent) //to an activity. Works great
.setOngoing(true)
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(0, 1));
Here is the BroadcastReceiver which is declared in the class below.
private BroadcastReceiver notificationMediaChanger = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
System.out.println("RECEIVEDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
if(action.equals(NOTIFICATION_MEDIA_CHANGE_NEXT))
playNextSong();
else if(action.equals(NOTIFICATION_MEDIA_CHANGE_BACK))
playPreviousSong();
}
};
OnCreate the receiver is registered
registerReceiver(notificationMediaChanger, new IntentFilter(getString(R.string.receiver_notification_media_change))); //LocalBroadcastManager.getInstance(getApplicationContext()) appears to be equivalent.
And OnStop it is removed:
unregisterReceiver(notificationMediaChanger);
Your action strings do not match.
Intent next = new Intent(getString(R.string.receiver_notification_media_change));
next.setAction(NOTIFICATION_MEDIA_CHANGE_NEXT);
For some reason, you are replacing one action string with another. I do not know why.
registerReceiver(notificationMediaChanger, new IntentFilter(getString(R.string.receiver_notification_media_change)));
Here, you are using the first action string. Your Intent has the second action string. These are presumably not the same.
Also:
LocalBroadcastManager is not used by PendingIntent
Unless the Notification is only on the screen while your activity is on the screen (which would be bizarre), you need to register your receiver in the manifest
I have successfully created an item on the notification bar with following code in which DownloadService extends the IntentService class.
public class MyService extends Activity
{
...
void startService()
{
...
Intent myIntent = new Intent(StoryGallery.this,DownloadService.class);
myIntent.putExtra("story name", story.title);
startService(myIntent);
}
}
Question is how to click the notification item to return to my app?
It seems there is lots of questions like this, but I can't find a straightforward answers on how to launch the app by clicking the notification item. I have tried to make "DownloadService implements OnClickListener", but there is not any response after clicking.
So Thanks in advance for reply.
A Service should not implement an onClickListener as it has no UI. It just runs in the background. So, whenever you want to display a notification use :
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
/** IMPORTANT : Create an intent which starts the activity **/
Intent intent = new Intent(context, ActivityName.class);
/** IMPORTANT : Ensure that you use getActivity with the PendingIntent. **/
/**This pending intent will be fired when you click on the notification.**/
builder.setContentIntent(PendingIntent.getActivity(context, 0, intent,
0));
builder.setContentTitle(title);
builder.setContentText(message);
builder.setSmallIcon(R.drawable.notification_icon);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, notification);
I would like to send a LocalBroadcast when clicking on a button inside a notification. I know how to do that with a regular broadcast, but I would like to keep the broadcast inside my app. Is this possible?
The code I have is roughly:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setContentTitle("Title")
.setContentText("content")
.setSmallIcon(R.drawable.icon1)
.setContentIntent(pIntent)
.setAutoCancel(true);
Intent myButtonIntent = new Intent(BUTTON_PRESSED);
// the following line gives me a normal broadcast, not a LocalBroadcast
PendingIntent myButtonpIntent = PendingIntent.getBroadcast(context, 12345, myButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.addAction(R.drawable.icon2, "OK", myButtonpIntent);
Notification notification = notificationBuilder.build();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
And also:
BroadcastReceiver bReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BUTTON_PRESSED)) {
// do something
}
}
};
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BUTTON_PRESSED);
bManager.registerReceiver(bReceiver, intentFilter); // I want to use the LocalBroadcastManager
// registerReceiver(bReceiver, intentFilter); // Instead, I have to use this line for a non-local broadcast
No.
First of all, LocalBroadcastManager is part of the support package (an optional library you add to your application), not part of the system itself.
Secondly, even if it were, the notification service is used by all applications. Since it's a shared resource, there is nothing "local" that occurs when you post a notification.
this might work(it works for me)
add your BroadcastReceiver to manifest.xml
<!-- If this receiver listens for broadcasts sent from the system or from
other apps, even other apps that you own, set android:exported to "true". -->
<receiver android:name=".myBroadcastReceiver" android:exported="false">
<intent-filter>
<action android:name="some" />
</intent-filter>
</receiver>
creating a Notification and add action( .addaction() )
and sending Broadcast to BroadcastReceiver
(you can use the helper function)
Intent Rintent = new Intent(this , YOUR_BroadcastReceiver_CLASS.class );
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
createNotificationChannel(ChanelID ,"name " , "Desc" );
startForeground(FLAG_FORGRANDONLLINE, new NotificationCompat.Builder(ServiceFindTask.this,
NotifID) // don't forget create a notification channel first
.setOngoing(true)
.setSmallIcon(R.mipmap.somet)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running ")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setVibrate(new long[]{1000,100})
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
// Sending a action for BroadcastReceiver class
.addAction(R.drawable.body,"GO offline" , makePendingIntent(SERVICE_TO_CLIENT_GO_OFFLINE , null , Rintent))
.build());
// Helper function
public PendingIntent makePendingIntent(Integer action , #Nullable String data ,Intent intent) {
intent.setAction( action.toString());
if(data != null){
intent.putExtra("kay", data);}
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
return pendingIntent;
}
receive the action and create LocalBroadcast using LocalBroadcastManager
based on your notification action
public class myBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (Integer.parseInt(action)){
case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
helpLocalBroadcastManager(intent , context , Service.SERVICE_TO_CLIENT_GO_OFFLINE , null);
break;
}
}
private void helpLocalBroadcastManager(Intent intent ,Context context ,Integer action , #Nullable String data ) {
intent = new Intent(action.toString());
// Adding some data
if(data != null){
intent.putExtra("kay", data);}
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
now you can receive the LocalBroadcast in any activity that is connect to BroadcastReceiver like this:
private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (Integer.parseInt(action)){
case Service.SERVICE_TO_CLIENT_GO_OFFLINE:
Toast.makeText(Activity_Main.this , "This is massage from Activity_Main " , Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this)
.registerReceiver(messageReceiver, new IntentFilter(String.valueOf(ServiceFindTask.SERVICE_TO_CLIENT_GO_OFFLINE)));
}
this question was for 8 years ago but this was something i needed now and this is how i did it THANKS FOR READING