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);
Related
I'm delivering a notification which has 2 action buttons namely "Accept" and "Reject".
I'm following this Github repo.
When user clicks "Accept", certain conditions are checked and the logic is performed accordingly.
UPDATE 2.0 - The problem is that upon clicking "Accept" button, operation is happening successfully but the notification isn't disappearing from the status bar because the id generating here: m = (new Random()).nextInt(10000); is different from here: actionIntent.putExtra("id", NotificationARBroadcastReceiver.m); every single time!
Here's the code for notification:
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationNewRequestService());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);
Here's getNotificationNewRequestService():
private Notification getNotificationNewRequestService() {
mBuilder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.mipmap.app_icon_1)
.setContentTitle("Title")
.setContentText("text...");
Intent resultIntent = new Intent(getBaseContext(), Profile.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getBaseContext(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
// for action button
Intent actionIntent = new Intent(getBaseContext(), MyBroadcastSender.class);
actionIntent.putExtra("id", NotificationARBroadcastReceiver.m);
PendingIntent actionPendingIntent = PendingIntent
.getBroadcast(getBaseContext(),
0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.addAction(R.drawable.ic_accepted_request_black_24dp, "Accept", actionPendingIntent);
mBuilder.addAction(R.drawable.ic_close_black_24dp, "Reject", null);
return mBuilder.build();
}
Here's NotificationARBroadcastReceiver.java file:
public class NotificationARBroadcastReceiver extends BroadcastReceiver {
public static String NOTIFICATION = "notification";
public static NotificationManager mNotifyMgr;
public static int m;
#Override
public void onReceive(Context context, Intent intent) {
m = (new Random()).nextInt(10000);
Log.d("mMain", String.valueOf(m));
mNotifyMgr =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
mNotifyMgr.notify(m, notification);
}
}
Here's MyBroadcastSender.java file:
public class MyBroadcastSender extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Received by MyBroadcastSender.", Toast.LENGTH_SHORT).show();
int id = intent.getIntExtra("id", 1);
// send back to your class
Intent newIntent = new Intent();
newIntent.setAction(context.getString(R.string.broadcast_id));
newIntent.putExtra("id1", id);
context.sendBroadcast(newIntent);
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
Toast.makeText(context, "Broadcast sent back.", Toast.LENGTH_SHORT).show();
}
}
and here's MyBroadcastReceiver.java file:
// BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver(){
super();
}
#Override public void onReceive(Context context, Intent intent) {
int id2 = intent.getIntExtra("id1", 1);
if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id))) {
NotificationARBroadcastReceiver.mNotifyMgr.cancel(id2);
Intent intent1 = new Intent(MyService.this, MainActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
Toast.makeText(context, "Broadcast received by MyBroadcastReceiver. Now, you can perform actions.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Intent is null.", Toast.LENGTH_SHORT).show();
}
}
}
In getNotificationNewRequestService(), I'm putting notification id as an extra in "id", then in MyBroadcastSender.java, I'm getting this extra as int id = intent.getIntExtra("id", 1); and then putting again as newIntent.putExtra("id1", id); and then finally getting it in MyBroadcastReceiver.java as int id2 = intent.getIntExtra("id1", 1); and trying to remove the notification using it as NotificationARBroadcastReceiver.mNotifyMgr.cancel(id2);.
Sorry for this much code, I've to upload it all as they all are necessary.
What I want is to know how to deliver the same notification id from NotificationARBroadcastReceiver.java (which is a separate java file) to MyBroadcastReceiver(which is an inner class in MyService.java)?
Update 1.0- this is what happened when I printed out the values of m, mMain, id, id1:
D/m: 0
D/mMain: 9994
D/id: 0
D/id1: 0
Assuming getNotificationService() == getNotificationNewRequestService() Looks like the NotificationARBroadcastReceiver isn't called before the notfication is built and displayed.
You would do better to generate the notification id where you create the notification and just add it to the intent there as well you don't need to make.
So call getNotificationNewRequestService() from NotificationARBroadcastReceiver.recieve() and make sure the notification ids match up.
Edit:
move:
m = (new Random()).nextInt(10000);
before:
actionIntent.putExtra("id", NotificationARBroadcastReceiver.m); // this will be 'm'
Result:
int m = (new Random()).nextInt(10000);
Intent actionIntent = new Intent(getBaseContext(), MyBroadcastSender.class);
actionIntent.putExtra("id", m);
Log.d(getClass().getSimpleName(), "Notification Id is : " + m);
then, you can check what values are in id, id1 and id2. Don't forget to call .notify() with same Id you got from m.
You can, also, create getRandomNotificationId() and getLastGeneratedNotificationId() methods. Whenever you generate an Id, store it in public static integer variable, so that you can access it throughout the class.
Problem might be that you are accessing m from NotificationARBroadcastReceiver before initializing it. So, it will definitely be 0. And, you mentioned something about println error, are you using System.out.println()?
Before Edit:
As seen on your new edit, try closing notification before starting it:
m = (...);
// some code here
mNotifyMgr.cancel(m);
mNotifyMgr.notify(m, notification);
and see if your issue gets resolved.
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
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
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 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();