检查网络连接的android [英] Check network connectivity android

查看:178
本文介绍了检查网络连接的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新在Android中使用服务,我很困惑。我已经和活动我要检查所有的网络连接到了的时候(WiFi或3G)。我实现了一个简单的服务 BroadcastReveiver

I am new using Service in Android and I am quite confused. I have and Activity and I want to check for all the time that the network connection is up (wifi or 3g). I implemented a simple Service and a BroadcastReveiver.

这里的服务的code

public class NetworkCheck extends IntentService {

private final String CONNECTION = "connection";

public NetworkCheck(String name) {
    super(name);
}

@Override
protected void onHandleIntent(Intent workIntent) {

    ConnectivityManager conMgr = (ConnectivityManager)getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);


    String dataString = workIntent.getDataString();

    if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
            || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {

        // notify user you are not online
        Intent localIntent = new Intent().putExtra(CONNECTION, 0);

        LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);

    }
}

这里的code中的广播接收器

public class NetworkReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

     int value = intent.getIntExtra("connection", 0);
     if(value == 0){
         //now I print, then I will show up a dialog
         System.out.println("NO CONNECTION!!!!!!!!");

     }

    }
}

这是在用户权限清单

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

而这里是code,我把我的活动的的onCreate

this.intent = new Intent(this, NetworkCheck.class);
        this.startService(this.intent);

        LocalBroadcastManager.getInstance(this).registerReceiver(new NetworkReceiver(), new IntentFilter());

这不工作,我想不通为什么。

This does not work and I cannot figure out why.

推荐答案

Isn't建议检查所有的时间连接,调用它,只有当你需要它:

Isn´t recommended to check all the time connectivity, call it only when you need it:

无线

public boolean isConnectedWifi(Context context) {
         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
         return networkInfo.isConnected();
}

3G

public boolean isConnected3G(Context context) {
         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);     
         return networkInfo.isConnected();
}

这篇关于检查网络连接的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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