要保持后台运行的服务(Android),你可以按照以下步骤进行操作:
以下是一个示例代码:
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
public class MyBackgroundService extends Service {
private static final int NOTIFICATION_ID = 1;
@Override
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION_ID, createNotification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 执行后台任务的逻辑
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private Notification createNotification() {
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("后台服务")
.setContentText("服务正在运行中...")
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent);
return builder.build();
}
}
要启动此服务,你可以在Activity中调用startService()方法:
Intent intent = new Intent(this, MyBackgroundService.class);
startService(intent);
请确保在AndroidManifest.xml文件中声明服务:
这样,你的服务就会在后台持续运行,并且在被系统杀死后能够自动重启。
上一篇:保持和移动元素(窗口)