创建BroadcastReceiver,在安装/卸载任何应用程序时显示应用程序名称和版本号。但我通过intent.getData()
获取包名。但是当我试图使用packagemanager找到该应用程序的名称时,它会在所有安装/卸载/替换的情况下抛出异常。可能存在的问题是什么?如何解决?
代码:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;
public class ApplicationStatusNotification extends BroadcastReceiver {
/**
* This method receives message for any application status(Install/ Uninstall) and display details.
*/
@Override
public void onReceive(Context context, Intent intent) {
// Get application status(Install/ Uninstall)
boolean applicationStatus = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
String toastMessage = null;
// Check if the application is install or uninstall and display the message accordingly
if(intent.getAction().equals("android.intent.action.PACKAGE_INSTALL")){
// Application Install
toastMessage = "PACKAGE_INSTALL: "+ intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);
}else if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")){
// Application Uninstall
toastMessage = "PACKAGE_REMOVED: "+ intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);
}else if(intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){
// Application Replaced
toastMessage = "PACKAGE_REPLACED: "+ intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);
}
//Display Toast Message
if(toastMessage != null){
Toast.makeText(context, toastMessage, Toast.LENGTH_LONG).show();
}
}
/**
* This method get application name name from application package name
*/
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;
}
}
答案 0 :(得分:11)
我遵循this示例,其中引入了BroadcastReceiver,如下所示;
<receiver android:name="PackageChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REPLACED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
现在一旦调用了PackageChangeReceiver.onReceive(..),Intent.getData()就会包含一些内容;由Uri.toString()返回的package:my.test.package
。要使用PackageManager搜索此ApplicationInfo,您应该只提取可以由Uri.getSchemeSpecificPart()
检索的包名称,该名称只能为您提供my.test.package
。
此外,基于快速测试,删除包后很可能不再有ApplicationInfo可用。