Retrofit2.0 android.os.NetworkOnMainThreadException解决方法

时间:2022-10-06 08:00:22


在使用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()) 总有个能解决问题。