我认为有另一种解决方案,无需 root 设备。我的老板要求我避免生根,所以经过一些研究,我找到了这个解决方法。
结果,没有进行任何黑客攻击,系统密钥仍然存在,但用户无法离开应用程序并启动另一个应用程序。所以,我做了以下步骤。
1。
通过编辑清单,为适当的Activity 设置不带TitleBar 和ActionBar 的全屏主题,如下所示:
<application
...
android:theme="android:Theme.Holo.NoActionBar.Fullscreen" >
2。
通过覆盖Activity类的方法禁用后退按钮:
@Override
public void onBackPressed() {
return;
}
3。
将以下字符串添加到清单(适当的Activity 的意图过滤器):
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
现在您可以用您的应用程序替换默认主屏幕。但是仍然可以通过单击“最近使用的应用”按钮并选择另一个来退出应用。
4。
为了避免离开应用程序的所有其他方式,我添加了一个服务,该服务在每次活动暂停时启动。此服务重新启动应用程序并发送有关它的通知。
服务代码:
public class RelaunchService extends Service {
private Notification mNotification;
private Timer mTimer;
public RelaunchService() {
}
@Override
public void onCreate(){
super.onCreate();
if (mNotification == null) {
Context context = getApplicationContext();
Intent notificationIntent = new Intent(this, FullscreenActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification.Builder mBuilder = new Notification.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setContentTitle("Your app title")
.setContentText("App is being relaunched");
mNotification = mBuilder.getNotification();
mTimer = new Timer("LaunchTimer");
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(1, mNotification);
mTimer.schedule(new TimerTask() {
@Override
public void run() {
Intent intent = new Intent(RelaunchService.this, YourActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}, 300);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
mTimer.cancel();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
添加到 Activity 类的代码:
@Override
protected void onResume() {
super.onResume();
exitAllowed = false;
Intent servIntent = new Intent(this, RelaunchService.class);
stopService(servIntent);
}
@Override
protected void onPause() {
super.onPause();
savePersistentData();
if (!exitAllowed) {
Intent servIntent = new Intent(this, RelaunchService.class);
startService(servIntent);
}
}
当您想要关闭应用程序时,应将 exitAllowed 布尔变量分配给 true。您可以考虑一些方法来做到这一点,例如通过单击“退出”按钮。在我的情况下,退出需要密码。