了java.lang.RuntimeException:無法內螺紋創建處理程序尚未調用Looper.prepare()在運行Android的方法中的異常一個MainTask的
我有一個服務調用的方法run
我MainTask
每15秒(用於測試的原因)timer.scheduleAtFixedRate(new MainTask(), 0, 15000);
(稱爲onStartCommand
run方法中的代碼看起來像這樣:
public void run() {
Log.v("MainTask", "run() Called");
GpsHelper gpsHelper = new GpsHelper(getApplicationContext(), this); // This is causing the error - commented out => no error
// Doing some independent webrequests here!
}
的GpsHelper類看起來像這樣(它有一些if語句 - 因爲它也被用來在Mainactivity
外服: mLocationManager.removeUpdates(this);
public GpsHelper(Context context, LocationReceiver locationReceiver) {
this.context = context;
this.locationReceiver = locationReceiver;
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationReceiver instanceof Runnable) {
isRunnable = true;
}
run();
}
/**
* Getting the Location, handling permission, requesting location updates if time is greater than 2 minutes
*/
public void getLocation() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && !isRunnable) {
StaticHelpers.askForFineLocationPermission(context);
} else {
if (isRunnable && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.v("GpsHelper", "Runnable can't get position - check permissions!");
} else {
Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// If time not greater than 2 minutes
// TODO: Move to resources
if (location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
Log.v("GpsHelper", "Using existing location");
locationReceiver.onLocationAvailable(location);
} else {
Log.v("GpsHelper", "No Position Available => Requesting Location Updates");
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (!isRunnable && !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsDialog();
}
}
}
}
得到這個方法被調用的位置後
何時發生此錯誤? 第四次運行叫做
可能的答案需要包含什麼? 答案應該可以幫助我解決這個錯誤而不會改變任何邏輯行爲,並且不應該在UI線程上運行!
Log.v(「MainTask」,「run()Called」); GpsHelper gpsHelper = new GpsHelper(getApplicationContext(),this); 在處理程序中添加此代碼或runOnUiThread() – Kamal