android.os.NetworkOnMainThreadException在android上使用rxjava [英] android.os.NetworkOnMainThreadException using rxjava on android

查看:141
本文介绍了android.os.NetworkOnMainThreadException在android上使用rxjava的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法实现rxJava以检查android上是否存在互联网连接我是这样做的:

i'm having trouble implementing rxJava in order to check if there is internet connection on android i'm doing it like this:

我的启动器活动我有这在onCreate中:

on my launcher activity i have this in onCreate:

AndroidObservable.bindActivity(this,
            Observable.just(Utils.isActiveInternetConnection(Launcher.this)))
            .subscribeOn(Schedulers.newThread())
            .subscribe(new Action1<Boolean>() {
                @Override
                public void call(Boolean aBoolean) {
                    if (aBoolean) {
                        Toast.makeText(Launcher.this, "There is internet connection", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Launcher.this, "There is no internet connection", Toast.LENGTH_SHORT).show();
                    }
                }
            });

我有一个Utils类,它是一个带有静态方法的最终类,observable正在使用的方法是这些:

i have an Utils class it is a final class with static methods the methods in that the observable is using are this ones:

    public static boolean isActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e("network", "Error checking internet connection", e);
        }
    } else {
        Log.d("network", "No network available!");
    }
    return false;
}

private static boolean isNetworkAvailable(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        return true;
    }
    else {
        return false;
    }
}

我收到android.os.NetworkOnMainThreadException和我找不到原因,提前谢谢。

i'm receiving android.os.NetworkOnMainThreadException and i can't find why, thanks in advance.

推荐答案

Observable.just(...)<在调用线程(主线程,在本例中)上立即调用/ code>。您的代码实际上只是内联版本:

Observable.just(...) is called immediately on the calling thread (the main thread, in this case). Your code is effectively just an inlined version of this:

boolean activeConn = Utils.isActiveInternetConnection(Launcher.this);
AndroidObservable.bindActivity(this, 
        Observable.just(activeConn))
        .subscribeOn(...)
        ...

你试图通过调用 subscribeOn()将其从主线程移开 - 但是电话已经发生。

You've tried to move it off the main thread by calling subscribeOn() - but the call has already happened.

我们处理这个问题的方式(我不确定这是最好的方式,但它有效)是推迟网络或阻止调用直到订阅发生,设置observable在正确的线程上运行,然后订阅:

The way we handle this (and I'm not sure that this is the best way, but it works) is to defer the network or blocking call until subscription happens, set up the observable to run on the correct threads, and then subscribe:

AndroidObservable.bindActivity(this,
        Observable.defer(new Func0<Boolean>() {
            @Override
            public Observable<Observable<Boolean>> call() {
                return Observable.just(Utils.isActiveInternetConnection(Launcher.this));
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                if (aBoolean) {
                    Toast.makeText(Launcher.this, "There is internet connection", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Launcher.this, "There is no internet connection", Toast.LENGTH_SHORT).show();
                }
            }
        });

这篇关于android.os.NetworkOnMainThreadException在android上使用rxjava的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