Hide Notification Drawer when opening Activity - android

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

Related

Need to dismiss the notification on tap when App is in foreground - android

Im testing the push notification with my app.
when App in the foreground:
Step 1. Received the notification (in system tray).
2. now, I'm in some other screen than the home screen.
3. Actual Problem: On tap on the notification, it is going to the home screen.
4. Expected: If the app is in the foreground, just I need to cancel on tap of the notification. (No need to swipe.)
when App in background/killed: (Works well)
Step 1. Received the notification (in the system tray)
2. On tap, open the home screen of the app.
Tried with setting launch mode flags in intent. Not helped. Below is my code. Please suggest the solution guys.
Intent resultIntent = new Intent(this, MainActivity.class);
//resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title);
mBuilder.setContentText(body);
mBuilder.setAutoCancel(true);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(body));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setChannelId(TestUtils.creatChanel(this).getId());
}
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(642, mBuilder.build());
Not sure about dismiss notification on tap, but since your concern is wrong navigation.
We can check app is in foreground or not and prevent new activity to be opened from notification click, if app is in foreground.
//If app is in foreground setting pending intent to null
PendingIntent pendingIntent;
Intent notificationIntent = new Intent(getApplicationContext(), Main2Activity.class);
if(isAppInForeground()){
Log.e("--^","inForeground");
pendingIntent = null;
}else{
Log.e("--^","inBackground");
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Add this function (SOURCE: link)
private boolean isAppInForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> services = activityManager.getRunningAppProcesses();
boolean isActivityFound = false;
if (services.get(0).processName
.equalsIgnoreCase(getPackageName()) && services.get(0).importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
isActivityFound = true;
}
return isActivityFound;
}
In this case if notification came when app is in foreground, it will do nothing if clicked. So user has only one option left to swipe it to remove.
You can create Custom Notification with close button to close notification using RemoteViews
// create Notification with RemoteViews:
RemoteViews remoteViews= new RemoteViews(getApplicationContext().getPackageName(), R.layout.your_custom_notification);
Intent closeIntent = new Intent(context, CloseNotificationService.class);
hangUpIntent.setAction("close");
PendingIntent pendingCloseIntent = PendingIntent.getBroadcast(this, 0, closeNotification, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.cancel_notification, pendingCloseIntent);
// create notification here..
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(remoteViews)
.build();
OnClick of close button it will redirect to service class:
public class CloseNotificationService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*/
public CloseNotificationService() {
super("notificationIntentService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
switch (intent.getAction()) {
case "close":
Handler hangUpHandler = new Handler(Looper.getMainLooper());
hangUpHandler.post(new Runnable() {
#Override
public void run() {
NotificationManager notifManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancel(notificationId); // get notification id from intent.
}
});
break;
}
}
}
For more information of RemoteViews you can refer official google developer website https://developer.android.com/training/notify-user/custom-notification
Instead of this:
Intent resultIntent = new Intent(this, MainActivity.class);
do this:
Intent resultIntent = getPackageManager().getLaunchIntentForPackage("your.package.name");
and put that in your Notification. This will launch the app if it is not already running, otherwise it will just bring the app's task to the foreground in whatever state it was when the user last used it. If the user is already in the app (ie: on another screen), this will do nothing when the user clicks the Notification.
Should be exactly what you are looking for.
Inside your launcher activity have you tried notification manager class cancelAll() method??
In this way if there is already a notification on launch then it will cancelled automatically

Heads-up Notification Buttons Not Executing

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.

How to open current activity which is open while click on notification

