and*_*per 18 android android-manifest android-package-managers android-activity
我正在尝试检查是否在运行时启用/禁用了活动(或任何其他应用程序组件类型).
可以使用下一个代码:
final ComponentName componentName = new ComponentName(context, activityClass);
final PackageManager pm = context.getPackageManager();
final int result = pm.getComponentEnabledSetting(componentName);
Run Code Online (Sandbox Code Playgroud)
但是返回的结果,如文档中所写:
返回组件的当前启用状态.可以是COMPONENT_ENABLED_STATE_ENABLED,COMPONENT_ENABLED_STATE_DISABLED或COMPONENT_ENABLED_STATE_DEFAULT之一.最后一个意味着组件的启用状态基于清单中的原始信息,如ComponentInfo中所示.
所以它不仅是启用/禁用,还是"默认".
如果返回"COMPONENT_ENABLED_STATE_DEFAULT",我如何知道它是默认为启用还是禁用(在运行时)?
这个问题的原因是无论人们放入清单中的内容("启用"属性),代码都应该有效.
是否有可能使用意图解决?
Jar*_*ler 10
如果
COMPONENT_ENABLED_STATE_DEFAULT返回,我怎么知道默认为启用还是禁用?
您需要使用PackageManager加载所有组件,并检查匹配的ComponentInfo的启用状态.以下代码应该有效:
public static boolean isComponentEnabled(PackageManager pm, String pkgName, String clsName) {
ComponentName componentName = new ComponentName(pkgName, clsName);
int componentEnabledSetting = pm.getComponentEnabledSetting(componentName);
switch (componentEnabledSetting) {
case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
return false;
case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
return true;
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
default:
// We need to get the application info to get the component's default state
try {
PackageInfo packageInfo = pm.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES
| PackageManager.GET_RECEIVERS
| PackageManager.GET_SERVICES
| PackageManager.GET_PROVIDERS
| PackageManager.GET_DISABLED_COMPONENTS);
List<ComponentInfo> components = new ArrayList<>();
if (packageInfo.activities != null) Collections.addAll(components, packageInfo.activities);
if (packageInfo.services != null) Collections.addAll(components, packageInfo.services);
if (packageInfo.providers != null) Collections.addAll(components, packageInfo.providers);
for (ComponentInfo componentInfo : components) {
if (componentInfo.name.equals(clsName)) {
return componentInfo.isEnabled();
}
}
// the component is not declared in the AndroidManifest
return false;
} catch (PackageManager.NameNotFoundException e) {
// the package isn't installed on the device
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的设备上测试上面的代码:
System.out.println(isComponentEnabled(getPackageManager(),
"com.android.systemui",
"com.android.systemui.DessertCaseDream"));
System.out.println(isComponentEnabled(getPackageManager(),
"com.android.settings",
"com.android.settings.DevelopmentSettings"));
Run Code Online (Sandbox Code Playgroud)
假
真正
| 归档时间: |
|
| 查看次数: |
3029 次 |
| 最近记录: |