一.监听线程类:
package com.example.lxb.topapp70; import android.content.Intent; import android.os.Build; import android.provider.Settings; import android.util.Log; /** * Created by lxb on 2017/4/1. */ public class TopAppListenThread extends Thread { private boolean terminated = false; // 停止请求标志 private static final String curAppId = "curAppId"; private String sCurApp = ""; private String sLastApp = ""; public TopAppListenThread() { } public void run() { while (!terminated) { try { Thread.sleep(3000); listenAppTask(); } catch (InterruptedException e) { terminated = true; } } } public void cancel() { terminated = true; interrupt(); } /** * 监听app任务栈 */ private void listenAppTask() throws InterruptedException { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { boolean useGranted = SystemUtils.isUseGranted(); if (useGranted) { curAppCheck(true); } else { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); //开启应用授权界面 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); AppContext.getAppContext().startActivity(intent); } } else { curAppCheck(false); } } /** * 检测当前appId与栈顶元素是否一致, * 如果不一致就发信号通知本地服务当前应用已发生改变 * * @param bIsHighVersion */ private void curAppCheck(boolean bIsHighVersion) { sCurApp = bIsHighVersion ? SystemUtils.getHigherPackageName() : SystemUtils.getLowerVersionPackageName(); if(!sCurApp.equals(sLastApp)){ notifyLocalServer(sCurApp); } sLastApp = sCurApp; Log.e("TopAppService", "顶层app=" + sCurApp); } /** * notify本地服务有当前顶端应用更新了 * * @param appId */ private void notifyLocalServer(String appId) { System.out.println("36-------------------------write: " + appId); } }
二.系统工具类:
package com.example.lxb.topapp70; import android.app.ActivityManager; import android.app.AppOpsManager; import android.app.usage.UsageStats; import android.app.usage.UsageStatsManager; import android.content.ComponentName; import android.content.Context; import android.os.Build; import android.util.Log; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; /** * Created by lxb on 2017/4/1. */ public class SystemUtils { /** * 判断 用户查看历史记录的权利是否给予app * * @return */ public static boolean isUseGranted() { Context appContext = AppContext.getAppContext(); AppOpsManager appOps = (AppOpsManager) appContext.getSystemService(Context.APP_OPS_SERVICE); int mode = -1; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { mode = appOps.checkOpNoThrow("android:get_usage_stats", android.os.Process.myUid(), appContext.getPackageName()); } boolean granted = mode == AppOpsManager.MODE_ALLOWED; return granted; } /** * 高版本:获取顶层的activity的包名 * * @return */ public static String getHigherPackageName() { String topPackageName = ""; Context appContext = AppContext.getAppContext(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { UsageStatsManager mUsageStatsManager = (UsageStatsManager) appContext.getSystemService(Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); // We get usage stats for the last 10 seconds //time - 1000 * 1000, time 开始时间和结束时间的设置,在这个时间范围内 获取栈顶Activity 有效 List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time); // Sort the stats by the last time used if (stats != null) { SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>(); for (UsageStats usageStats : stats) { mySortedMap.put(usageStats.getLastTimeUsed(), usageStats); } if (mySortedMap != null && !mySortedMap.isEmpty()) { topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName(); //Log.e("TopPackage Name", topPackageName); } } } return topPackageName; } /** * 低版本:获取栈顶app的包名 * * @return */ public static String getLowerVersionPackageName() { String topPackageName; //低版本 直接获取getRunningTasks Context appContext = AppContext.getAppContext(); ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE); ComponentName topActivity = activityManager.getRunningTasks(1).get(0).topActivity; topPackageName = topActivity.getPackageName(); return topPackageName; } }
三.测试类:
public class MainActivity extends AppCompatActivity { private static final String curAppId = "curAppId"; private TopAppListenThread topAppListenThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); topAppListenThread = new TopAppListenThread(); initView(); } private void initView(){ findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //observerLogic(); topAppListenThread.start(); } }); }
布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.lxb.topapp70.MainActivity"> <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始观察" /> </RelativeLayout>