从oreo开始,android后台政策发生了重大变化,请参考这里https://developer.android.com/about/versions/oreo/background更多细节,
为了避免您的服务被 Android 杀死,您必须将其作为前台服务运行
步骤一:给manifest文件添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
这是有关此权限的更多详细信息https://developer.android.com/reference/android/Manifest.permission#FOREGROUND_SERVICE
第 2 步:创建服务,我正在为您分享示例代码
public class DemoService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SSB Log", "onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// For foreground service
Intent notificationIntent = new Intent(this, DemoService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
// Creating channel for notification
String id = DemoService.class.getSimpleName();
String name = DemoService.class.getSimpleName();
NotificationChannel notificationChannel = new NotificationChannel(id,
name, NotificationManager.IMPORTANCE_NONE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(notificationChannel);
// Foreground notification
Notification notification = new Notification.Builder(this, id)
.setContentTitle(getText(R.string.app_name))
.setContentText("Show service running reason to user")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker("Ticker text")
.build();
startForeground(9, notification);
}
// Service logic here
return Service.START_NOT_STICKY;
}
}
步骤 3:在清单中声明服务
<service android:name=".DemoService" />
第 4 步:从 Activity 启动服务
Intent startDemoService = new Intent(this,DemoService.class);
startService(startDemoService);