[英]Android get broadcast about the application installed or removed
我想開發一個應用程序,可以接收有關正在安裝或刪除的其他應用程序的廣播。 到目前為止,我嘗試了下面的代碼,但是,它僅在刪除安裝時提供廣播事件,它不提供有關安裝或刪除的其他應用程序beibg的信息。 那么,有沒有辦法獲取新安裝的應用程序的包名稱。
在表現:
receiver android:name=".apps.AppListener">
<intent-filter android:priority="100">
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
在AppListener中:
public class AppListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// there is a broadcast event here
// but how to get the package name of the newly installed application
Log.v(TAG, "there is a broadcast");
}
}
增加:對於Api 14或更高版本,不推薦使用此功能。
<action android:name="android.intent.action.PACKAGE_INSTALL"/>
包名稱嵌入到您在onReceive()方法中接收的Intent中。 您可以使用下面的代碼段閱讀它:
Uri data = broadcastIntent.getData();
String installedPackageName = data.getEncodedSchemeSpecificPart();
對於PACKAGE_ADDED,PACKAGE_REMOVED和PACKAGE_REPLACED,您可以使用上面的代碼獲取包名稱。
如果應用程序更新,您將獲得2個背靠背廣播,如下所示:1。PACKAGE_REMOVED 2. PACKAGE_REPLACED
在應用程序更新的情況下,PACKAGE_REMOVED意圖將包含額外的布爾值,以區分應用程序刪除和應用程序更新。 您可以讀取此布爾值,如下所示:
boolean isReplacing = broadcastIntent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
只是為了得到包名稱,你正在調用PackageManagerService api是開銷。 必須避免它。
希望這個能對您有所幫助。
有兩種選擇:
1)如果您在詢問是否可以在卸載相同的應用程序時收到廣播,則答案是:
除非您是System應用程序,否則無法執行此操作。
Android將在安裝時通知應用程序。 這將是一個安全風險,因為它將使應用程序能夠防止卸載。
2)如果您詢問何時卸載其他應用程序,則可能與以下內容重復:
您在onReceive函數中獲得的意圖包含與要添加或刪除的包相關的信息。
intent.getData().toString()
您可以通過此函數獲取應用程序名稱:
private String getApplicationName(Context context, String data, int flag) {
final PackageManager pckManager = context.getPackageManager();
ApplicationInfo applicationInformation;
try {
applicationInformation = pckManager.getApplicationInfo(data, flag);
} catch (PackageManager.NameNotFoundException e) {
applicationInformation = null;
}
final String applicationName = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)");
return applicationName;
}
有關詳細信息,請查看: 創建的BroadcastReceiver,在安裝/卸載任何應用程序時顯示應用程序名稱和版本號?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.