检查网络连接 android

Check network connectivity android

我是在 Android 中使用 Service 的新手,我很困惑。我有 Activity 并且我想检查网络连接是否正常(wifi 或 3g)。我实现了一个简单的 Service 和一个 BroadcastReveiver

这里是Service

的代码
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);

    }
}

这里是BroadcastReceiver

的代码
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!!!!!!!!");

     }

    }
}

这是Manifest

中的用户权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这是我在 Activity

onCreate 方法中输入的代码
this.intent = new Intent(this, NetworkCheck.class);
        this.startService(this.intent);

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

这不起作用,我不知道为什么。

不建议一直检查连接,只在需要时调用它:

WiFi:

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();
}

您在 activity 中注册的 IntentFilter 没有任何与之关联的过滤器。

由于您正在使用 "connection"(您的 CONNECTION 常量)的操作创建意图,因此您需要创建一个具有相同操作的 IntentFilter 来触发您的 BroadcastReceiver。

例如:

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

您获取当前网络状态的测试似乎不正确。如果 WIFI 或移动数据不可用,此测试将 return 错误。

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

如果您要查看网络数据是否可用,请查看如何 official documentation handles the test。你可以用类似的东西替换你的测试:

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

广播接收器的intent过滤器下面添加了吗

 <receiver android:name=".BroadcastReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

        </intent-filter>
    </receiver>

这是为了您检查您的网络连接。

public boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in air plan mode it will be null
    return (netInfo != null && netInfo.isConnected());

}