一.监听线程类:

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 stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);            // Sort the stats by the last time used            if (stats != null) {                SortedMap, UsageStats> mySortedMap = new TreeMap, 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"?>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">            android:id="@+id/btn_start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开始观察" />





更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  2. 获取Android(安卓)Device的信息
  3. Android中获取应用程序(包)的信息-----PackageManager的使用(一)
  4. android 判断网络是否连接
  5. Android(安卓)JSON 解析
  6. android 入门demo 解析xml
  7. android 工具类2
  8. android 多点触摸绘画demo
  9. Android(安卓)获取手机当前所在的经纬度

随机推荐

  1. 这15个Android开源库,只有经常逛Github的
  2. Android学习14--Android应用资源
  3. 【设计模式与Android】策略模式——锦囊
  4. Android(安卓)设置应用的底部导航栏(虚拟
  5. 【设计模式与Android】模板方法模式——
  6. android 上企业信息云端查看及实现
  7. 移动经分升级到 android4.x 版本后的一个
  8. android 上网 (一)-- apn切换拨号
  9. Android(安卓)Scroller的使用及自我理解
  10. 把手机变成鼠标和触摸板,附android/iphone