How do I display the same activity when clicking a notification? - java

I am developing a music player however when I click the notification which is created, a new version of this activity is displayed and not the one displaying the currently playing song and seekbar.
The current code I'm using for the notification is
Intent i = new Intent(this, AmplitudeMusicPlayer.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0 , i, 0);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder noti = new NotificationCompat.Builder(this);
noti.setContentTitle("Now Playing")
.setContentText(songTitle)
.setSmallIcon(R.drawable.default_art)
.setContentIntent(pIntent);
notificationManager.notify(0, noti.build());

Which launch mode are you declaring for your activity?
http://developer.android.com/guide/topics/manifest/activity-element.html#lmode
The "standard" and "singleTop" modes differ from each other in just
one respect: Every time there's a new intent for a "standard"
activity, a new instance of the class is created to respond to that
intent. Each instance handles a single intent. Similarly, a new
instance of a "singleTop" activity may also be created to handle a new
intent. However, if the target task already has an existing instance
of the activity at the top of its stack, that instance will receive
the new intent (in an onNewIntent() call); a new instance is not
created. In other circumstances — for example, if an existing instance
of the "singleTop" activity is in the target task, but not at the top
of the stack, or if it's at the top of a stack, but not in the target
task — a new instance would be created and pushed on the stack.

Related

How to create a notification with Action in android

