I'm developing some kind of media controls for my android wear. The scenario is the following:
The WearableListenerService in the wear app is notified when the media data changes, i.e. artist/title. An ongoing notification is shown which has a full screen second page with some controls in it.
Because I don't want it to show on my smartphone, the notifications are build in the wearable app.
The second page consists of an activity baked in a display intent:
Intent pageIntent = new Intent(this, ControlActivity.class);
pageIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
pageIntent,
0);
Notification controlPage = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.extend(
new Notification.WearableExtender()
.setCustomSizePreset(Notification.WearableExtender.SIZE_FULL_SCREEN)
.setDisplayIntent(pendingIntent))
.build();
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(currentArtist)
.setContentText(currentTitle)
.setOngoing(true)
.extend(
new NotificationCompat.WearableExtender()
.addPage(controlPage)
.addAction(new NotificationCompat.Action(button, null, intent))
.setContentAction(0)
.setContentIcon(button)
.setBackground(BitmapFactory.decodeResource(getResources(), bg))
.setHintHideIcon(true)
)
.build();
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification);
Now the notification is refreshed from time to time to display new data on the first notification page which forces the activity in the second page to be recreated every time the notification is updated. This results in some ugly behavior where the user can see that the activity inside the second page is recreated.
Is there any way to prevent the activity in the second page from being completely recreated (onDestroy, onCreate) and/or only update the data on the first page of the notification as it should be?
Is it the PendingIntent creation that doesn't really work here?
The Manifest entry looks as the following:
<activity
android:name=".media.ControlActivity"
android:allowEmbedded="true"
android:exported="true"
android:launchMode="singleTop"
>
I've tried all combinations of flags as well as only updating the necessary parts but nothing changes.
Help is greatly appreciated. Let me know if you need further information.
Edit: The main problem seems to be that the embedded activity (for a custom layout) in the second page of the notification is always recreated as soon as I call notify. Reusing, only updating changed values on the first page or updating nothing has no effect.
Simply broadcast the new information to your second activity and update the fields when you receive the broadcast. And make it local so the broadcast concerns only your application.
In the second activity add the BroadcastReceiver as a member attribute :
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
/*do what you're supposed to do, update your data
you get the information from the intent by calling intent.getXExtra() as usual*/
}
};
And register it in your onCreate() method :
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("your-filter-name"));
In your notification activity, when you update the information, add this :
Intent intent = new Intent("your-filter-name");
intent.putExtra(...);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Your second activity won't be recreated each time and the modifications should go smoothly :)
there is no method to prevent recreate the embedded activity in the notification, you can try this way in your sence.
use a action in second page, and start activity when click the action, when the notification is updated by time, the activity will not be recreated
Related
I am using the following code showing the notification, it works properly. I am look for the listener from which i can come to know whether the notification is expanded or not.
I want to open the app if the notification is expanded or else open the particular activity of the app.
Intent intent= new Intent(context, Activity1.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, getNextRandom(), intent, 0);
Builder newBuilder newBuilder = new Notification.Builder(context);
newBuilder.setContentTitle(title)
.setContentText(subtitle)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon)
.setTicker(notificationMessage)
.setContentIntent(pendingIntent);
Notificationnotification = new Notification.BigTextStyle(newBuilder)
.setBigContentTitle(notificationTitle)
.bigText(text)
.build();
Let me know if there is way to acheive this?
There is no way to know if the notification is open... What you can do is add buttons to the expanded notification that pressing on them will act differently than pressing on the notification itself.
There maybe no direct way, but maybe the following hack can help!!
You can have a custom notification layout and use RemoteView, Set a setOnClickPendingIntent to launch a service for the entire view so that you get notified when the notification is clicked.
When the user clicks the notification, service is started and show the new expanded custom layout from the service (you replace the old notification with the new one)
Maybe show your initial notification also from the same service using startforeground, so that your app is not killed and the view click can be received faster since service is already running and response time for changing the view is lower.
see this for remoteview and this for launching service from notification click.
My android application generates a notification. This notification is definid in the following way:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_alarms)
.setContentTitle("title")
.setContentText("example text");
Intent resultIntent = new Intent(this, MyActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
So when I open the notification drawer and click on the notification area, the actvity MyActivity starts. But, If another instance of the MyActivty is already running, I obtain that two MyActivty instances will running at the same time, while I want that always just one instance at time, runs in my application.
I have tried using
android:launchMode="singleTop"
android:clearTaskOnLaunch="true"
but the result is the same.
How can I achieve this task?
Ultimately, you probably need to think about using Fragments, instead of Activities for the kind of UI interaction you are wanting (and really the way the NavDrawer is designed to work - and they way the official examples implement it).
You can use different intent flags to bring an old Activity back to the front, but this is really not the intended behavior you ultimately need (which is Fragment related).
Ex Intent Flags
Intent intent = new Intent(this, ActivityExamlpe.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
I have a method which receives text from a push notification, via the Parse API, and packages it into a notification object. Pretty standard stuff. My problem is that I'm trying to use a BigTextStyle to display my notification in the list, but it refuses to do so, and only shows one line of text and the two-finger gesture does not cause it to expand.
However, if I tap the notification, which opens the app, then return to the notification list, it is displayed in the BigTextStyle and is responsive to gestures. So, my guess is that somehow tapping on the notification is activating it and allowing the BigTextStyle code to kick in.
I like that tapping on the notification opens the app, but I don't want to force my users to open the app then close it again to see the full text of my messages. So is there a way I could either make the notification display in the BigTextStyle format from the start, or to make it so that the first click "activates" the notification, allowing the full message text to be seen, and then a second click opens the app? Any help would be appreciated.
Here is my code from the Notification method:
public void receiveNotification() {
NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle();
bts.bigText(SplashActivity.globalDataString);
bts.setSummaryText("Tap to open app, swipe to dismiss message");
NotificationCompat.Builder m = new NotificationCompat.Builder(this);
m.setContentTitle("New Push Notification")
.setContentText(SplashActivity.globalDataString)
.setSmallIcon(R.drawable.app_icon)
.setStyle(bts)
.build();
Intent openApp = new Intent(this, MenuActivity.class);
// This ensures that navigating backward from the Activity leads out of
// the application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MenuActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(openApp);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
m.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(pushMessageID, m.build());
pushMessageID++;
//reset notification
flag1 = false;
}
EDIT: I think my problem is with where I'm calling my receiveNotification() method from. Right now I have it in the onCreate() method of my app's starting activity, which doesn't make much sense looking back. Should I put it in my broadcastReceiver class, or would there be a better place to put it?
Yes, the creation and display of the notification is usually done either in the broadcast receiver, or in an intent service started by the broadcast receiver. Only when the user taps the notification, the relevant activity is launched. You can see Google's client code sample here.
There are a lot of questions/answers about how to start an application from within your application in Android. But those solutions do not produce the same flow as if an icon was tapped in Android launcher.
For example, I do this (this is used with notifications):
intent = context.getPackageManager().getLaunchIntentForPackage("com.test.startup");
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Then when I tap on notification the app is started, however, it is started somewhat differently than when I tap the icon in the App drawer. Specifically: with this approach my main Activity is always created (i.e. onCreate() then onResume() is called). However, if application was already started and then put in background, then starting it from Launcher will only cause onResume() of currently shown activity to be called (not onCreate() on the main one). Is there a way to trigger the same resume flow programmatically from within my app?
To summarize the task: when user taps on notification I need my app to be either started (if it's not already), or brought to the foreground in its current state (if it's in background) and have some data passed to it. The app will then take care of handling/rendering that data.
Your app is behaving the way it supposed to. Even if you try the launch the app from App drawer it will call the same callback. You have to understand the lifecycle. As your activity is in the background onCreate will not get called. But for the handling the data from the notification intent you should utilize callback method OnNewIntent() in activity. You should override this method and extract the data the from the new intent and should update UI. After onNewIntent onresume will be called.
I hope this solves your problem.
Here is my onPause code which works the way you expected i.e when user clicks on the notification it doesnt call onCreate again:
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(getApplicationContext(), PlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(getBaseContext(), 0, intent,0);
NotificationCompat.Builder noti =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_media_play)
.setContentTitle("Nepali Music And more")
.setContentText("Playing");
noti.setContentIntent(pIntent);
noti.setAutoCancel(true);
noti.setOngoing(true);
Notification notification = noti.getNotification();
notificationManager.notify(1, notification);
Focus mainly on the intent flags
You want to use the intent flags Intent.FLAG_ACTIVITY_CLEAR_TOP to find your activity and clear the stack above it. You also need the Intent.FLAG_ACTIVITY_SINGLE_TOP flag to prevent your activity from being recreated (to resume).
The Intent.FLAG_ACTIVITY_SINGLE_TOP is necessary since by default, the launch mode is "standard" which lets you create multiple instances of your activity. If you were to set your launch mode to SingleTop, then this flag own't be necessary
I have a service that shows a notification that I wish that will be able to go to a specific activity of my app each time the user presses on it. Usually it would be the last one that the user has shown, but not always.
If the activity was started before, it should return to it, and if not, it should open it inside of the app's task, adding it to the activities tasks.
In addition, on some cases according to the service's logic, I wish to change the notification's intent so that it will target a different activity.
How do i do that? Is it possible without creating a new notification and dismissing the previous one? Is it also possible without creating a new task or an instance of an activity?
No it wouldn't be possible to change the Activity once you have sent the notification.
You can start an Activity on your task stack that is not a problem, check out the notification service in the tutorial here:
http://blog.blundell-apps.com/notification-for-a-user-chosen-time/
You have to set a pending intent on the notification:
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SecondActivity.class), 0);
// Set the info for the view that shows in the notification panel.
notification.setLatestEventInfo(this, title, text, contentIntent);
You can see the pending intent takes a normal intent "new Intent(this, SecondActivity.class" so if you want specific behaviour (like bringing to the top instead of starting a new activity. Add the flags like you would normally to this intent. i.e. FLAG_ACTIVITY_REORDER_TO_FRONT (something like that)
Since platform version 11, you can build a notification using Notification.Builder. The v4 support library has an equivalent class NotificationCompat.Builder.
You can't change the Activity once you've sent the notification, but you can update the notification with a new Intent. When you create the PendingIntent, use the flag FLAG_CANCEL_CURRENT. When you send the new notification, use the ID of the existing notification when you call NotificationManager.notify().
Also, you should be careful how you start your app. The Status Bar Notifications guide tells you how to set up the back stack.