在 Android 中关闭活动后的后台服务

Ade*_*cus 0 service android background-process

我尝试创建应用程序,检查一些远程数据库的新闻和活动。当应用程序运行时,它工作正常,应用程序检查,显示通知等。但是如果用户关闭应用程序,一切都会停止。是否可以在应用程序中创建后台服务,在应用程序关闭后工作(例如,用于发送本地通知)?如果可能的话,我必须做什么?

PS 我了解 Firebase 和 Google Cloud,但我想创建独立的应用程序。

小智 5

As @Flo We said Service is the only option you can use

public class BackGroundService extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service","Started");

//Write your code here to run in background


        return super.onStartCommand(intent, flags, startId);
    }

}
Run Code Online (Sandbox Code Playgroud)

使用 Intent 启动服务,不要在 onDestroy 上停止服务,它将继续在后台运行