有没有办法在运行时检查清单中声明了哪些BroadcastReceivers?
答案 0 :(得分:3)
使用PackageManager
,您可以queryBroadcastReceivers()
查找谁将全部回复特定Intent
,并使用getInstalledPackages()
,您可以找到每个包安装的接收器。
答案 1 :(得分:3)
代码与此类似,来自Activity:
// Query all packages that have the BroadcastReceivers...
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager pm = getPackageManager();
final List<ResolveInfo> listPkgs = pm.queryBroadcast(mainIntent, 0);
if (listPkgs != null && listPkgs.size() > 0){
for(ResolveInfo resInfo : listPkgs){
// Now resInfo will contain the list of packages that has receivers...
}
}
答案 2 :(得分:1)
谢谢,但不是我的意图......我想知道是否在运行时在正在运行的应用程序中声明了一个特定的接收器,并实现了这样:
private <Receiver extends CyborgReceiver<?>> boolean checkIfBroadcastReceiverIsRegisteredInManifest(Class<Receiver> receiverType) {
PackageManager pm = application.getPackageManager();
try {
ActivityInfo info = pm.getReceiverInfo(new ComponentName(application, receiverType), PackageManager.GET_RECEIVERS);
return info.enabled;
} catch (NameNotFoundException e) {
return false;
}
}
答案 3 :(得分:0)
传入应用程序对象作为第一个参数,如果必须,可以使用(Application)context.GetApplicationContext()
执行此操作,然后传入实现广播接收器类的类作为第二个参数,例如broadcastReceiver.class
public static boolean validateReceiverInManifest(Application application, Class receiverClass) throws PackageManager.NameNotFoundException {
PackageManager pm = application.getPackageManager();
String packageName = application.getPackageName();
PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_RECEIVERS);
ActivityInfo[] receivers = packageInfo.receivers;
String receiverClassName = receiverClass.getName();
for (ActivityInfo activityInfo : receivers) {
if (activityInfo.name.equals(receiverClassName)) {
return true;
}
}
return false;
}