how to check the top activity from android app in background service

笑着哭i 提交于 2019-11-29 12:57:51

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" />

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.

Martin Marconcini

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!