在启动时启动您的应用
实现此目的的最佳方法是将您的应用设置为启动器
<activity ...
android:launchMode="singleInstance"
android:windowActionBar="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
锁定您的应用
最可靠的方法是使用带有 Lollipop 或更高版本的设备并利用
startLockTask
首先您必须将您的应用设置为设备所有者。请注意,您的设备必须未配置:如果您已注册,则应恢复出厂设置并跳过帐户注册。
为了能够注册您的应用,您必须首先设置一个 DeviceAdminReceiver 组件:
package com.example.myapp;
public class MyDeviceAdminReceiver extends android.app.admin.DeviceAdminReceiver {
@Override
public void onEnabled(Context context, Intent intent) {
Toast.makeText(context, "Device admin permission received", Toast.LENGTH_SHORT).show();
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "are you sure?";
}
@Override
public void onDisabled(Context context, Intent intent) {
Toast.makeText(context, "Device admin permission revoked", Toast.LENGTH_SHORT).show();
}
@Override
public void onLockTaskModeExiting(Context context, Intent intent) {
// here you must re-lock your app. make your activity know of this event and make it call startLockTask again!
}
}
一旦您拥有未配置的设备,您就可以从 adb 启动以下命令(无需 root )
adb shell dpm set-device-owner com.example.myapp/.MyDeviceAdminReceiver
为避免 android 要求用户权限来固定您的应用,您必须调用
setLockTaskPackages
终于!
@Override
public void onResume(){
super.onResume();
DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) getSystemService(
Context.DEVICE_POLICY_SERVICE);
ComponentName mAdminComponentName = new ComponentName(getApplicationContext(), MyDeviceAdminReceiver.class);
mDevicePolicyManager.setLockTaskPackages(mAdminComponentName, new String[]{getPackageName()});
startLockTask();
}
@Override
public void finish(){
stopLockTask();
super.finish();
}