如何使用intentfilter和broadCastReceiver检查WiFi连接?

时间:2015-02-06 11:54:29

标签: android broadcastreceiver

如何使用BroadCastReceiver检查当前是否存在无线连接?

我尝试了一些例子但是我不应该使用哪个intentFilter?

请提供一个例子

1 个答案:

答案 0 :(得分:0)

清单文件: -

<receiver
        android:name="com.ideal.log.activitymaster.NetworkChangeReceiver"
        android:enabled="true" >
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

接收机

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;

    public class NetworkChangeReceiver extends BroadcastReceiver {

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

            String status = getConnectivityStatusString(context);

            Toast.makeText(context, status, Toast.LENGTH_LONG).show();
        }

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

我希望它会有所帮助。

<强> ---- ----- UPDATE 也可以以编程方式注册接收器。 的注册

registerReceiver(receiver, new IntentFilter(
            "android.net.wifi.WIFI_STATE_CHANGED"));

NetworkChangeReceiver receiver = new NetworkChangeReceiver();

取消注册人

@Override
protected void onDestroy() {
    unregisterReceiver(receiver);
    super.onDestroy();
}