Android:用于互联网连接的 BroadcastReceiver

Android: BroadcastReceiver for internet connection

我正在尝试让我的 BroadcastReceiver 工作,但是当我断开互联网连接时我遇到了问题,我得到了 Toast "Please connect the device to the internet.",另一方面我Toast "Please connect the device to the internet." 当我再次建立互联网连接时。 class有问题吗?

package com.bustracker;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class ConnectionChangeReceiver extends BroadcastReceiver {

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

  ConnectivityManager connectivityManager = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetInfo = connectivityManager
    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
  boolean isConnected = activeNetInfo != null
    && activeNetInfo.isConnectedOrConnecting();
  if (isConnected) {
   Toast.makeText(context, "The device is connected to the internet ",
     Toast.LENGTH_SHORT).show();
   Log.i("NET", "connecte" +isConnected);
  } else {
   Toast.makeText(context, "Please connect the device to the internet.",
     Toast.LENGTH_SHORT).show();
  }

 }
}

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

问题是您获得的是移动数据连接而不是 wifi,因此即使设备已连接以获取当前 NetworkInfo 无论如何

,它仍然会让您出错
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();