在Android 9之后,当手机进入待机模式时,带通知的前台服务可能会被系统停止。为了解决这个问题,可以采用以下代码示例中的方法:
public class MyForegroundService extends Service {
private static final String CHANNEL_ID = "ForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Notification notification = createNotification(input);
startForeground(1, notification);
// 执行你的任务逻辑
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
private Notification createNotification(String input) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent);
return builder.build();
}
}
Intent serviceIntent = new Intent(this, MyForegroundService.class);
serviceIntent.putExtra("inputExtra", "Foreground Service Example");
ContextCompat.startForegroundService(this, serviceIntent);
通过使用上述代码示例中的方法,你可以确保即使在Android 9及更高版本中,带通知的前台服务也能在手机进入待机模式后继续运行。