簡體   English   中英

當應用程序在 android 中進入后台時服務停止

[英]Service stops when app goes to background in android

我一直在服務 class 中使用處理程序,處理程序負責通過套接字每 5 秒發送一次位置。 我在onDestroy方法中取消計時器。 當應用程序進入后台時,服務會在 1 分鍾后停止。

public Runnable mn_Runnable12 = new Runnable() {
        public void run() {
            gps = new GPSTracker(LocationService.this);
            if (gps.canGetLocation()) {
                latString = Double.toString(gps.getLatitude()); // Live
                logString = Double.toString(gps.getLongitude());
                connection= MyApplication.getInstance().getConnection();
                if (connection!=null&&connection.isConnected()) {
                    sendLocation();
                }

            }
        }
    };

這是在服務的onCreate()里面。

 T.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      mHandler12.postDelayed(mn_Runnable12, 5000);
                                  }
                              },
                5000,
                5000);

我嘗試在服務的onDestroy方法中停止處理程序,服務被置頂但處理程序仍在運行。

 @Override
    public void onDestroy() {
        System.out.println("Location Service Detaroy-----");
        // T.cancel();
    // T.purge();
     if(mHandler12!=null){
         mHandler12.removeCallbacksAndMessages(null);
     }if(mHandler10!=null){
        mHandler10.removeCallbacksAndMessages(null);
    }
    }

我一直在服務 class 中使用處理程序,處理程序負責通過套接字每 5 秒發送一次位置。 我在onDestroy方法中取消計時器。 當應用程序進入后台時,服務會在 1 分鍾后停止。

public Runnable mn_Runnable12 = new Runnable() {
        public void run() {
            gps = new GPSTracker(LocationService.this);
            if (gps.canGetLocation()) {
                latString = Double.toString(gps.getLatitude()); // Live
                logString = Double.toString(gps.getLongitude());
                connection= MyApplication.getInstance().getConnection();
                if (connection!=null&&connection.isConnected()) {
                    sendLocation();
                }

            }
        }
    };

這是在服務的onCreate()里面。

 T.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      mHandler12.postDelayed(mn_Runnable12, 5000);
                                  }
                              },
                5000,
                5000);

我嘗試在服務的onDestroy方法中停止處理程序,服務被置頂但處理程序仍在運行。

 @Override
    public void onDestroy() {
        System.out.println("Location Service Detaroy-----");
        // T.cancel();
    // T.purge();
     if(mHandler12!=null){
         mHandler12.removeCallbacksAndMessages(null);
     }if(mHandler10!=null){
        mHandler10.removeCallbacksAndMessages(null);
    }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM