欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现亮屏后弹出一个Activity

程序员文章站 2022-06-17 22:42:49
首先我们需要设置权限然后动态注册广播: IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerRe...

首先我们需要设置权限

<uses-permission android:name="android.permission.WAKE_LOCK" />

然后动态注册广播:

 IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(new AlarmClockReceiver(), filter);

广播接受接处理(AlarmClockReceiver)

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 ");

      }
    }
}

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

 <service
            android:name=".RemindService"
            android:enabled="true"
            android:exported="true" />
        <receiver
            android:name=".AlarmClockReceiver"
            android:enabled="true"
            android:exported="true"
          />

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

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://blog.csdn.net/weixin_44710164/article/details/107945936