Android,当应用启用设备管理员时更改 GPS 状态

Android, Change GPS status when app is device administrator enabled

当应用程序被用户设置为 Device administrator 时如何设置 GPS 状态。

我正在使用这个方法:

private void turnGPSOn() {
    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    getApplicationContext().sendBroadcast(intent);

    String provider = Settings.Secure.getString(getApplicationContext()
            .getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (!provider.contains("gps")) { // if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        this.getApplicationContext().sendBroadcast(poke);

    }
}

并且至少在 API-21:

出现此错误
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=27737, uid=10464

请注意已启用的Device administrator权限,不要将问题标记为重复

android.location.GPS_ENABLED_CHANGE intent 只能由系统应用程序广播,因为它是受保护的广播(意味着您的应用程序应该使用 systemsignature 进行签名,或者它应该是系统应用程序)。即使您的应用被用户选择为设备管理应用,也不意味着它有资格使用系统功能。设备管理应用程序将可以访问 DevicePolicyManager class 公开的功能。在 Lollipop 及更高版本上,可以使用 DevicePolicyManger class 来控制一些全局设置和安全设置。

Control Secure Settings

Control Global Settings