繁体   English   中英

android 关闭应用后是否可以无限运行服务?

[英]Is it possible to run service endlessly in android even after closing the app?

我试过警报管理器在预定的时间给我通知,但如果我想继续订阅我的服务器上的某个主题,通过关闭应用程序,连接将关闭,我能做些什么来保持与我的服务器的连接,使用web 套接字或后台服务。 我已经尝试过后台服务,但是当应用程序关闭一段时间后它也会停止,没有任何事情可以保持活力。

在服务 class 中使用START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;
}

并将其添加到清单中:

<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"
            android:stopWithTask="false"/>

使用WorkManager来调度任务,尤其是OneTime

如果应用程序被终止,工作人员仍将“运行”事件。

你可以做那样的事情。

  1. 建设工人 Class
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters

class NotifyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {

    override fun doWork(): Result {
        // Method to trigger an instant notification
        triggerNotification()

        return Result.success()
    }
}

工作人员只需要处理通知触发器。

  1. 构建工作请求

现在创建一个OneTimeWorkRequest ,因为您只需要触发一次通知。

或者,您可以使用PeriodicWorkRequest进行重复性工作。

        val notificationWork = OneTimeWorkRequest.Builder(NotifyWorker::class.java)
            .setInitialDelay(delay) // this is when your notification should be triggered 
            .setInputData(inputData) // this is the data you can pass to the NotifyWorker 
            .addTag("notificationWork")
            .build()

现在您已经创建了安排工作所需的一切,您可以要求 WorkManager 将其排队到系统的活动任务列表中:

  WorkManager.getInstance(context).enqueue(notificationWork)

此时,WorkManager 会将工作添加到其队列中,然后确定何时可以运行并按照第一步指定的方式执行工作。 go,你的通知现在会准时触发,无论设备重启应用强制关闭,也无需使用庞大的服务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM