Android, Detect when other apps are launched

后端 未结 7 1053
臣服心动
臣服心动 2020-11-22 02:41

I\'m trying to develop an app that prevents a user from getting to a specified app without a password. The scenario is...

  1. user clicks on \"Email\" app (for exa
7条回答
  •  灰色年华
    2020-11-22 03:14

    class CheckRunningActivity extends Thread{
        ActivityManager am = null;
        Context context = null;
    
        public CheckRunningActivity(Context con){
            context = con;
            am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        }
    
        public void run(){
            Looper.prepare();
    
            while(true){
                // Return a list of the tasks that are currently running,
                // with the most recent being first and older ones after in order.
                // Taken 1 inside getRunningTasks method means want to take only
                // top activity from stack and forgot the olders.
                List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
    
                String currentRunningActivityName = taskInfo.get(0).topActivity.getClassName();
    
                if (currentRunningActivityName.equals("PACKAGE_NAME.ACTIVITY_NAME")) {
                    // show your activity here on top of PACKAGE_NAME.ACTIVITY_NAME
                }
            }
            Looper.loop();
        }
    }
    

    You can get current running Activity and check if this Activity corresponds to Email application.

    Run CheckRunningActivity Thread on Application start (or on device boot).

    new CheckRunningActivity().start();
    

    Update: This class need android.permission.GET_TASKS permission, so add next line to the Manifest:

    
    

提交回复
热议问题