1. 程式人生 > >android監聽當前應用

android監聽當前應用

一.監聽執行緒類:

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>