如果我关闭我的应用程序,服务将关闭

Service will close if i close my application

我正在从应用程序 class 调用 服务,如果我关闭该应用程序或从当前 运行 个应用程序中删除,该服务将自动销毁,我没有在 Destroy() 方法中写任何代码

在这里调用服务是代码:

 Intent syncIntent = new Intent(this, ScanBLE_Service.class);
 this.startService(syncIntent);

这里是服务代码class

public class ScanBLE_Service extends IntentService {


  public ScanBLE_Service() {
    super(ScanBLE_Service.class.getName());
    // TODO Auto-generated constructor stub

    mHandler = new Handler();

}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
                 demo();
}}

    private void demo() {

    mHandler.removeCallbacksAndMessages(null);
    mHandler.postDelayed(new Runnable() {
                             @Override
                             public void run() {
                                  Toast.makeText(getApplicationContext(), "Demoooo", Toast.LENGTH_SHORT).show();

                    demo();
                 }
            }, 5000
    );
}

是的,如果关闭应用程序,服务将关闭。一种情况是,当服务不会关闭时,通知屏幕上会有一个持续的通知。 更多here

正常行为是即使应用程序关闭,服务也会保持 运行,因为它与应用程序分离并在后台运行,除非您调用 stopSelf() 或 stopService(x,x)它应该保持 运行..

PS:还有另一种类型的服务,它是 IntentService(扩展了 IntentService 而不是 Service),一旦执行 onHandleIntent() 中的代码,它就会自动停止..

您应该使用服务,而不是 IntentService。扩展服务 class 并覆盖 onStartCommand 方法,然后在该方法中进行计算

为了 运行 您的服务,即使在应用程序被销毁后,您也需要执行以下操作。

  1. 通过 Service classs
  2. 扩展您的服务
  3. return START_STICKYonStartCommand()
  4. 覆盖onTaskRemoved(参考下面的示例代码)。

    public class MyIntentService 扩展服务 { 定时器 mTimer;

        @Override
        public void onCreate()
        {
            super.onCreate();
    
            mTimer = new Timer();
    
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            mTimer.schedule(mTimerTask, 1000, 5000);
    
            return START_STICKY;
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent)
        {
            return null;
        }
    
    
        TimerTask mTimerTask = new TimerTask()
        {
            @Override
            public void run()
            {
              System.out.println("timer task run");
    
            }
        };
    
    
        @Override
        public void onTaskRemoved(Intent rootIntent)
        {
            System.out.println("onTaskRemoved");
    
            Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
            restartServiceIntent.setPackage(getPackageName());
    
            PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
    
            super.onTaskRemoved(rootIntent);
        }
    
    }