The following is my code that configures notification bar.
PendingIntent pi = PendingIntent.getActivity(
getApplicationContext(),
0,
new Intent(getApplicationContext(), AudioActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_star)
.setContentTitle("My app")
.setContentText("works")
.setContentIntent(pi);
mNotificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE
);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
At runtime, I first show AudioActivity at front-ground, then I open the notification bar that shows a message like "My app works". Clicking on the message opens AudioActivity again.
But it seems that the system calls the onCreate method of AudioActivity when I click notification bar. And before that it does not call the onDestroy of the existing AudioActivity. I was wondering if I have two AudioActivity instances running, and how I can manage them. What I expected is it should have worked as how activities are switched and onStart is used rather onCreate.
Thanks.
The best solution for you is to make it call onNewIntent and reuse the existing activity
In the called activity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if ("action.action.myactionstring".equals(intent.getAction())) {
finish();
}
}
In the called activities mainfest entry
<activity android:name=".MyNotifiedActivity" >
<intent-filter>
<action android:name="action.action.myactionstring" />
...
</intent-filter>
</activity>
When creating the pending intent
Intent myIntent = new Intent("action string");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(
getApplicationContext(),
0,
myIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
The Intent.FLAG_ACTIVITY_SINGLE_TOP flag tells android to reuse the existing instance of the activity (if it exists). onNewIntent is called instead of onCreate, if it isnt already running, the it calls onCreate as usual
#Nick Cardoso: Here is the changed code. I think it works in the way that it does not call onCreate. I was only wondering why it does not call onNewIntent as you expected. Thanks.
PendingIntent pi = PendingIntent.getActivity(
getApplicationContext(),
0,
new Intent("com.example.myapp.ACTION_NOTIFICATION"),
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_star)
.setContentTitle("My app")
.setContentText("works")
.setContentIntent(pi);
mNotificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE
);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.ourradio.AudioActivity"
android:label="#string/title_activity_audio"
android:parentActivityName="com.example.ourradio.FeedActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ourradio.FeedActivity" />
<intent-filter>
<action
android:name="com.example.myapp.ACTION_NOTIFICATION" />
</intent-filter>
</activity>
<service
android:name="com.example.ourradio.AudioService"
android:label="#string/label_service_audio" >
</service>
</application>
#Joe C , a simpler solution maybe add the SINGLE_TOP flag in the androidManifest as a launchMode in the activity like this:
<activity
android:name="com.example.ourradio.AudioActivity"
android:label="#string/title_activity_audio"
android:parentActivityName="com.example.ourradio.FeedActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you can see this link for more information: http://www.intridea.com/blog/2011/6/16/android-understanding-activity-launchmode
Related
I have a single Activity in my app (called MainActivity) and when I send notification to user, I want it to get opened if the notification is clicked. the important point is to avoid activity recreation and if there is already an instance of it alive, bring it to front and deliver the data to it. to get this behavior I have tried:
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
.putExtra("data", ...);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and in manifest:
<activity
android:name="...activities.MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen.Light">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
activity>
but the onNewIntent(Intent intent) method never gets called when I touch the notification, instead onCreate is called and the activity is recreated. please note that since I'm testing, I send the notification from the MainActivity itself and while it is open, I drag status bar and click on my notification (which then recreates the MainActivity). what is the problem?
The code that you shared seems to be fine and only concern I see is setIntent() inside onNewIntent().
May be you can try removing them and check. And next is getApplicationContext() that you are passing in the PendingIntent. Try passing it as MainActivity.this.
Below is my snippet for reference. I done it in Kotlin instead of Java. However logic is same.
Manifest.xml
<activity
android:name = ".MainActivity"
android:launchMode = "singleTop">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Logic for generating notification residing in MainActivity
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
intent.putExtra("DATA", "SENT FROM PENDING INTENT")
val contentIntent = PendingIntent.getActivity(
applicationContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val b = NotificationCompat.Builder(this, getString(R.string.app_name))
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentIntent(contentIntent)
.setContentInfo("Info")
val nmanager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nmanager.notify(1, b.build())
And this is my onNewIntent() part
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Log.i("onNewIntent", "Called")
intent?.let {
binder.msgView.text = it.getStringExtra("DATA")
Log.i("onNewIntent:", "Received new intent data")
}
}
NOTE : With the help of button action I generate the notification from inside the MainActivity.
Well I've an app it has basicly three 3 classes which are 1-MainActivity, 2- DetailActivity and 3-Broadcast. even app was closed broadcastreceiver is working and if it receives something, it fires notification. when I pressed notification it is opening Detail class. until this point there is no problem it is working perfect. but if I press back in DetailActivity. it is directing to me home page of phone. but app should direct me to Main class. after app direct me to home page if I go back to app from background running apps it will start main class I am using docs codes which are:
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DetailActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
and
int id = 1;
...
Intent resultIntent = new Intent(this, DetailActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(DetailActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());
Actualy I found the answer after some try and error,
PendingIntent.FLAG_UPDATE_CURRENT
After changing this line it works fine, also instead of ".this" I am using getApplicationContext(); for context
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_IMMUTABLE
);
as #MeknessiHamida mentioned..you should override the OnBackPressed method and start a intent to launch your main activity.
you just need to override it in the detailsActivity ( as per your question's ) : make an intent that directs you to the main Activity:
#Override public void onBackPressed() {
//Include the code here
return; }
I use the GoogleTransitionIntentService to show a notification if a user enter a Geofence, but the notification recreate MainActivity.class. I want to resume this activity.
https://github.com/googlesamples/android-play-location/tree/master/Geofencing
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent notificationPendingIntent =
PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText("Test")
.setContentIntent(notificationPendingIntent);
builder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
Manifest:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You have to use launchmode as singleTop inside your menifest for the given activity.
android:launchMode = "singleTop"
Try adding android:launchMode="singleTop" for MainActivity in the manifest.
You can add flags like
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
and set
android:launchMode = "singleTop"
to activity in manifest.
From GoogleDoc
If the activity has launch mode singleTop (or the up intent contains FLAG_ACTIVITY_CLEAR_TOP), the parent is brought to the top of the stack, and its state is preserved. The intent is received by the activity's onNewIntent() method. If the activity has launch mode standard (and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP), the current activity and its parent are both popped off the stack, and a new instance of the parent activity is created to receive the navigation intent.
I have a notification that have an action "Open Dial". I want when I click on "Open dial" action. My notification will disappear and Dial will appear.
I tried setAutocancel(true) and set notification.flags = Notification.FLAG_AUTO_CANCEL but these not working.
I know that I can't use SetAutocancel and set Flag_Auto_Cancel when I set action for my notification. If i want do that, I must use cancel(id) function of NotificationManager.
My idea to do that is sending an IntentFilter and using BroadcastReceiver to receive it When "Open Dial" is clicked.
But I don't know how I can do that because Intent.Action_Dial is an activity. If I use PendingIntent.getBroacast(), functions in onReceive() of Broadcast will work, but Dial won't show. Anyone know how I can resolve this problem ?.
This is my notication:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Notification");
builder.setContentText("This is notification");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setTicker("This is ticker");
Intent intent = new Intent(Intent.ACTION_DIAL);
PendingIntent pendingIntent = PendingIntent.getActivity(this, MSG_B, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.mipmap.ic_launcher, "Dial", pendingIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
manager.notify(id, notification);
this is my receiver
NotificationCompat.Builder builder;
Notification notification;
NotificationManager manager;
#Override
public void onReceive(Context context, Intent intent) {
manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(intent.getAction().equals("download")){
Log.d("LOG","Download");
showNotify(3, context);
DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL();
downloadFileFromURL.execute("http://freebigpictures.com/wp-content/uploads/2009/09/river-edge.jpg");
}
else if(intent.getAction().equals("android.intent.action.DIAL")){
Log.d("LOG", "cacel Dial");
manager.cancel(NotificationServices.MSG_B);
}
else if(intent.getAction().equals("cancelActivity")){
Log.d("LOG","cacel Activity");
manager.cancel(NotificationServices.MSG_B);
}
else {
Log.d("LOG","Fail ABC");
}
}
This is mainifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".activity.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".services.NotificationServices"
android:enabled="true"
android:exported="true">
</service>
<receiver android:name=".broadcast.BroadcastReceiverImage">
<intent-filter>
<action android:name="download"/>
<action android:name="cancelDial"/>
<action android:name="cancelActivity"/>
<action android:name="android.intent.action.DIAL"></action>
</intent-filter>
</receiver>
</application>
The solution is to start the Activity in the BroadcastReceiver, after cancelling the Notification. Here is the code for the PendingIntent:
Intent intent = new Intent();
intent.setAction("cancelDial");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, MSG_B, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and the code for the BroadcastReceiver:
else if(intent.getAction().equals("cancelDial")){
Log.d("LOG", "Cancel Dial");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
manager.cancel(NotificationServices.MSG_B);
}
Hopefully it will help someone in the future.
I'm having an activity with some EditTexts and an Ongoing Notification.
After filling into EditTexts, I come back Home screen by pressing Home button (my app is running in background). All I want is to come back my activity with filled EditTexts (not to create a new one) when I click the Ongoing Notification.
I have tried this
How should i do from notification back to activity without new intent
And this
Notification click: activity already open
They don't work at all !!!
Below is my code snippet
ProtocolMonitorActivity.java
Intent resultIntent = new Intent(this, ProtocolMonitorActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ProtocolMonitorActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notiBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.noti_icon)
.setContentTitle("Protocol Monitor App")
.setContentText("Service is running")
.setOngoing(true);
notiBuilder.setContentIntent(resultPendingIntent);
notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(notiId, notiBuilder.build());
Manifest
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ProtocolMonitorActivity"
android:label="#string/app_name"
android:process="com.android.phone"
android:launchMode="singleTop"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEVELOPMENT_PREFERENCE" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ProtocolMonitorActivity" />
</activity>
</application>
Does someone have any idea on this?
Thank you so so much!!!
You cannot do this using TaskStackBuilder. The behaviour of TaskStackBuilder is that it always clears the task (recreating any activites).
You just need a "launch Intent" to bring your task to the foreground in whatever state it happens to be in. There's 2 ways to do this:
Varient 1:
final Intent notificationIntent = new Intent(this, ProtocolMonitorActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Variant 2:
final Intent notificationIntent =
PackageManager.getLaunchIntentForPackage(getPackageName());
Then do:
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notiBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.noti_icon)
.setContentTitle("Protocol Monitor App")
.setContentText("Service is running")
.setOngoing(true);
notiBuilder.setContentIntent(resultPendingIntent);
notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(notiId, notiBuilder.build());
Just insert this line
resultIntent.setAction(Intent.ACTION_MAIN);
set android:launchMode="singleTop" in your activity tag in menifest inside required activity.