当应用程序进入后台时,计时器在 10 分钟后停止

时间:2021-07-05 13:49:58

标签: android service timer background-service

我需要在应用打开时或在后台每 5 秒发送一次位置,它工作 10 分钟。

计时器用于每 5 秒发送一次位置。我搜索了很多所以计时器不是一个好方法,我不想更改我的服务代码,那么在后台连续工作的最佳方法是什么。服务在后台运行,但计时器停止。

  @Override
public void onCreate() {
    System.out.println("Location Service onCreate--------");
    gps = new GPSTracker(LocationService.this);
    socket();
    T.scheduleAtFixedRate(mTt1, 5000, 5000);
}

 TimerTask mTt1 = new TimerTask() {
        public void run() {
            mHandler12.postDelayed(mn_Runnable12, 5000);
        }
    };



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();
                } else {
                    //System.out.println("mn_Runnable12-------else");
                }

            }
        }
    };

0 个答案:

没有答案
相关问题