解決context.startforegroundservice() did not then call service.startforeground()
原因:
- Android 8.0 系統不允許背景應用建立背景服務,故隻能使用
啟動服務Context.startForegroundService()
- 建立服務後,應用必須在5秒内調用該服務的
顯示一條可見通知,聲明有服務在挂着,不然系統會停止服務 + ANR 套餐送上。startForeground()
- Notification 要加 Channel,系統的要求。
解決步驟:
Service.java 中
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
startFG();
}
}
private void startFG() {
NotificationBuilder builder = new NotificationBuilder(this);
final Notification notification = builder.buildNotification();
startForeground(NotificationBuilder.NOTIFICATION_ID, notification);
}
NotificationBuilder.java
public final class NotificationBuilder {
public static final String NOTIFICATION_CHANNEL_ID = "com.demo.CHANNEL_ID";
public static final int NOTIFICATION_ID = 0xD660;
private final Context mContext;
private final NotificationManager mNotificationManager;
public NotificationBuilder(Context context) {
mContext = context;
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public Notification buildNotification() {
if (shouldCreateNowPlayingChannel()) {
createNowPlayingChannel();
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);
return builder.setSmallIcon(R.drawable.all_app_takeaway_icon)
.setContentTitle("")
.setContentTitle("")
.setOnlyAlertOnce(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private boolean nowPlayingChannelExists() {
return mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) != null;
}
private boolean shouldCreateNowPlayingChannel() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNowPlayingChannel() {
final NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"目前播放",
NotificationManager.IMPORTANCE_LOW);
channel.setDescription("目前播放的電台");
mNotificationManager.createNotificationChannel(channel);
}
}
還要注意:
AndroidManifest.xml 中配置permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
啟動Service方法:
//背景啟動service
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
Intent serviceIntent = new Intent(this, DemoService.class);
startForegroundService(serviceIntent);
} else {
Intent serviceIntent = new Intent(this, DemoService.class);
startService(serviceIntent);
}