1
完全公開,我仍然在學習RxJava,如果很多可用教程不可用,那麼掌握這個想法有點困難新手友好。RxJava - 無法在未調用Looper.prepare()的線程中創建處理程序 - API 16
此錯誤發生在API 16上,在上面的API 23 &上正常工作(已在下面進行了測試)。如你所見,我試圖用RxJava取代異步任務。
這是我的代碼:
private void getGps() {
TrackGPS gps = new TrackGPS(this);
Single.fromCallable(() -> {
if (gps.canGetLocation()) {
mMainVariables.setLongitude(gps.getLongitude());
mMainVariables.setLatitude(gps.getLatitude());
if (mMainVariables.getLongitude() != 0.0) {
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(mMainVariables.getLatitude(), mMainVariables.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
Log.e("Address:", addresses.get(0).getAddressLine(0));
mMainVariables.setAddress(addresses.get(0).getAddressLine(0));
mMainVariables.setCity(addresses.get(0).getLocality());
mMainVariables.setState(addresses.get(0).getAdminArea());
mMainVariables.setCountry(addresses.get(0).getCountryName());
mMainVariables.setPostalCode(addresses.get(0).getPostalCode());
mMainVariables.setKnownName(addresses.get(0).getFeatureName());
Log.d("Lat Long:", "Lat: " + Double.toString(mMainVariables.getLatitude()) + " Long: " + Double.toString(mMainVariables.getLongitude()));
return addresses.get(0).getAddressLine(0);
} else {
gps.showSettingsAlert();
}
} else {
Toasty.error(this, "Can't locate GPS", Toast.LENGTH_SHORT, true).show();
}
return "";
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((result) -> {
mTxtResult.setText(result);
});
}
編輯:以下堆棧:
05-23 20:26:58.936 3420-3420/com.example.ga.realm3 E/AndroidRuntime: FATAL EXCEPTION: main
io.reactivex.exceptions.OnErrorNotImplementedException: Can't create handler inside thread that has not called Looper.prepare()
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
at io.reactivex.internal.observers.ConsumerSingleObserver.onError(ConsumerSingleObserver.java:45)
at io.reactivex.internal.operators.single.SingleObserveOn$ObserveOnSingleObserver.run(SingleObserveOn.java:79)
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
at android.os.Handler.handleCallback(Handler.java:730)
啊,所以這是錯誤。您可以在前後顯示它,但不能在後臺線程中顯示。 – Rosenberg
是的,這是正確的。它可以進入doOnSubscribe()和subscribe()塊,但不在BG線程中。 –