參考網址:https://blog.csdn.net/yt_42370304/article/details/105842170
https://blog.csdn.net/sinat_20059415/article/details/80584487
https://blog.csdn.net/luo_boke/article/details/102696097
Android8.0後不再允許背景service直接通過startService方式去啟動
啟動方式
Intent intent = new Intent(this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
MyService
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
//建立NotificationChannel
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(NOTIFICATION_ID,
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
//Android9.0會報Caused by: java.lang.SecurityException: Permission Denial:
//android.permission.FOREGROUND_SERVICE---AndroidManifest.xml中需要申請此權限
startForeground(1,getNotification());
}
//這個必須加,不能設定為null
private Notification getNotification() {
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("測試服務")
.setContentText("我正在運作");//标題和内容可以不加
//設定Notification的ChannelID,否則不能正常顯示
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(NOTIFICATION_ID);
}
Notification notification = builder.build();
return notification;
}
}
說明:
測試發現Android8.0後如果用startService啟動服務,應用退到背景後此服務一會兒就會被殺掉;如果用startForegroundService啟動服務,并且添加了消息通知後,應用背景挂起則不會被系統殺掉