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);
Related
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();
}
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 am trying to create a notification that when clicked will open an external app. I've seen the documentation for creating notifications and for sending the user to another app. But I can't seem to figure out how to combine the two. The problem is that the advised way to launch an app from a notification, is to creating the pending intent like this:
Intent intent = new Intent(this, MyActivity.class);
TaskStackBuilder stackBuidler = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MyActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
But to launch an external app, you have to create an implicit intent like this:
String uri = ...
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
As far as I can tell, there is no way to create the TaskStackBuilder with this kind of intent, because addParentStack() will only take an Activity, a Class, or a ComponentName.
I guess the question boils down to... is it possible to create a intent that is both pending and implicit?
The only workaround I can think of right now is to create an Activity in my app that does nothing but launch the external app.
I did try creating the intent from the URI then doing the following, but nothing happens when you click the notification:
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Well, a lot later, I think I have the solution for you.
For all the other guys who are searching for an answer to launching an external app from your own custom notification.
Here it is:
public void createMyNotification(String titl, String titlcont, String conti){
Context context = getApplicationContext();
PackageManager pm = context.getPackageManager();
Intent LaunchIntent = null;
String apppack = "com.mycompany.appack.apname.app";
String name = "";
try {
if (pm != null) {
ApplicationInfo app = context.getPackageManager().getApplicationInfo(apppack, 0);
name = (String) pm.getApplicationLabel(app);
LaunchIntent = pm.getLaunchIntentForPackage(apppack);
}
Toast.makeText(context,"Found it:" + name,Toast.LENGTH_SHORT).show();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Intent intent = LaunchIntent; // new Intent();
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = new Notification.Builder(this)
.setTicker(titl)
.setContentTitle(titlcont)
.setContentText(conti)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
noti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
}
This does not use an additional Activity to launch the external app.
If you know packageName what you want start it, You can get Intent for startActivity.
Read this link start application knowing package name
I don't know if this is the best approach, but this is the solution that ended up working:
Create the notification
//Create the pending intent
Intent intent = new Intent(context, MyActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MyActivity.class);
stackBuilder.addNextIntent(intent);
PendingIndent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//Create the notification builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle("Notification Title")
.setContentText("Hello world!")
.setContentIntent(pendingIntent); //Attach the pending intent to launch when notification is clicked
//Send the notification
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, builder.build());
MyActivity.java
public class MyActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create implicit intent - see http://developer.android.com/training/basics/intents/sending.html
String uri = "...";
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
I'd still be interested to know if there's a way to bypass having an additional Activity that does nothing but launch an implicit intent.
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();
I can find a way to send parameters to my activity from my notification.
I have a service that creates a notification. When the user clicks on the notification I want to open my main activity with some special parameters. E.g an item id, so my activity can load and present a special item detail view. More specific, I'm downloading a file, and when the file is downloaded I want the notification to have an intent that when clicked it opens my activity in a special mode. I have tried to use putExtra on my intent, but cant seem to extract it, so I think I'm doing it wrong.
Code from my service that creates the Notification:
// construct the Notification object.
final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());
final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
contentView.setImageViewResource(R.id.image, R.drawable.icon);
contentView.setTextViewText(R.id.text, tickerText);
contentView.setProgressBar(R.id.progress,100,0, false);
notif.contentView = contentView;
Intent notificationIntent = new Intent(context, Main.class);
notificationIntent.putExtra("item_id", "1001"); // <-- HERE I PUT THE EXTRA VALUE
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(id, notif);
Code from my Activity that tries to fetch the extra parameter from the notification:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle extras = getIntent().getExtras();
if(extras != null){
Log.i( "dd","Extra:" + extras.getString("item_id") );
}
The extras is always null and I never gets anything into my log.
Btw... the onCreate is only run when my activity starts, if my activity is already started I also want to collect the extras and present my activity according to the item_id I receive.
Any ideas?
Take a look at this guide (creating a notification) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".
For managing if the activity is already running you have two ways:
Add FLAG_ACTIVITY_SINGLE_TOP flag to the Intent when launching the activity, and then in the activity class implement onNewIntent(Intent intent) event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.
Same as number one, but instead of adding a flag to the Intent you must add "singleTop" in your activity AndroidManifest.xml.
If you use intent extras, remeber to call PendingIntent.getActivity() with the flag PendingIntent.FLAG_UPDATE_CURRENT, otherwise the same extras will be reused for every notification.
I had the similar problem my application displays message notifications.
When there are multiple notifications and clicking each notification it displays that notification detail in a view message activity. I solved the problem of same extra parameters is being received in view message intent.
Here is the code which fixed this.
Code for creating the notification Intent.
Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
notificationIntent.putExtra("NotificationMessage", notificationMessage);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);
Code for view Message Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("NotificationMessage"))
{
setContentView(R.layout.viewmain);
// extract the extra-data in the Notification
String msg = extras.getString("NotificationMessage");
txtView = (TextView) findViewById(R.id.txtMessage);
txtView.setText(msg);
}
}
}
Maybe a bit late, but:
instead of this:
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
Log.i( "dbg","onNewIntent");
if(extras != null){
Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));
}
mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}
Use this:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("keyName");
}
Encounter same issue here.
I resolve it by using different request code, use same id as notification, while creating PendingIntent. but still don't know why this should be done.
PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(**id**, notif);
After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.
like this:
Intent notificationIntent = new Intent(Main.this, Main.class);
notificationIntent.putExtra("sport_id", "sport"+id);
notificationIntent.putExtra("game_url", "gameURL"+id);
notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));
I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...
I tried everything but nothing worked.
eventually came up with following solution.
1- in manifest add for the activity
android:launchMode="singleTop"
2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()
Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);
Bundle bundle = new Bundle();
bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
new Random().nextInt(), notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
AndroidManifest.xml
Include launchMode="singleTop"
<activity android:name=".MessagesDetailsActivity"
android:launchMode="singleTop"
android:excludeFromRecents="true"
/>
SMSReceiver.java
Set the flags for the Intent and PendingIntent
Intent intent = new Intent(context, MessagesDetailsActivity.class);
intent.putExtra("smsMsg", smsObject.getMsg());
intent.putExtra("smsAddress", smsObject.getAddress());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MessageDetailsActivity.java
onResume() - gets called everytime, load the extras.
Intent intent = getIntent();
String extraAddress = intent.getStringExtra("smsAddress");
String extraBody = intent.getStringExtra("smsMsg");
Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.
It's easy,this is my solution using objects!
My POJO
public class Person implements Serializable{
private String name;
private int age;
//get & set
}
Method Notification
Person person = new Person();
person.setName("david hackro");
person.setAge(10);
Intent notificationIntent = new Intent(this, Person.class);
notificationIntent.putExtra("person",person);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
.setPriority(2)
.setLargeIcon(bm)
.setTicker(fotomulta.getTitle())
.setContentText(fotomulta.getMessage())
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setContentTitle(fotomulta.getTicketText())
.setDefaults(Notification.DEFAULT_ALL);
New Activity
private Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_push);
person = (Person) getIntent().getSerializableExtra("person");
}
Good Luck!!
In your notification implementation, use a code like this:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
...
Intent intent = new Intent(this, ExampleActivity.class);
intent.putExtra("EXTRA_KEY", "value");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pendingIntent);
...
To Get Intent extra values in the ExampleActivity, use the following code:
...
Intent intent = getIntent();
if(intent!=null) {
String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...
VERY IMPORTANT NOTE: the Intent::putExtra() method is an Overloaded one. To get the extra key, you need to use Intent::get[Type]Extra() method.
Note: NOTIFICATION_ID and NOTIFICATION_CHANNEL_ID are an constants declared in ExampleActivity
After doing some search i got solution from android developer guide
PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ArticleDetailedActivity.class);
contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
To Get Intent extra value in Test Activity class you need to write following code :
Intent intent = getIntent();
String extra = intent.getStringExtra("extra") ;
Please use as PendingIntent while showing notification than it will be resolved.
PendingIntent intent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Add PendingIntent.FLAG_UPDATE_CURRENT as last field.
G'day,
I too can say that I tried everything mentioned in these posts and a few more from elsewhere.
The #1 problem for me was that the new Intent always had a null bundle.
My issue was in focusing too much on the details of "have I included .this or .that".
My solution was in taking a step back from the detail and looking at the overall structure of the notification. When I did that I managed to place the key parts of the code in the correct sequence.
So, if you're having similar issues check for:
1. Intent notificationIntent = new Intent(MainActivity.this, NotificationActivity.class);
2a. Bundle bundle = new Bundle();
//I like specifying the data type much better. eg bundle.putInt
2b. notificationIntent.putExtras(bundle);
3. PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, WIZARD_NOTIFICATION_ID, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
4. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
5. NotificationCompat.Builder nBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(false)//false is standard. true == automatically removes the notification when the user taps it.
.setColor(getResources().getColor(R.color.colorPrimary))
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationManager.notify(WIZARD_NOTIFICATION_ID, nBuilder.build());
With this sequence I get a valid bundle.
If you use
android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"
in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:
Intent notificationClick = new Intent(context, NotifyActivity.class);
Bundle bdl = new Bundle();
bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
notificationClick.putExtras(bdl);
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // schließt tasks der app und startet einen seperaten neuen
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotifyActivity.class);
stackBuilder.addNextIntent(notificationClick);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(notificationPendingIntent);
Important is to set unique data e.g. using an unique id like:
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));