学习Android APP开发时,看菜鸟教程里面有关发送广播和启动服务的代码
Intent it1 = new Intent("com.test.intentservice");
startService(it1);
发送广播(AndroidManifest中静态注册Receiver)
sendBroadcast(new Intent("com.example.broadcasttest.MY_BROADCAST"));
自己照写后运行,发现没有任何效果,但是没有报错。经过调查,发现菜鸟教程的作者用的应该是以前的版本,而我使用的是Android 8.0
作者使用的是隐式intent(隐式广播),并在AndroidManifest中静态注册
而针对 Android O 的应用无法继续在其Manifest清单中为应用自己的隐式广播注册广播接收器
所以要用显式intent(或者动态注册隐式广播接收器)
Intent(Context, Class)
像这样
//必须显式调用Intent,Android8.0后禁用隐式Broadcast应用无法为自己的隐式广播注册静态接收器 Intent intent = new Intent(new Intent(MainActivity.this,MyBroadcastReceiver.class)); intent.setAction("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent);
Intent it1 = new Intent(this,TestService.class);
然后再用setAction()方法设置操作就行了