完全披露,我还在学习RxJava,如果可用的许多教程都不是新手友好的话,有点难以理解这个想法。
此错误发生在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)
答案 0 :(得分:1)
您无法在Scheduler
主题中显示与UI相关的内容。您正试图展示Toast
,并且我还假设您的showSettingsAlert()
也在尝试展示对话框。
这违反了线程政策。与
非常相似