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

后端 未结 4 400
一个人的身影
一个人的身影 2020-12-18 17:21

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         


        
相关标签:
4条回答
  • 2020-12-18 17:53

    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

    0 讨论(0)
  • 2020-12-18 17:57

    instead of service Use receiver to receive the launch event and there you can implement this code.

    0 讨论(0)
  • 2020-12-18 18:00

    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" />
    
    0 讨论(0)
  • 2020-12-18 18:02

    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.

    0 讨论(0)
提交回复
热议问题