首先要在 AndroidManifest.xml 文件中声明后台服务:

<service android:name=".MyService" />

然后创建一个 MyService 类,继承自 Service 类,实现后台保活的逻辑:

public class MyService extends Service {

    private static final String CHANNEL_ID = 'MyServiceChannel';
    private static final int NOTIFICATION_ID = 1;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(NOTIFICATION_ID, getNotification());
        return START_STICKY;
    }

    private Notification getNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, 'MyService Channel', NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        return builder.build();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

在 onStartCommand 方法中调用 startForeground 方法,将服务设置为前台服务,并传入一个 Notification 对象。这个 Notification 对象将会显示在通知栏中,保证服务不被系统回收。

可以在 getNotification 方法中自定义 Notification 对象的样式和内容。

最后,在需要启动服务的地方调用 startService 方法即可:

Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
Android 后台保活:使用通知栏实现 Java 服务持久运行

原文地址: https://www.cveoy.top/t/topic/l0X6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录