0

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

4

2 回答 2

0

每次单击锁定按钮时都会调用 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);

        }
    }
于 2019-10-18T06:14:27.093 回答
0

使用通知在后台运行服务,并且内部服务检测屏幕是否锁定。//createAndShowForegroundNotification 将创建一个不可取消的通知。然后注册意图过滤器,不要忘记在 //destroyed 时取消注册

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    createAndShowForegroundNotification(BackgroundSyncService.this, 9797);
    final IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    mScreenReceiver = new ScreenReceiver();
    this.registerReceiver(mScreenReceiver, filter);
    return START_STICKY;
}

//这是在服务内部屏幕灯关闭时将调用的接收器

公共类 ScreenReceiver 扩展 BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here

        } else{

              }
    }

}
于 2019-10-18T07:18:05.193 回答