对于解锁和锁屏这种用的比较频繁action,谷歌做了限制,必须手动用代码注册
直接上代码:这是注册广播(手动代码注册广播接收者)
1 public class MainActivity extends AppCompatActivity { 2 Screen screen; 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 screen = new Screen(); 9 IntentFilter filter = new IntentFilter(); 10 //添加action 11 filter.addAction("android.intent.action.SCREEN_OFF"); 12 filter.addAction("android.intent.action.SCREEN_ON"); 13 //注册广播接收者 14 this.registerReceiver(screen,filter); 15 } 16 17 @Override 18 protected void onDestroy() { 19 super.onDestroy(); 20 unregisterReceiver(screen); 21 }
1 public class Screen extends BroadcastReceiver { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 String action = intent.getAction(); 5 if (action.equals("android.intent.action.SCREEN_OFF")){ 6 System.out.println("屏幕锁屏了"); 7 }else if (action.equals("android.intent.action.SCREEN_ON")){ 8 System.out.println("屏幕解锁了"); 9 } 10 } 11 }
下面是开机自启:
老套路,新建一个类继承于BroadcastReceiver,然后配置清单文件
1 <receiver android:name="com.itheima.bootreceiver.BootReceiver"> 2 <intent-filter > 3 <action android:name="android.intent.action.BOOT_COMPLETED"/> 4 </intent-filter> 5 </receiver>
然后就是onReceiver方法:
1 public class BootReceiver extends BroadcastReceiver { 2 3 //当手机重启会执行这个方法 4 @Override 5 public void onReceive(Context context, Intent intent) { 6 7 //开启mainActivity 8 Intent intent2 = new Intent(context,MainActivity.class); 9 //☆ 如果在广播里面开启Activity 要设置一个任务栈环境 10 intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 11 //在广播接收者里面开启activity 12 context.startActivity(intent2); 13 14 } 15 16 }
注意:
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);一定要加上一个