这是我的后台代码
public class BackgroundService extends Service {
private int interval1 = 60; // 60 seconds
private int interval2 = 60; // 60 seconds
//=============================================================================================================================
private Handler mTimer1 = new Handler();
private Runnable mTask1 = new Runnable() {
public void run() {
Looper.prepare();
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);//, Looper.getMainLooper());
mTimer1.postDelayed(this, interval1 * 1000L);
Looper.loop();
}
};
//=============================================================================================================================
private Handler mTimer2 = new Handler();
private Runnable mTask2 = new Runnable() {
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");
}
mTimer2.postDelayed(this, interval2 * 1000L);
}
};
当我运行应用程序时,它几秒钟后就停止了。它在日志控制台中显示以下错误消息
请帮我解决这个问题
谢谢
最佳答案
不能多次为Looper
准备Thread
。在准备之前,检查Looper
是否与Thread
相关。
private Runnable mTask1 = new Runnable() {
public void run() {
if(Looper.myLooper() == null) { // check already Looper is associated or not.
Looper.prepare(); // No Looper is defined So define a new one
}
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);//, Looper.getMainLooper());
mTimer1.postDelayed(this, interval1 * 1000L);
Looper.loop();
}
};
关于java - 如何在android中解决此错误-java.lang.RuntimeException:每个线程只能创建一个Looper,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22296317/