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

后端 未结 4 410
一个人的身影
一个人的身影 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 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 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

    
    

提交回复
热议问题