I have try all the methods but it doesn't work for me. i want to open or resume app with whatever screen open while click on notification.
I used following method:
NotificationCompat.BigTextStyle notiStyle = new NotificationCompat.BigTextStyle();
notiStyle.setBigContentTitle(team);
notiStyle.bigText(message);
Intent resultIntent = new Intent(this, MainDrawerActivity.class);
resultIntent.putExtra("fromNotification", "notification");
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
int icon = R.mipmap.ic_launcher;
return new NotificationCompat.Builder(this).setSmallIcon(icon)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent).setContentTitle(team)
.setContentText(message).setStyle(notiStyle).build();
To raise your application to the foreground without starting any new activity, fire its launcher intent.
This method is from an old project of mine.
/**
* Creates a new launcher intent, equivalent to the intent generated by
* clicking the icon on the home screen.
*
* #return the launcher intent
*/
public static Intent newLauncherIntent(final Context context) {
final Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}
The intent created by this method does not start a new task if the app is running, even though it has that flag.
This is another way to obtain a launcher intent. However, I found that this intent would always start a new task, which is not what you want if the app is running.
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID);
This is working fine for following three conditions:
1.if app already open and click on notification, notification should remove from status bar.
2.if app is open and in background then app should resume with whatever screen open already previously.
3.if app is close and click on notification in status bar then app should open.
private final static int NORMAL = 0x00;
private final static int BIG_TEXT_STYLE = 0x01;
private static NotificationManager mNotificationManager;
in onMessage call
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
new CreateNotification(BIG_TEXT_STYLE, team, message).execute();
then declare following class in GCMIntentService.
public class CreateNotification extends AsyncTask {
int style = NORMAL;
String team, message;
public CreateNotification(int style, String team, String message) {
this.style = style;
this.team = team;
this.message = message;
}
#Override
protected Void doInBackground(Void... params) {
Notification noti = new Notification();
switch (style) {
case BIG_TEXT_STYLE:
noti = setBigTextStyleNotification(team, message);
break;
}
noti.sound = (null);
noti.defaults = 0;
noti.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.beep);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(0, noti);
return null;
}
}
and finally
private Notification setBigTextStyleNotification(String team, String message) {
// Create the style object with BigTextStyle subclass.
NotificationCompat.BigTextStyle notiStyle = new NotificationCompat.BigTextStyle();
notiStyle.setBigContentTitle(team);
notiStyle.bigText(message);
Intent resultIntent = getPackageManager()
.getLaunchIntentForPackage(getPackageName());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the Intent that starts the Activity to the top of the stack.
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
int icon = R.mipmap.ic_launcher;
return new NotificationCompat.Builder(this).setSmallIcon(icon)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent).setContentTitle(team)
.setContentText(message).setStyle(notiStyle).build();
}
You should have something like this in Application class to store the current activity.
private BaseActivity mCurrentActivity = null;
public BaseActivity getCurrentActivity() {
return mCurrentActivity;
}
public void setCurrentActivity(BaseActivity currentActivity) {
this.mCurrentActivity = currentActivity;
}
Then, inside your handle notification Service class.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
BaseActivity currentActivity = ((App) this.getApplicationContext())
.getCurrentActivity();
Intent intent;
if (currentActivity instanceof ActivityA) {
intent = new Intent(this, ActivityA.class);
} else if (currentActivity instanceof ActivityB) {
intent = new Intent(this, ActivityB.class);
} else {
intent = new Intent(this, MainActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// your code...
}
If your app is killed, default activity will be called, such as MainActivity.
Else, when you receive & click push notification message when app is on foreground or background. Current activity will stay there as default activity, such as ActivityA & ActivityB. Then you can navigate to wherever another activities or fragments.
My suggestion, better we should use Fragment, it's easier in navigate to specially screen from push notification.
//I am using write now this can possible
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
Intent notificationIntent = new Intent(context, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
If you want to just resume the app state then instead of multiple activity I will suggest you just keep single activity and use Fragments for different screen.
On Notification click you need to define entry point of app in notification payload and the entry point decide what will be the next navigation.
If you are having only single activity then you can define that activity as a entry point and on the activity you can decide do you have to push new fragment or not.
Or second option if you are using firebase then push all notification as background notification and onMessageReceive method you can get top activity from activity stack and set that activity as entry point for the notification. But there is still problem as user may be click on notification after navigate from set entry point activity which again problem. So I prefer to go with first one approach.
make new activity
public class FinishImmediateActivity extends AppCompatActivity {
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
}
add to manifest.xml
<activity android:name=".FinishImmediateActivity"/>
check app is running
public static boolean isMainActivityRunning() {
ActivityManager activityManager = (ActivityManager) MyApp.getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < tasksInfo.size(); i++) {
if (tasksInfo.get(i).baseActivity.getPackageName().equals(MyApp.getContext().getPackageName())) {
return true;
}
}
return false;
}
then call that activity in notification intent.
Intent resultIntent = new Intent(this, isMainActivityRunning() ? FinishImmediateActivity.class : HomeActivity.class);
By this way also we can achieve the above result:
try {
int icon;
icon = R.mipmap.ic_launcher;
int mNotificationId = 001;
Intent intent = new Intent(this, MainDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//FLAG_UPDATE_CURRENT is important
PendingIntent pendingIntent = PendingIntent.getActivity(this,
(int)System.currentTimeMillis(), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(
this);
Notification notification =
mBuilder.setSmallIcon(icon).setTicker(json.getString("team")).setWhen(0)
.setAutoCancel(true)
.setContentTitle(json.getString("team"))
.setStyle(new
NotificationCompat.BigTextStyle().bigText(json.getString("message")))
.setContentIntent(pendingIntent)
.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.beep))
NotificationManager notificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
} catch (Exception e) {
e.printStackTrace();
}

How to add button to notifications in android?

My app plays music and when users open notifications screen by swiping from the top of the screen ( or generally from the bottom right of the screen on tablets ), I want to present them a button to stop the currently playing music and start it again if they want.
I am not planning to put a widget on the user's home screen, but just into notifications. How can I do this?
You can create an intent for the action (in this case stop playing) and then add it as an action button to your notification.
Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_snooze, getString(R.string.snooze),
snoozePendingIntent);
Please refer to the Android documentation.
I will try to provide a solution that I have used and most of the music player also use the same technique to show player controls in notification bar.
I am running a service which is used to manage Media Player and all its controls. Activity User control interacts with Service by sending Intents to the service for example
Intent i = new Intent(MainActivity.this, MyRadioService.class);
i.setAction(Constants.Player.ACTION_PAUSE);
startService(i);
TO receive intents and perform action in Service class I am using following code in onStartCommand method of Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
if(mediaPlayer.isPlaying()) {
pauseAudio();
}
}
Now to exact answer to your question to show notification with playing controls. You can call following methods to show notification with controls.
// showNotification
private void startAppInForeground() {
// Start Service in Foreground
// Using RemoteViews to bind custom layouts into Notification
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.notification_status_bar);
// Define play control intent
Intent playIntent = new Intent(this, MyRadioService.class);
playIntent.setAction(Constants.Player.ACTION_PLAY);
// Use the above play intent to set into PendingIntent
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
// binding play button from layout to pending play intent defined above
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setImageViewResource(R.id.status_bar_play,
R.drawable.status_bg);
Notification status = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
status = new Notification.Builder(this).build();
}
status.flags = Notification.FLAG_ONGOING_EVENT;
status.icon = R.mipmap.ic_launcher;
status.contentIntent = pendingIntent;
startForeground(Constants.FOREGROUND_SERVICE, status);
}
Hope this really helps you. And you will be able to achieve what you want. Have a Happy Coding :)
// It shows buttons on lock screen (notification).
Notification notification = new Notification.Builder(context)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.NotIcon)
.addAction(R.drawable.ic_prev, "button1",ButtonOneScreen)
.addAction(R.drawable.ic_pause, "button2", ButtonTwoScreen)
.....
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(1)
.setMediaSession(mMediaSession.getSessionToken())
.setContentTitle("your choice")
.setContentText("Again your choice")
.setLargeIcon(buttonIcon)
.build();
Please refer this for more details Click here
tested, working code with android Pie. These all go inside the same service class.
Show a notification:
public void setNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("a", "status", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("notifications");
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
else
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Receiver.service = this;
Notification.MediaStyle style = new Notification.MediaStyle();
notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification")
.addAction(R.drawable.close_icon, "quit_action", makePendingIntent("quit_action"))
.setStyle(style);
style.setShowActionsInCompactView(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notification.setChannelId("a");
}
// notificationManager.notify(123 , notification.build()); // pre-oreo
startForeground(126, notification.getNotification());
}
Helper function:
public PendingIntent makePendingIntent(String name)
{
Intent intent = new Intent(this, FloatingViewService.Receiver.class);
intent.setAction(name);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
return pendingIntent;
}
To handle the actions:
static public class Receiver extends BroadcastReceiver {
static FloatingViewService service;
#Override
public void onReceive(Context context, Intent intent)
{
String whichAction = intent.getAction();
switch (whichAction)
{
case "quit_action":
service.stopForeground(true);
service.stopSelf();
return;
}
}
}
You'll need to update your manifest too:
<receiver android:name=".FloatingViewService$Receiver">
<intent-filter>
<action android:name="quit_action" />
</intent-filter>
</receiver>
I think that beside Ankit Gupta answer, you can use MediaSession (API > 21) to add native mediaController view :
notificationBuilder
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(new int[]{playPauseButtonPosition}) // show only play/pause in compact view
.setMediaSession(mSessionToken))
.setColor(mNotificationColor)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setUsesChronometer(true)
.setContentIntent(createContentIntent(description)) // Create an intent that would open the UI when user clicks the notification
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setLargeIcon(art);
Source: tutorial
you can alse create custom view and display it in the notificcation area , first answer here is great.
you can add button as below and can perform action on that button also i have done for me as below please check.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setAutoCancel(true)
.setContentTitle(name)
.setContentText(body)
.setGroupSummary(true)
.addAction(android.R.drawable.ic_menu_directions, "Mark as read", morePendingIntent);
//morePendingIntent(do your stuff)
PendingIntent morePendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE_MORE,
new Intent(this, NotificationReceiver.class)
.putExtra(KEY_INTENT_MORE, REQUEST_CODE_MORE)
.putExtra("bundle", object.toString()),
PendingIntent.FLAG_UPDATE_CURRENT
);
I don't know if this is the right way or not, but it works.
Create a BroadCastReceiver class to receive the data when button is pressed.
public class MyBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String log = "URI: " + intent.toUri(Intent.URI_INTENT_SCHEME);
Log.d("my", "LOG:::::::" + log);
}
}
Now in any activity where you want to create the notification -
Intent intent = new Intent();
intent.setAction("unique_id");
intent.putExtra("key", "any data you want to send when button is pressed");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
Now use this pending intent when you are creating the notification and lastly you need to register this broadcast in order to receive it in MyBroadCastReceiver class.
BroadcastReceiver br = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter("unique_id");
registerReceiver(br, filter);
Now if you want to do certain things when the button is pressed, you can do so in the onReceive() method in MyBroadCastReceiver class.

