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" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…