如何防止退出应用时服务被破坏

How to prevent the service from being destroyed when I exit the app

我有一项服务 class 从 firebase 读取并将读数发送到模型以获得响应。但是,问题是当我退出应用程序时服务被破坏了。

备注:

  1. 我的服务在我登录时启动,当我在应用程序中注销时必须销毁
  2. 我的服务 class 包含广播接收器作为内部 class 以显示对话框,以防我从模型获得所需的响应以显示自定义对话框。

^ 这条注释很重要

我查找了已经提出的问题,没有人解决我的问题。

退出应用程序时我必须让服务运行

清单文件:

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

服务class:

public class ModelServiceM extends Service {
    
    Timer timer = new Timer();
    BroadcastReceiver mReceiver;

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

    @Override
    public void onCreate() {
      //skip this for now
        /*IntentFilter filter = new IntentFilter();
        filter.addAction("action");
        mReceiver = new MyReceiver();
        registerReceiver(mReceiver, filter);*/
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d("message","onStartCommand Lunched");
        //things

            timer.schedule(new TimerTask() {
                public void run() {
                  
                  //things 
            }, delay,period);


    //return START_STICKY;
        flags=START_STICKY;
    return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        Log.d("message","onDestroy Lunched");
        timer.cancel();
        //unregisterReceiver(mReceiver);
        super.onDestroy(); } 


    // use this as an inner class like here or as a top-level class
    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // do something
            Log.d("RECEIVER","onReceive lunched");
            //things
        }
        // constructor
        public MyReceiver(){ }
    }
}

看看即使应用程序关闭它们仍然存在的 ForegroundServices。