Android : Cancel Notification after click on Action (Like Call)

I have an action to Dial a number via
uri = Uri.parse("tel:" + address);
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(uri);
PendingIntent pd = PendingIntent.getActivity(context, 0,intent,
PendingIntent.FLAG_UPDATE_CURRENT);
notif.addAction(R.drawable.ic_menu_call, "Call", pd);
but the problem is that I don't know
how/when to call the NotificationManager's manager.cancel() function
so as to dismiss the notification when the call action is clicked!
I had the same situation and I managed to solve it by creating a broadcast receiver that is called when the action button is pressed. The broadcast receiver then receives an intent with the notification id that you want to dismiss and the number you want to dial.
The is the code that creates the notification:
NotificationManager notificationManager =
(NotificationManager)MyApplication.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
//for some versions of android you may need to create a channel with the id you want
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel("your_channel_id", "ChannelName", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(chan);
}
Intent intent = new Intent(MyApplication.getAppContext(), ActionReciever.class);
intent.putExtra("phoNo", phoneNumber);
// num is the notification id
intent.putExtra("id", num);
PendingIntent myPendingIntent = PendingIntent.getBroadcast(
MyApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
);
Notification n = new NotificationCompat.Builder(MyApplication.getAppContext(),
"your_channel_id")
.setSmallIcon(R.drawable.app_pic)
.addAction(R.drawable.app_pic, "Dial now", myPendingIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(num, n);
This is the broadcast receiver code, it is called when the action button is pressed. The received intent here is the intent inside the pending intent we prepared in the notification:
public class ActionReciever extends BroadcastReceiver {
#SuppressLint("MissingPermission")
#Override
public void onReceive(Context context, Intent intent) {
String phoneNumber = intent.getStringExtra("phoNo");
int id = intent.getIntExtra("id",0);
Intent i = new Intent(Intent.ACTION_DIAL);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse("tel:" + phoneNumber));
NotificationManager notificationManager =
(NotificationManager) MyApplication.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
context.startActivity(i);
}
}
Register the BroadcastReceiver in the app manifest inside application tag
<receiver android:name=".ActionReciever" />
MyApplication is a class that extends the default Application so I can have a place to store the context I need.
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Note that you need to update the manifest to run the MyApplication class like this:
android:name="com.example.yourpackage.MyApplication"
This code works even if the app is down and without a background service.
See Android READ PHONE STATE? - about phone state.
case TelephonyManager.CALL_STATE_RINGING:
notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(100); // cancel notification by ID
break;
// build your notification.
intent notificationIntent = new Intent(context,
YourPhoneActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
iconLarge);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context).setSmallIcon(iconSmall).setLargeIcon(bm)
.setContentTitle(title).setContentText(message)
.setAutoCancel(false).setContentIntent(intent).setWhen(when)
.setTicker(message);
builder.getNotification();

Categories

Resources