java - Android后台服务错误: Can't create handler inside thread that has not called

标签 java android gps

这是我的任务: 我需要运行 2 个后台服务。一个用于通过 ksoap 将我的移动数据同步到服务器。另一个服务我需要将我的 GPS 位置发送到服务器。 所以我写了这段代码。但是当我添加 gpsTimer 部分时,它在加载应用程序时出现以下错误。请帮助我解决这个问题。,或者告诉我任何其他方法来实现这种情况。

这是我的代码

public class BackgroundService extends Service {

    private Timer timer;
    private Timer gpsTimer;

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

    public void onCreate() {
        super.onCreate();
        timer = new Timer("BackgroundServiceTimer");
        timer.schedule(syncTask, 1000L, 60 * 1000L);

        gpsTimer = new Timer("GPSServiceTimer");
        gpsTimer.schedule(syncTaskGps, 1000L, 10 * 1000L);

    }

    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        timer = null;

        gpsTimer.cancel();
        gpsTimer = null;
    }

    public void onLowMemory() {
        super.onLowMemory();
        stopService(new Intent(com.lk.lankabell.android.activity.BackgroundService.class.getName()));

    }

    private TimerTask syncTaskGps = new TimerTask() {
        public void run() {
          Log.w("GPS Tracker", "Tracker going to run"+new Date());
          LocationManager mlocManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
          LocationListener mlocListener = new MyLocationListener();
          mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);    
        }
    };
    private TimerTask syncTask = new TimerTask() {
        public void run() {
            if (isOnline() == true) {
                Log.w("Method 2", "setUpdateCardAcceptTag");
                setUpdateCardAcceptTag();
                Log.w("Method 3", "getCardBulkSerialData");
                getCardBulkSerialData();
                Log.w("Method 12", "updateStockDataFromRemote");
                updateStockDataFromRemote();
                Log.w("Method 5", "SetRemarksData");
                SetRemarksData();
                Log.w("Method 6", "SetCardSaleData");
                SetCardSaleData();
                Log.w("Method 7", "synchMerchants");
                synchMerchants();
                Log.w("Method 9", "getUpdatedCities");
                getUpdatedCities();
                Log.w("Method 10", "getNotifications");
                getNotifications();
                Log.w("Method 11", "getNextSerialDetails");
                getNextSerialDetails();
                Log.w("Method 12", "getNextSerialDetails");
                //synchLocations();
                Log.w("Method 13", "synchLocations");

            }
        }
    };

这是我的错误:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

enter image description here

最佳答案

使用Handler代替Timer/TimerTask

public class MyService extends Service {
private Handler mTimer = new Handler();
private Runnable mTask = new Runnable() {
@Override
public void run() {
//DO SOMETHING HERE
mTimer.postDelayed(this, interval*1000L);
}
};

private int interval = 60; // 60 seconds

public void onCreate() {
mTimer.postDelayed(mTask, interval*1000L); //start the timer for the first time
}

public void onDestroy() {
if(mTimer != null) {
mTimer.removeCallbacks(mTask); //cancel the timer
}
}
}

通过使用Handler,你有一个优势,你可以随时重置间隔,例如首先你希望它每5秒运行一次,而不是用户决定每1秒运行一次,只需更改间隔变量并调用mTimer.postDelayed再次。

关于java - Android后台服务错误: Can't create handler inside thread that has not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193259/

相关文章:

python - MapBox 使用的标准 GPS 纬度/经度/缩放坐标

java - 纬度和经度以管道符号返回。如何处理?

java - HtmlUnitDriver 中预期的内容类型为 'application/javascript'

android - 如何使用 Jetpack Navigation 从嵌套 fragment 导航到父 fragment ?

java - Android Studio 中的 appLocale 设置

android - 如何加载特定的SDK?

android - 从 Location.distanceBetween() 返回的初始方位角的比例是多少

java - 强制子类将某个字段的值设为 "implement"

java - PowerMockito 与 TestNG 和 Mockito 框架

java - 在java中写在linux chardevice上