In my app i want to check whethere any other app launches or not from my app.So i am currently usimg Activitymanager to find the top activity like this
Act
You should use Service for this. Then only you can achieve the background process..Please Go through about Services http://developer.android.com/guide/components/services.html and you can see this also http://www.vogella.com/articles/AndroidServices/article.html both URLs will help you
instead of service Use receiver to receive the launch event and there you can implement this code.
By using service you can achieve this..
public void checkActivity() {
handler = new Handler();
activityRunnable = new ActivityRunnable();
handler.postDelayed(activityRunnable, 500);
}
private class ActivityRunnable implements Runnable {
@Override
public void run() {
ActivityManager manager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
if (runningTasks != null && runningTasks.size() > 0) {
ComponentName topActivity = runningTasks.get(0).topActivity;
// Here you can get the TopActivity for every 500ms
if(!topActivity.getPackageName().equals(getPackageName())){
// Other Application is opened
}
handler.postDelayed(this, 500);
}
}
}
Call the checkActivity()
in onCreate of service
and dont forgot to remove the handler.removeCallbacks(activityRunnable);
callbacks in onDestroy
start the service in LauncherActivity onCreate
and stop the service in LauncherActivity onDestroy
Note: Dont forgot to add the permission in your manifest
<uses-permission android:name="android.permission.GET_TASKS" />
The approach you are taking is wrong and prone to have your app rejected from the Google Play Store (plus it may stop working).
Check this thread to see possible ways to detect wether your app went to the background or not.