Many of us might faced this kind of need in their app. It is much more simple to achieve this. I will discuss here what I tried and achieved.
You must be aware of activity life cycle. It states that when ever an activity goes to background(on tapping home button, phone call etc) it executes these series of methods.

onResume(activity is visible and active) -> onPause(before activity becomes invisible) -> onStop(activity invisible).

Yes activity executes onStop() and stays there without executing onDestroy() this is the state we call as app or activity is in background. At any time when we tap the app from stack it goes through below mentioned methods and becomes visible in the same state where we left before.

onRestart() -> onStart() -> again onResume(activity visible).

So I thought of triggering a notification(you can trigger or do whatever techniques you like) just before it goes to background and as a result on tapping the notification it will launch the activity.

Hence onPause() or onStop() methods are suitable to trigger a notification. I choose onStop().

@Override
	protected void onStop() {
		super.onStop();
		
		createNotification();
	}

	private void createNotification() {
		Intent homeIntent = new Intent(this, MainActivity.class);

//              by setting below mentioned action and category we can launch activity from background
		homeIntent.setAction(Intent.ACTION_MAIN);
		homeIntent.addCategory(Intent.CATEGORY_LAUNCHER);

//              or
//		homeIntent.setAction("android.intent.action.MAIN");
//		homeIntent.addCategory("android.intent.category.LAUNCHER");
		
//              Required pending intent
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, homeIntent,0);
		
//              to support API 14 I used NotificationCompat
		Notification notiBuilder = new NotificationCompat.Builder(this)   
				.setContentTitle("New mail from " + "test@gmail.com")
		        .setContentText("Subject")
		        .setSmallIcon(R.drawable.ic_launcher)
		        .setContentIntent(pendingIntent)
		        .addAction(R.drawable.ic_launcher, "Call", pendingIntent)
		        .addAction(R.drawable.ic_launcher, "More", pendingIntent)
		        .addAction(R.drawable.ic_launcher, "And more", pendingIntent).build();
		
//              notification will be cleared on tapping
		notiBuilder.flags |= Notification.FLAG_AUTO_CANCEL;	
		
//              triggering notification
		notificationManager.notify(0,notiBuilder);
	}

I used an editText for verification.

For source code github.

Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s