2012-05-14 262 views
2

我無法獲取允許用戶授予應用程序權限以便設備管理員工作的活動。Android:設備管理員:啓動設備管理員服務

我的代碼如下...

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

稍遲,但...您需要使用startActivityForResult()作爲nitinreddy建議,但您不能從服務做到這一點。要從服務中這樣做,最好的辦法是啓動一個透明的活動,從該活動請求管理權限,然後完成()該活動。 –

+0

http://stackoverflow.com/a/17297711/581159這可能會幫助你... – Zeba

回答

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() 
+0

嗨,首先非常感謝您的答覆。什麼是「getPolicyAdmin」的成員?我似乎無法找到它是DevicePolicyManager的一種方法? –

+1

不,是CustomReceiver引用deviceadmin類的組件嗎? – nithinreddy

+0

意思是擴展DeviceAdminReceiver的那個?你介意與我分享那麼一點代碼嗎?只需編輯上述答案即可。 –

0

這裏是如何做到這一點的一個明顯例子,(官方文檔herehere錯過一些上下文)

//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); 

Here is the reference class used in the official sample app.