首页 > 解决方案 > 如果屏幕被锁定,我应该如何重新启动我的 android 应用程序?

问题描述

每次用户按下我的应用程序上的锁定按钮时,我都想重新启动我的 Android 应用程序,即使我已经从我的应用程序启动了图库/相机;这样即使启动的画廊/相机也会从我的应用程序任务中清除。请提出一个相同的方法。

标签: androidtask

解决方案


每次单击锁定按钮时都会调用 onStop() 。因此,每次触发 onStop() 时重写该方法以检查屏幕是否处于唤醒状态,然后调用您的第一个 Activity。

@Override
    protected void onStop() {
        super.onStop();

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

        if(!pm.isScreenOn()){

            Intent mStartActivity = new Intent(YOUR_CURRENT_ACTIVITY.this, YOUR_FIRST_ACTIVITY.class);
            PendingIntent mPendingIntent = PendingIntent.getActivity(YOUR_CURRENT_ACTIVITY.this, 123456,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
            System.exit(0);

        }
    }

推荐阅读