要保持一个Android服务长时间运行,可以使用以下方法:
public class MyService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "MyServiceChannel";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My Service")
.setContentText("Service is running")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
// 进行其他的服务逻辑
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "My Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}
public class MyService extends Service {
private static final long INTERVAL = 60 * 1000; // 1分钟
private AlarmManager alarmManager;
private PendingIntent alarmIntent;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyService.class);
this.alarmIntent = PendingIntent.getService(this, 0, alarmIntent, 0);
startAlarm();
// 进行其他的服务逻辑
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
cancelAlarm();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void startAlarm() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, alarmIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, alarmIntent);
}
}
private void cancelAlarm() {
alarmManager.cancel(alarmIntent);
}
}
以上是两种常用的保持Android服务长时间运行的方法,你可以根据自己的需求选择适合的方法。