startForegroundService 闪退问题

1 NotificationCompat

//通知显示
PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("SMS")
        .setPriority(Notification.PRIORITY_MIN)
        .setContentIntent(contentIntent)
        .setContentTitle("我怕谁!")
        .setAutoCancel(true)
        .setContentText("SMSContext")
        .setWhen(System.currentTimeMillis());

//把service设置为前台运行,避免手机系统自动杀掉改服务。
startForeground(startId, builder.build());



或者
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setChannelId(CHANNEL_ONE_ID);
builder.setContentTitle("SMS");
builder.setContentText("SMSListener is runing...");
startForeground(NOTICE_ID,builder.build());



复制代码

2 再次启动Service

//兼容版本服务
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    //8.0上启动前台服务
    startForegroundService(new Intent(this, ChannlService.class));
    tv_runstatus.postDelayed(new Runnable() {
        @Override
        public void run() {
            startService(new Intent(MainActivity.this, ChannlService.class));
        }
    }, 500);

} else {
    startService(new Intent(this, ChannlService.class));
}复制代码

避免了用户看到通知栏,也是前台服务 onstartCommon会调用两次,本身处理下逻辑判断便可bash

相关文章
相关标签/搜索