I'm wondering how to create a notification in android with action icons that allowed me to call a method in the main activity.
just like the one in this image : Notification icon exemple
First Welcome to stackoverflow. I'd like to remind you this is not a website to learn how to program but a website to ask questions with actual problems that can help the community. Your questions have to be detailed and specific with your code or attempt as well as the error log.
That being said, here is the best way to create a notification:
Step 1 - Create Notification Builder
First step is to create a notification builder using NotificationCompat.Builder.build(). You can use Notification Builder to set various Notification properties (small icons, large icons, title, priority etc)
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
Step 2 - Setting Notification Properties
Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following −
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("I'm a notification alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
Step 3 - Attach Actions
This is optional and only required if you want to attach an action with the notification. An action will allows users to go directly from the notification to an Activity in your application (where they can look at one or more events or do further work).
The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder.
For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().
A PendingIntent object helps you to perform an action on your application's behalf, often at a later time, regardless whether or not your application is running.
Also there's the stackBuilder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// 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);
mBuilder.setContentIntent(resultPendingIntent);
Step 4 - Issue the notification
Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
I hope this answers your question.

Why android notifications are not occurring after every 2 mins?

I am trying to create a notification after every 2 mins but , only single notification is getting created(when app is started).
My code is :
notifyme.java :
public class notifyme extends Service {
#Override
public void onCreate() {
super.onCreate();
Intent intent=new Intent(this,MainActivity.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notify=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Hello")
.setContentText("Some random text")
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManager nMgr=(NotificationManager)this.getSystemService(this.NOTIFICATION_SERVICE);
Random r=new Random();
int nid=r.nextInt(50000)+1;
nMgr.notify(nid,notify.build());
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In MainActivity.java :
Intent notificationIntent = new Intent(this, notifyme.class);
PendingIntent contentIntent = PendingIntent.getService(getApplicationContext(), 0, notificationIntent,0);
AlarmManager am = (AlarmManager) getSystemService(this.ALARM_SERVICE);
am.cancel(contentIntent);
am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),120*1000, contentIntent);
first you don't need a whole service to show a notification, if that's all it's doing, you could use a BroadcastReceiver and use PendingIntent.getBroadcast method. BroadcastReceiver needs less memory and doesn't have any life-cycle (which could complicate things).
The reason you're not seeing more than one notification is on the line nMgr.notify(119,notify.build());
This number 119 is the notification ID. So after X seconds that it's executing that code again, your new notification is directly replacing the old one and it all looks as if it hasn't changed.
If you want to put several notifications up (AKA. SPAM the user), you should always change that number. maybe using a Random
First of all, making new notifications in every two seconds is completely against guidelines.
As docs says :
When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
Instead, you should consider updating a previous notification, either
by changing some of its values or by adding to it, or both.
here the issue is that you are using the same ID to create the notification. (here 19).
When you publish a notification, if there is an active notification with the same id. notificatipon manager will update the existing one. So everytime the service is running, it just updates the notification with id "19".
If you are keen on issuing notifications on every 2 minutes (Which will affect the user-experience of your app very badly, let me warn you), try giving different ids to the notifications. You can save the issued ids in SharedPreferences or something.

Resuming current background activity on notification

My application contains multiple activities. I have implemented push notifications and also shown the notification in bar. My issue is, when i click on notification is take me to the specific activity that i has specified.
Intent intent =new Intent(GcmService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(GcmService.this, 0, intent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
getApplicationContext())
.setContentTitle(getResources().getString(R.string.app_name))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
notificationBuilder.setContentIntent(pendingIntent);
mNotificationManager.notify((int) when, notificationBuilder.build());
I want if my activity is in background, and user click on the notification app resume the current activity that is in background and show dialog box.
And if my application is closed. open the Launching activity and then show the dialog box.
If you want to continue again when you click the notification(in this case your application still running on background) than you can using this method :
http://developer.android.com/training/basics/activity-lifecycle/stopping.html
I've tried it and it works.
You can link your notification to a DispatcherActivity.
If you have open Activities on the backstack, finish the DispatcherActivity suddenly in onCreate(). If not, forward to your launching activity and finish the DispatcherActivity too.
To track your active activities on backstack use this How to know Activity Count of my application? suggestions.

Can I use NotificationCompat.BigTextStyle without crashing on older devices?

I don't have any device older than 4.1 to test on. I'm trying to test out pushing my notifications with the code below. It's mostly all taken from the Notification documentation. Would my code crash or does the NotificationCompat class handle all of this for me gracefully?
Under the "Handling Compatability" section it reads:
Handling compatibility
Not all notification features are available for a particular version,
even though the methods to set them are in the support library class
NotificationCompat.Builder. For example, action buttons, which depend
on expanded notifications, only appear on Android 4.1 and higher,
because expanded notifications themselves are only available on
Android 4.1 and higher.
To ensure the best compatibility, create notifications with
NotificationCompat and its subclasses, particularly
NotificationCompat.Builder. In addition, follow this process when you
implement a notification:
...
So does this mean that if I use the NotificationCompat class it will handle all of the compatibility for me?
My code that I'm worried about (because it uses BigTextStyle):
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title")
.setContentText(String.format("%s", message));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(mContext, ActivityMain.class);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// 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);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Add max priority
mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
// Add bigTextStyle
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(String.format("%s", message));
mBuilder.setStyle(bigTextStyle);
mBuilder.setAutoCancel(true);
// mId allows you to update the notification later on.
mNotificationManager.notify(1, mBuilder.build());
You have nothing to worry about.
Helper class for generating large-format notifications that include a lot of text.
If the platform does not provide large-format notifications, this method has no effect. The user will always see the normal notification view.
(NotificationCompat.BigTextStyle)

Android Notification Opens On Existing Activity

I am in trouble with notification intents. I have a service(Service checks for messages and creates notification) which creates notifications. And application has an action bar and via slide menu users can navigate between activities.
http://i.stack.imgur.com/YJXe6.png
When user clicks notification it opens a new activity on the current activity.(Like an independent new instance). I want to open them in the same instance as if user navigating manually(Like clicking A when on B activity ie)
My current activity launchMode is standard(Although I tried singleTop and singleTask and flags)
Current Notification code :
Intent i = null;
i = new Intent(this, MessagesListActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,i, 0);
Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(msg);
notificationBuilder.setSmallIcon(R.drawable.speech_bubble_orange);
notificationBuilder.setContentIntent(contentIntent);
notificationBuilder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = notificationBuilder.build();
notificationManager.notify(Constants.UNREADMESSAGESNOTIFICATIONID,notification);
Thanks for your help.
I solved the problem. With this combination new launched activity clears stackback. I also did not change the launchmodes (still standard)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
In your manifest, you have to tag your activity as single instance, and keep the singleTask
android:launchMode= "singleTask" | "singleInstance"
in addition, you may have to remove the single top flag from your intent.
If I understood correctly, I think what you are looking for is the TaskStackBuilder. It allows you to create a backstack to provide proper navigation to the Activity being launched by the PendingIntent.
See the docs here for more information.

Categories

Resources