本文转载自:https://blog.csdn.net/nowtodays/article/details/82430171
安卓8.0开始对推送系列做了更严格的规定
在发送推送时需要对api版本进行判断
这里先简单贴一下新版的适配方式,详细的教程可以参考大神文档:
Android通知栏微技巧,8.0系统中通知栏的适配 -郭霖
用如下方式启动一个前台服务:
//Service代码
private final String CHANNEL_ID = "TEST_SERVICE_ID";
private final String CHANNEL_NAME = "渠道一";
private final String contentSub = "小标题";
private final String contentTitle = "标题";
private final String contentText = "测试前台服务";
Notification notification;
Notification.Builder builder;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
chan.enableLights(true);
chan.setLightColor(Color.RED);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
builder = new Notification.Builder(this, CHANNEL_ID);
notification = builder
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(contentText)
.setSubText(contentSub)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(contentTitle)
.build();
} else {
Intent i = new Intent();
PendingIntent p = PendingIntent.getActivity(this, 1, i, 0);
notification = new Notification.Builder(getApplicationContext())
.setContentInfo(contentSub)
.setSubText(contentSub)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(p)
.build();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, notification);
return START_STICKY;
}
开启服务
//启动前台Service
Intent i = new Intent(this, TestService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(i);
} else {
startService(i);
}