Aug 29, 2013

Detect home button press in android and Notify when Our app is Closed

In this Code I am explaining how to Notify when app is closed using Home button or Exit Button 

From ICS to android not Supporting major Events when app is closed , so we can not now beofre application close , but using activity manager we can get Running app Package name and Its contained Activity class 

use below code in your onPause so When ever your application close it returns true 

// Method  to Check Our app is running or Not
public static boolean isAppSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
Log.w(" YES TRUE ", "isAppSentToBackground ");
return true;
}
   }
Log.w(" YES FALSE ", "isAppSentToBackground ");
return false;
}


// Checking while App is closed in Onpause or onStart or OnDestroy 

mCtx=getApplicationContext();

@Override
protected void onPause() {
super.onPause();
if (isAppSentToBackground(mCtx)) {
// Do what ever you want after app close 
// simply Close session 
 }
}

No comments:

Post a Comment