Android 获取当前Activity

方式一:

  /**
     * 在Application内添加监听
     */
    public void registerListenerLifecycle(){
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

方式二:
替换Instrumentation

//在 Application内初始化
public class TopActivityGet {

    private TopActivityGet(){}

    private static TopActivityGet instance;
    private static CInstrumentation cInstrumentation;
    private Activity activity;

    public static TopActivityGet getInstance(){
        if (instance == null){
            synchronized (TopActivityGet.class){
                if (instance == null){
                    instance = new TopActivityGet();
                    init();
                }
            }
        }
        return instance;
    }

    private static void init(){
        try {
            cInstrumentation = new CInstrumentation();
            Class cls = Class.forName("android.app.ActivityThread"); // ActivityThread被隐藏了,所以通过这种方式获得class对象

            Method mthd = cls.getDeclaredMethod("currentActivityThread", (Class[]) null); // 获取当前ActivityThread对象引用

            Object currentAT = null;
            currentAT = mthd.invoke(null, (Object[]) null);

            Field mInstrumentation = currentAT.getClass().getDeclaredField("mInstrumentation");

            mInstrumentation.setAccessible(true);//设置private变量为可读取

            mInstrumentation.set(currentAT, cInstrumentation); // 修改ActivityThread.mInstrumentation值
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Activity getTopActivity(){
        return activity;
    }

    public void setTopActivity(Activity activity){
        this.activity = activity;
    }
}

public class CInstrumentation extends Instrumentation {

    @Override
    public void callActivityOnResume(Activity activity) {
        super.callActivityOnResume(activity);
        TopActivityGet.getInstance().setTopActivity(activity);
    }
}

监听其他应用的最高Activity:需要向用户申请权限

public class AppMonitoringService extends AbsWorkService {

   private UsageStatsManager manager;
   
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        manager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);

        startMonitoring();
        return START_STICKY;
    }
//....
	
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startMonitoring(){
    	 UsageEvents usageEvents = manager.queryEvents(startTime, endTime);
        UsageEvents.Event event = new UsageEvents.Event();
//遍历这个事件集合,如果还有下一个事件
        while (usageEvents.hasNextEvent()){
            //得到下一个事件放入event中,先得得到下个一事件,如果这个时候直接调用,则	event的package是null,type是0。
            usageEvents.getNextEvent(event);
            //如果这是个将应用置于前台的事件
            if(event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND){
            //.............
            }
        }
       
    }


}

你可能感兴趣的:(Android)