android8.0以上启动后台服务时会报错,因为8.0以后的版本Google为了避免服务在用户不知情的情况之下做一下偷偷摸摸的事,所以启动规则做了限制,广播也是。
启动服务可以参考以下文章:服务启动
详细一点的可以参考这篇文章;8.0服务启动
下面我做了个demo,实现后台定时发送一个广播,然后在广播中启动服务,
服务:
public class Myservice extends Service {
int anHour = 5*1000;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Notification notification = new Notification.Builder(this).build();
// startForeground(0, notification);
createNotificationChannel();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Myservice --- > 99999988");//这是定时所执行的任务
Log.e("TAG--->","service");
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
long triggerAtTime = SystemClock.currentThreadTimeMillis() + anHour;
Intent intent2 = new Intent();
intent2.setAction("com.example.action.MyReceiver");
intent2.setPackage(getPackageName());
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
private void createNotificationChannel() {
// 通知渠道的id
String CHANNEL_ID = "my_channel_01";
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(this)
.setContentTitle("New Message") .setContentText("You've received new messages.")
// .setSmallIcon(R.drawable.ic_launcher_foreground)
.setChannelId(CHANNEL_ID)
.build();
startForeground(1,notification);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
广播:
public class MyBroadcast extends BroadcastReceiver {
String TAG = MyBroadcast.class.getName()+"--->";
@Override
public void onReceive(Context context, Intent intent) {
Log.e("TAG--",intent.getAction());
Intent i = new Intent(context, Myservice.class);
ContextCompat.startForegroundService(context,i);
Toast.makeText(context,
"接收到的Intent的Action为:" + intent.getAction() + "\n 消息内容是:" + intent.getStringExtra("msg"),
Toast.LENGTH_LONG).show();
}
}
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ganggang.macbook.testmie">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcast" >
<intent-filter >
<action android:name="com.example.action.MyReceiver"/>
</intent-filter>
</receiver>
<service android:name=".Myservice"></service>
</application>
</manifest>
Main:
public class MainActivity extends Activity {
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取程序界面中的按钮
// views();
Intent i = new Intent(this, Myservice.class);
ContextCompat.startForegroundService(this,i);
}
private void views(){
send = (Button)findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//创建Intent
Intent intent = new Intent();
intent.setAction("com.example.action.MyReceiver");
intent.setPackage(getPackageName());
intent.putExtra("msg", "简单的消息");
//发送广播
sendBroadcast(intent);
}
});
}
}