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();
}
Related
I am developing a flashLight app and I faced a problem in notification which is : When I press the notification text I want to turn of flash and close the whole app , How can I modified the notification method to do that ??
I tried to make anthor activity and put turn of and close app methods in it, but it does not work .
please help and thanks in advance .
this is my notification method
public void getNotification()
{
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
If you use the same Activity, then the onCreate method will be called again. You can send one extra with your Intent that indicates it is an Intent generated from the click of notification. In your Activity onCreate, check for this extra and call finish() if it is present.
public void getNotification() {
Intent intent = new Intent(this, FlashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("origin", "notification");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
And in your onCreate method in FlashActivity check the extra.
#Override
public void onCreate(Bundle savedInstanceState) {
...
if("notification".equals(getIntent().getStringExtra("origin"))) {
finish();
}
}
I believe you can use finish() on your Activity when the notification ils pressed.
EDIT: How to close any activity of my application by clicking on a notification?
You want to use PendingIntent.
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("FINISH",true);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
// Build the notification:
Notification notification = builder.build();
//rest of your methods to show notification
In your MainActivity update depending on your code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent){
setContentView(R.layout.activity_main);
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("FINISH"))
{
finish();
}
}
}
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
Right now I am creating a notification intent as per the following:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.setAction(Long.toString(System.currentTimeMillis()));
notificationIntent.putExtra("key", value);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification updateComplete = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(msg)
.setTicker(title)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon_notifications)
.build();
notificationManager.notify(100, updateComplete);
When the app is already in the background, everything works. The function onNewIntent is called and I get the value from the notificationIntent extras. However, if the app is NOT in the background, it goes to the root activity (login screen) which forwards the user to MyActivity. But the root activity doesn't get the call to onNewIntent, and by the time the user gets to MyActivity, the extras are lost.
Is there anyway around this?
I have been trying to store values elsewhere to no avail... This includes shared preferences.
#Override
protected void onMessage(final Context ctx, Intent intent) {
if (CommonMethod.isAppicationRunning(ctx)) {
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(ctx, ViewMessageDialog.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
resultIntent.putExtra("gcmmessage", message);
ctx.startActivity(resultIntent);
} else {
try {
sendNotification(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////////////////////
public static boolean isAppicationRunning(Context activity) {
ActivityManager am = (ActivityManager) activity
.getSystemService(EGLifeStyleApplication.mContext.ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.i("current activity", "activity"
+ activity.getClass().getSimpleName());
if (componentInfo.getPackageName().equals(
EGLifeStyleApplication.mContext.getPackageName())) {
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////
private void sendNotification(String message) throws JSONException {
// this
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.app_icon;
CharSequence tickerText = message; // ticker-text
long when = System.currentTimeMillis();
Context context = getApplicationContext();
context.getClass().getSimpleName();
Log.i("context.getClass().getSimpleName()",
"context.getClass().getSimpleName()="
+ context.getClass().getSimpleName());
CharSequence contentTitle = "Product Received.";
CharSequence contentText = message;
Intent notificationIntent = null;
int notificationID = CommonVariable.notificationID;
notificationIntent = new Intent(this, ViewHomeScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
// Play default notification sound
notification.defaults |= Notification.DEFAULT_ALL;
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(notificationID, notification);
}
check app running or not?if app is running in forgroung then please call only intent to pass that specific activity.and if app is running in backgroung then call sendnotification() to send notification on notification bar.
//this code is put in your gcmservice
Intent intent2 = new Intent();
intent2.setAction("RECEIVE_MESSAGE_ACTION_NEW");
intent2.putExtra("senderNum", senderNum);
intent2.putExtra("verificationCode",
ReturnValidationcode(message));
context.sendBroadcast(intent2);
Check this out. I don't know why your activity should run to get the upadate. If you follow that tutorial, then the mobile will automatically get push notification, if there are any. No need to run activity on background.
I found out how to do this.
Basically, if the activity you are launching with notificationIntent is already open (if it's the current activity the user is on), it will call onNewIntent(Intent intent). If it is not currently the active activity or if the application is not running, it will launch the activity and go to onCreate().
You have to get the intent from onCreate() by calling getIntent() and checking to see it's not null. Case closed.
I am implementing one sdk where when user click on notification then certain activity will be open.I am just wondering how can i pass different -different activity on intent.Here is my sample code:-
void fireNotification(Context _context, String appname,
String appdescription) {
Intent resultIntent = new Intent(_context, ResultActivity.class);
try {
PendingIntent contentIntent = PendingIntent.getActivity(_context,0, resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(_context);
}
Please suggest me how can pass different activity in intent.
I assume that you wanted to load another Activity instead of ResultActivity, you could just change the ResultActivity.class to the class name of the other activity.
If you are looking to have the ability to determine which activity to load after user taps on the notification, you can create a new Activity that will determine which Activity to load after it launches, kinda like an Activity to "redirect" the screen.
Try this..
void fireNotification(Context _context, String appname,
String appdescription) {
Intent resultIntent = null;
if(something)
resultIntent = new Intent(_context, SomeActivity1.class);
else
resultIntent = new Intent(_context, SomeActivity2.class);
try {
PendingIntent contentIntent = PendingIntent.getActivity(
_context,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(
_context);
}
Here is some code I use to create notifications. It uses the v4 Compatibility library.
As you can see you have to recreate the PentingIntent if you want to change the Activity to be launched. There is nothing wrong with cancelling and reissuing the intent as I have done. If you dont have allowing ticket text user likely not even notice it. Also, note that I know the compatibility builder lets you assign custom views but this crashes for me every time, directly assigning it seems more stable.
public static void setupNotification(Context context) {
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
}
mNotificationManager.cancel(R.layout.main);
int icon = R.drawable.ic_stat_notify_connected;
String tickerText = context.getString(R.string.TickerText);
createNotification(context, tickerText, icon);
mNotificationManager.notify(R.layout.main, mNotification);
}
private static void createNotification(Context context, String tickerText, int icon) {
Intent notificationIntent = new Intent();
notificationIntent = new Intent(context, NotificationOptionsActivity.class);
String contentTitle = context.getString(R.string.MessageTitle);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
if (mNotification == null) {
mNotification = new NotificationCompat.Builder(context.getApplicationContext()).setContentTitle(contentTitle).setSmallIcon(icon).setContentIntent(contentIntent).build();
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(context.getApplicationContext().getPackageName(), R.layout.notification_custom_layout);
mNotification.contentView = contentView;
} else {
mNotification.contentIntent = contentIntent;
}
}
Note: You have to use Intent.FLAG_ACTIVITY_NEW_TASK nothing else will work.
You can remove the code for the custom view if you don't have a custom view.
If you do have a custom view, you can set values in it as follows:
mNotification.contentView.setTextViewText(R.id.noti_user, user);
//default image
mNotification.contentView.setImageViewResource(R.id.noti_image, R.drawable.ic_user_icon);
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();