Retrofit2.0 android.os.NetworkOnMainThreadException解决方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit2.0 android.os.NetworkOnMainThreadException解决方法相关的知识,希望对你有一定的参考价值。
在使用Retrofit2.0中出现了android.os.NetworkOnMainThreadException异常,代码如下:
FamousInfoModel.getInstance(getActivity()).queryLookUp("人才",mCurrentPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mSubscriber);
根据网上意思,是要起一个新线程,代码如下:
new Thread()
@Override
public void run()
FamousInfoModel.getInstance(getActivity()).queryLookUp("人才",mCurrentPage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mSubscriber);
.start();
运行没有问题,但总看着别扭,有没有更好的方式呢?结果是肯定的。Schedulers.io()改为Schedulers.newThread()即可。
FamousInfoModel.getInstance(getActivity()).queryLookUp("人才",mCurrentPage)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mSubscriber);
当我们在自定义view里面请求数据时,上面的方法就不行了,如下
public class HomeSlideShowView extends FrameLayout
public HomeSlideShowView(Context context)
this(context, null);
public HomeSlideShowView(Context context, AttributeSet attrs)
this(context, attrs, 0);
public HomeSlideShowView(Context context, AttributeSet attrs, int defStyle)
super(context, attrs, defStyle);
this.context = context;
initView();
private void initView()
LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this,
true);
dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
adverList = new ArrayList<>();
imageViewsList = new ArrayList<>();
dotViewsList = new ArrayList<>();
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setFocusable(true);
mAdapter = new MyPagerAdapter(adverList);
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(new MyPageChangeListener());
//此处省去...
private void processData()
Log.d(TAG, "processData ");
APIWrapper.getInstance().getBannerImages()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<JavaResponse<List<Advertisement>>>()
@Override
public void onCompleted()
@Override
public void onError(Throwable e)
@Override
public void onNext(JavaResponse<List<Advertisement>> response)
List<Advertisement> list = response.data;
mHandler.obtainMessage(FRESH_BANNER_DATA, list).sendToTarget();
);
android.os.NetworkOnMainThreadException异常出现时,.subscribeOn(Schedulers.newThread()) 与 .subscribeOn(Schedulers.io()) 总有个能解决问题。
以上是关于Retrofit2.0 android.os.NetworkOnMainThreadException解决方法的主要内容,如果未能解决你的问题,请参考以下文章
Retrofit2.0+OkHttp打印Request URL(请求地址参数)
Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录