我正在尝试从用户激活设备管理员那里获得响应。如果用户按下激活然后做某事,或者如果用户按下取消,则会弹出一个对话框通知用户应该激活。
我尝试使用
在类DeviceAdmin
public class DeviceAdmin {
public static final int DEVICE_ADMIN_REQUEST = 9;
public static final int START_SERVICE = 8;
private static DevicePolicyManager mDevicePolicyManager;
private static ComponentName mComponentName;
public static DevicePolicyManager getDevicePolicyManager() {
return mDevicePolicyManager;
}
public static void setDevicePolicyManager(
final DevicePolicyManager devicePolicyManager) {
mDevicePolicyManager = devicePolicyManager;
}
public static ComponentName getComponentName() {
return mComponentName;
}
public static void setComponentName(final ComponentName componentName) {
mComponentName = componentName;
}
public static void initDPM(final Activity activity) {
if (mDevicePolicyManager == null) {
setDevicePolicyManager((DevicePolicyManager) activity
.getSystemService(Context.DEVICE_POLICY_SERVICE));
}
}
public static <T> void initComponent(final Activity activity,
final Class<T> reciever) {
if (mComponentName == null) {
setComponentName(new ComponentName(activity, reciever));
}
}
public static boolean isDeviceAdmin() {
return mDevicePolicyManager.isAdminActive(mComponentName);
}
public static void registerDeviceAdmin(final Activity activity,
final int requestCode) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
getComponentName());
activity.startActivityForResult(intent, requestCode);
}
public static void unregisterDeviceAdmin() {
if (mDevicePolicyManager.isAdminActive(mComponentName))
mDevicePolicyManager.removeActiveAdmin(mComponentName);
}
}
在MainActivity
public class LockIt extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
if (!DeviceAdmin.isDeviceAdmin())
DeviceAdmin.registerDeviceAdmin(this,
DeviceAdmin.DEVICE_ADMIN_REQUEST);
else
// Do something;
}
private void init() {
DeviceAdmin.initDPM(this);
DeviceAdmin.initComponent(this, LockItNowAdminReceiver.class);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DeviceAdmin.DEVICE_ADMIN_REQUEST) {
if (resultCode == RESULT_OK) {
// do something;
} else if (resultCode == RESULT_CANCELED) {
// showAdminDialog;
}
}
}
}
RESULT_OK为 -1,RESULT_CANCELED为 0
但是当我在调试模式下运行时,我发现无论用户按取消还是激活,resultCode 始终为 0。
更新
好的,我想我找到了原因。我android:launchMode="singleInstance"
在MainActivity 清单中使用过
这是获得设备管理员激活响应的正确方法吗?还是我做错了什么?