Android实现亮屏后弹出一个Activity

2022-02-09 16:11:45 浏览数 (2)

首先我们需要设置权限

代码语言:javascript复制
<uses-permission android:name="android.permission.WAKE_LOCK" />

然后动态注册广播:

代码语言:javascript复制
 IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(new AlarmClockReceiver(), filter);

广播接受接处理(AlarmClockReceiver)

代码语言:javascript复制
public class AlarmClockReceiver extends BroadcastReceiver {

    private String TAG="hyc";

    @Override
    public void onReceive(Context context, Intent intent) {
      if (Intent.ACTION_SCREEN_ON==intent.getAction()){//亮屏
         Intent startPhone = new Intent(context, PhotoActivity.class);
          startPhone.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(startPhone);
          Log.d(TAG, "onReceive:on ");
      }else if (Intent.ACTION_SCREEN_OFF==intent.getAction()){//灭屏
          Log.d(TAG, "onReceive:off ");

      }
    }
}

广播与服务的清单文件如下:

代码语言:javascript复制
 <service
            android:name=".RemindService"
            android:enabled="true"
            android:exported="true" />
        <receiver
            android:name=".AlarmClockReceiver"
            android:enabled="true"
            android:exported="true"
          />

我们需要展示的Activity需要进行的操作

代码语言:javascript复制
public class PhotoActivity extends AppCompatActivity {

    @SuppressLint("InvalidWakeLockTag")
    private PowerManager.WakeLock wl;

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true);
        }else{
            //页面悬浮于锁屏之上
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

            //亮屏
            KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unlock");
            kl.disableKeyguard();

            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "bright");
            wl.acquire();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wl!=null){
            wl.release();
        }

    }
}

我的博客即将同步至腾讯云 社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3t68h9hdbicks

0 人点赞