Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
Log.d("topActivity", "CURRENT Activity ::"
         + taskInfo.get(0).topActivity.getClassName());
ComponentName componentInfo = taskInfo.get(0).topActivity;
componentInfo.getPackageName();

But i want to run this code in background service.So that i can detect When other app launches through this.So is there any idea to do this.Plz help me.thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...