检查Internet连接与广播接收器不工作

时间:2016-12-27 14:39:05

标签: android broadcastreceiver

我有一个类,用于检查在我的应用程序运行时是否连接了Internet:

public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

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

    if (isConnected){
        Toast.makeText(context, "CONNECTED!", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(context, "NOT CONNECTED", Toast.LENGTH_LONG).show();
    }
}}

我在清单文件中,在应用程序括号

之间添加了此接收器
        <receiver
        android:name=".DataHelpers.NetworkChangeReceiver"//DataHelpers is the package name
        android:label="NetworkChangeReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

当我运行依赖互联网的应用程序并关闭连接时,我不应该收到“已连接!”的Toast消息吗?接收方是否应该识别出我的onReceive()课程中没有连接并触发NetworkChangerReceiver方法?

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

 public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}

定义BroadcastReceiver

 public class NetworkChangeReceiver extends BroadcastReceiver {

    public boolean isConnected = true;
    String status;
    Context Cnt;
    Activity activity;
    Activity parent;
    AlertDialog alert;


    public NetworkChangeReceiver(Activity a) {
        // TODO Auto-generated constructor stub
        parent = a;
    }

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

        activity = (Activity) context;
        status = NetworkUtil.getConnectivityStatusString(context);
        if (status.equals("Not connected to Internet")) {
            //Toast.makeText(context, "Internet connection required", Toast.LENGTH_LONG).show();
        }
        ReturnStatus(status, context);
    }

    public void ReturnStatus(String s, final Context cnt) {
        if (s.equals("Mobile data enabled")) {
            isConnected = true;
            //Intent intent = new Intent(activity,activity.getClass());
            //activity.startActivity(intent);

        } else if (s.equals("Wifi enabled")) {
            isConnected = true;

        } else {
            isConnected = false;
            final AlertDialog.Builder builder = new AlertDialog.Builder(cnt);
            // Set the Alert Dialog Message
            builder.setMessage("Internet connection required")
                    .setCancelable(false)
                    .setPositiveButton("continue",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                    activity.finish();
                                    Intent intent = new Intent(activity, activity.getClass());
                                    activity.startActivity(intent);
                                }
                            })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int id) {
                            if(alert.isShowing()) {
                                isConnected=false;
                                alert.dismiss();
                            }
                        }
                    });

            alert = builder.create();
            alert.show();
        }
    }

    public boolean is_connected() {
        return isConnected;
    }
}

现在在任何活动中使用它们:

public NetworkChangeReceiver receiver;
 Boolean bl = true;

public void checkInternet() {
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    receiver = new NetworkChangeReceiver(this);
    registerReceiver(receiver, filter);
    bl = receiver.is_connected();
    Log.d("Boolean ", bl.toString());
}

onPause()

中取消注册接收者
  @Override
protected void onPause() {
    super.onPause();
    try {
        unregisterReceiver(receiver);
    } catch (Exception e) {

    }
}

答案 1 :(得分:0)

您仍需要在onCreate()左右明确注册,例如

registerReceiver(new NetworkChangeReciever(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));