安卓:设备管理器:从服务启动设备管理器

4

我无法获得允许用户授予应用程序设备管理员权限的活动。

我的代码如下...

ComponentName comp = new ComponentName(this, CustomReceiver.class);

Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, comp);
i.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Explanation");

startActivity(i);

应用程序没有崩溃或报告异常。我可能做错了什么?

2
有点晚了,但是...你需要像nitinreddy建议的那样使用startActivityForResult(),但是你不能从服务中这样做。要从服务中这样做,最好的方法是启动一个透明的活动,在该活动中请求管理员权限,然后finish()该活动。 - Jasjit Singh Marwah
这个链接可能会对你有所帮助:https://dev59.com/hl7Va4cB1Zd3GeqPM8nU#17297711 - Zeba
2个回答

1

这里有一个明确的示例,(官方文档此处此处缺少一些上下文)

//class that implements DeviceAdminReceiver, defined in the Manifest 
ComponentName deviceAdminCN = new ComponentName(context, DeviceAdminReceiverImpl.class) 

...

Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdminCN);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "your explanation for the user here");
startActivityForResult(intent, YOUR_REQUEST_CODE);

这是官方示例应用程序中使用的参考类。


1

类似这样的东西就可以了

if (!mPolicy.isAdminActive()) {

    Intent activateDeviceAdminIntent =
        new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

    activateDeviceAdminIntent.putExtra(
        DevicePolicyManager.EXTRA_DEVICE_ADMIN,
        mPolicy.getPolicyAdmin());

    // It is good practice to include the optional explanation text to
    // explain to user why the application is requesting to be a device
    // administrator. The system will display this message on the activation
    // screen.
    activateDeviceAdminIntent.putExtra(
        DevicePolicyManager.EXTRA_ADD_EXPLANATION,
        getResources().getString(R.string.device_admin_activation_message));

    startActivityForResult(activateDeviceAdminIntent,
        REQ_ACTIVATE_DEVICE_ADMIN);
}

也许你还没有考虑到

mPolicy.getPolicyAdmin()

首先非常感谢您的回复。 "getPolicyAdmin" 是属于哪个类的成员?我似乎找不到它是 DevicePolicyManager 的一个方法? - Heshan Perera
1
不是,CustomReceiver是引用deviceadmin类的组件吗? - nithinreddy
你能分享一下继承DeviceAdminReceiver的那部分代码吗?只需要编辑上面的答案即可。 - Heshan Perera
好的,我会查看我手头上的示例,但如果您没有查看链接的话,您应该也能从这里找到答案。http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/DeviceAdminSample.html - nithinreddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接