簡體   English   中英

如何獲取已安裝或已刪除應用程序的名稱?

[英]How to get name of installed or removed application?

我已經編寫了一個廣播接收器來檢測安裝和刪除應用程序。 但是我也想獲得已安裝或已刪除應用程序的名稱。 我怎樣才能做到這一點?

這是我的BroadcastReceiver:

public class PackageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        switch(intent.getAction())
        {
            case Intent.ACTION_PACKAGE_ADDED:
                String replaced = "";
                if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    replaced = "replaced";
                }
                Log.e("application", "installed " + replaced);

                break;

            case Intent.ACTION_PACKAGE_REMOVED:
                if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    Log.e("application", "removed");
                }

                break;
        }

    }
}

在清單中:

<receiver
    android:name=".receivers.PackageReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
         <action android:name="android.intent.action.PACKAGE_ADDED" />
         <action android:name="android.intent.action.PACKAGE_REMOVED" />
         <data android:scheme="package" />
    </intent-filter>
</receiver>

結合在android文檔中找到的信息和堆棧溢出的答案 ,我想到了以下內容。 您使用的Intent可能還有EXTRA_UID個,其中包含修改后的應用程序的uid。 使用uid可以獲取應用程序名稱。 但是,您只能在ACTION_PACKAGE_ADDED意圖上執行此操作,因為在ACTION_PACKAGE_REMOVED應用中,該應用已被刪除,您無法獲取其名稱(仍然可以獲取uid)。

檢查此樣本:

int uid = intent.getIntegerExtra(Intent.EXTRA_UID);
String appName = context.getPackageManager().getNameForUid(uid);

因此,在您的情況下,它將是:

public class PackageReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch(intent.getAction())
        {
            case Intent.ACTION_PACKAGE_ADDED:
                String replaced = "";
                String appName = "";
                int uid = -1;
                if(intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    replaced = "replaced";
                }
                uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
                if(uid != -1){
                    appName = context.getPackageManager().getNameForUid(uid);
                }
                Log.e("application", "installed " + replaced + " uid " + uid + " appname " + appName);

                break;

            case Intent.ACTION_PACKAGE_REMOVED:
                if(!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))
                {
                    Log.e("application", "removed");
                }
                break;
        }
    }
}

通過以下代碼,我已經看到從Google Play安裝Google Earth后用logcat編寫的代碼:

已安裝uid 10404 appname com.google.earth

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM