1. 程式人生 > >Android 如何監控當前Foreground Activity,如何獲知應用程式的啟動

Android 如何監控當前Foreground Activity,如何獲知應用程式的啟動

public class CurrentApplicationPackageRetriever {
    private final Context context;
    public CurrentApplicationPackageRetriever(Context context) {
        this.context = context;
    }
    public String[] get() {
        if (Build.VERSION.SDK_INT < 21)
            return getPreLollipop();
        else
            return getLollipop();
    }
    private String[] getPreLollipop() {
        @SuppressWarnings("deprecation")
        List<ActivityManager.RunningTaskInfo> tasks =
            activityManager().getRunningTasks(1);
        ActivityManager.RunningTaskInfo currentTask = tasks.get(0);
        ComponentName currentActivity = currentTask.topActivity;
        return new String[] { currentActivity.getPackageName() };
    }

    private String[] getLollipop() {
        final int PROCESS_STATE_TOP = 2;
        try {
            Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");

            List<ActivityManager.RunningAppProcessInfo> processes =
                activityManager().getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (
                    // Filters out most non-activity processes
                    process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    &&
                    // Filters out processes that are just being
                    // _used_ by the process with the activity
                    process.importanceReasonCode == 0
                ) {
                    int state = processStateField.getInt(process);

                    if (state == PROCESS_STATE_TOP)
                        /*
                         If multiple candidate processes can get here,
                         it's most likely that apps are being switched.
                         The first one provided by the OS seems to be
                         the one being switched to, so we stop here.
                         */
                        return process.pkgList; 
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return new String[] { };
    }

    private ActivityManager activityManager() {
        return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }
}

4. 新增 GET_TASKS 許可權到 AndroidManifest.xml:

相關推薦

Android 如何監控當前Foreground Activity如何獲知應用程式啟動

public class CurrentApplicationPackageRetriever { private final Context context; public CurrentApplicationPackageRetriever(Context context) {

Android深入四大元件(一)應用程式啟動過程

前言 在此前的文章中,我講過了Android系統啟動流程和Android應用程序啟動過程,這一篇順理成章來學習Android 7.0的應用程式的啟動過程。分析應用程式的啟動過程其實就是分析根Activity的啟動過程。 1.Launcher請求A

Android 建立新的Activity禁止返回到前一個(或pre的pre)Activity (FLAG_ACTIVITY_CLEAR_TASK的應用

應用場景:在APP登入介面(A)中開啟註冊介面(B),在註冊介面(B)提交使用者名稱、密碼等資訊提交後,直接進入主介面(C)。此時如果使用者按下了Back鍵,是不期望回到註冊介面(B)或者是登入介面(A)的。 簡單來說就是:activity A->B A

Android外掛化開發之AMS與應用程式(客戶端ActivityThread、Instrumentation、Activity)通訊模型分析

今天主要分析下ActivityManagerService(服務端) 與應用程式(客戶端)之間的通訊模型,在介紹這個通訊模型的基礎上,再    簡單介紹實現這個模型所需要資料型別。         本文所介紹內容基於android2.2版本。由於Android版本的不同

Android專案基本成型後更換應用包名(package)的方法

起因 這裡本人也是第一次更改,由於之前一個APK專案裡面分了好幾個專案,導致有些功能不能同時使用,所以需要將一個APK同時安裝兩個(不同的專案)在手機上,因為應用開發者的問題也就是包名不能重複,不能同

如何退出當前所有activity重新進入loginActivity介面

程式碼如下: Intent intent = new Intent(this, LoginActivity.class); ComponentName cn = intent.getComponen

Android四大元件之ActivityActivity生命週期

      Android四大基本元件分別是Activity,Service服務,Content Provider內容提供者,BroadcastReceiver廣播接收器。      Activity作為四大元件之一,其生命週期也就是它所在的程序的生命週期。Activity生

[Android] Android獲取當前頂部Activity名方法歷史版本彙總

在做一個顯示當前頂部activity名和包名的ToolApp時遇到的問題。在Android5.0之前,獲取top Activity方法非常簡單。直接使用getRunningTasks方法即可。 //getRunningTasks() is deprecated

Android查缺補漏--Activity生命周期和啟動模式

oncreate 交互 odin 生命周期方法 ont state cnblogs blog 開發 一、生命周期 onCreate():啟動Activity時,首次創建Activity時回調。 onRestart():再次啟動Activity時回調。 onStart():

Linux下應用程式新增桌面圖示(ubuntu18.4)

一、桌面圖示位置 Lniux下桌面圖示儲存路徑為:/usr/share/applications   二、桌面圖示格式 所有桌面圖示格式均為desktop,即名為XXX.desktop   三、編輯內容(常用) // 檔案頭(必須) [Desktop Entry] /

exe應用程式無法啟動因為應用程式的並行配置不正確

問題:exe應用程式無法啟動,因為應用程式的並行配置不正確。有關詳細資訊,請參閱應用程式事件日誌,或使用命令列 sxstrace.exe 工具。 原因查詢: 1)開始→所有程式→附件→右鍵命令提示符→以管理員身份執行 2)輸入sxstrace.exe Trace -logfile:C

Ionic在應用程式啟動前讀取應用程式啟動之前的配置檔案避免程式碼頻繁編譯

1.app.module.ts 2.app.config.ts 1.新建app.config.ts檔案 2.內容: import { Inject, Injectable } from '@angular/core'; import { Http } from '@angular/

Android進階(二): 應用程序啟動過程

1.前言 最近一直在看 《Android進階解密》 的一本書,這本書編寫邏輯、流程都非常好,而且很容易看懂,非常推薦大家去看看(沒有收廣告費,單純覺得作者寫的很好)。 今天就將 應用程序啟動過程 總結一下(基於Android 8.0 系統)。 文章中例項&nbs

應用程式無法啟動因為應用程式的並行配置不正確;解決辦法

可以先利用sxstrace跟蹤除錯應用程式執行時需要的動態庫的版本和路徑。 步驟: 1.利用管理員身份執行命令提示視窗 2.輸入sxstrace.exe Trace -logfile:C:\trace.log(路徑自定義),開始跟蹤 3.執行應用程式,回車,完成跟蹤生

Android應用程式啟動詳解(二)從原始碼瞭解App的啟動過程

本文承接《Android應用程式啟動詳解(一)》繼續來學習應用程式的啟動的那些事。上文提到startActivity()方法啟動一個app後經過一翻過程就到了app的入口方法ActivityThread.main()。其實我們在之前的文章中《Android的訊息機制(二)之L

使用Android Studio建立第一個Hello World應用程式

 前面的部落格跟大家介紹了:下面我們將使用Android Studio建立第第一個簡單的Hello World應用程式。1、開啟Android Studio,載入畫面如下圖所示:2、選擇”Start a

Kubernetes雲原生應用程式分散式應用程式編寫架構Metaparticle_Kubernetes中文社群

自動部署、擴充套件和管理Container應用程式的開源系統Kubernetes共同創辦人Brendan Burns於KubeCon上,發表分散式應用程式編寫架構Metaparticle,這是一套為雲原生應用程式而生的Kubernetes標準庫,目的是讓開發者使用自己熟悉的程式語言,就能開發分

微軟開源容器開發工具Draft加快應用程式在Kubernetes環境部署_Kubernetes中文社群

今年4月微軟併購Kubernetes工具開發商Deis後,微軟在近日也開源了容器應用程式開發工具Draft,加速應用程式在Kubernetes環境的部署流程。 目前帶領微軟Azure容器服務團隊的Kubernetes共同創辦人Brendan Burns表示,雖然Kubernetes在部署、管理

應用程式無法啟動因為應用程式的並行配置不正確

今天在使用註冊機啟用軟體時,提示如下資訊:   解決方案: 1.雙擊註冊機,跳出錯誤資訊; 2.右擊windows鍵 -- 事件檢視器 -- windows日誌 -- 應用程式 -- 雙擊第一個“錯誤” 從中可以看到事件資訊:x86 、9.0.21022.8 3.百度搜索:x86

Android中如何修改系統時間(應用程式獲得系統許可權)

在 Android 的API中有提供 SystemClock.setCurrentTimeMillis()函式來修改系統時間,可惜無論你怎麼呼叫這個函式都是沒用的,無論模擬器還是真機,在logcat中總會得到"Unable to open alarm driver: Permission denied "