Thursday, February 26, 2015

Reopen an activity in notification click in android

If you are looking to implement code for reopen an activity in notification click in android than follow the below code.

Example flow of the application for this type of functionality : If the application is not running and user click on notification than it will open the user dashboard and if the application is  and user click on notification than it will close the dashboard activity and reopen the activity page.




            ActivityManager am =(ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
ActivityManager.RunningTaskInfo task = tasks.get(0); // get current task
  ComponentName rootActivity = task.baseActivity;

Intent notificationIntent;
if(rootActivity.getPackageName().equalsIgnoreCase("your package name")){
                //your app is open
// Now build an Intent that will bring this task to the front
notificationIntent = new Intent();
notificationIntent.setComponent(rootActivity);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

}
else
{
    //your app is not open,start it by calling launcher activity
notificationIntent = new Intent(context, SplashActivity.class);


}
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);

Uri defaultSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

if (defaultSound == null) {
defaultSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if (defaultSound == null) {
defaultSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
}
}

Builder builder = new Notification.Builder(context)
.setContentTitle(title).setContentText(message)
.setContentIntent(intent).setSmallIcon(icon)
.setLights(Color.YELLOW, 1, 2).setAutoCancel(true)
.setSound(defaultSound);

Notification not = new Notification.BigTextStyle(builder).bigText(
message).build();

// builder.setStyle(new Notification.BigTextStyle().bigText(message)) ;

not.defaults |= Notification.DEFAULT_VIBRATE;
not.defaults |= Notification.DEFAULT_SOUND;

notificationManager.notify(0, not);

0 comments:

Post a Comment

Don't lose faith when you see others receive answers to their prayers

An elephant and a dog became pregnant at same time. Three months down the line the dog gave birth to six puppies. Six months later the dog...

 

G-Expo Template by Ipietoon Cute Blog Design