Android 监测手机联网状态 wifi、移动数据流量

手机当完成联网时会发送一个广播,我们只要创建一个广播接收者即可,代码如下:

Android 监测手机联网状态 wifi、移动数据流量
package com.example.NetworkChangeReceiver2;

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

/**
 * Created by Heyiyong on 2014-4-20 下午2:23.
 */
public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo.State wifiState = null;
        NetworkInfo.State mobileState = null;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if (NetworkInfo.State.CONNECTED == wifiState) {
            Toast.makeText(MyActivity.instance, "wifi连接成功!",1).show();
            return;
        }
        if (NetworkInfo.State.CONNECTED == mobileState) {//当前的connect不是wifi,并且是移动数据
            Toast.makeText(MyActivity.instance, "移动数据流量连接!",1).show();
            return;
        }
        if (NetworkInfo.State.CONNECTED != wifiState
                && NetworkInfo.State.CONNECTED != mobileState) {//两种都不是
            Toast.makeText(MyActivity.instance, "没有连接任何网络!",1).show();
        }
    }
}
Android 监测手机联网状态 wifi、移动数据流量

 

MyActivity.java

Android 监测手机联网状态 wifi、移动数据流量
package com.example.NetworkChangeReceiver2;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {
    public static MyActivity instance;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        instance = this;
    }
}
Android 监测手机联网状态 wifi、移动数据流量

注意:不要忘了添加权限:

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

注册广播接收者:

Android 监测手机联网状态 wifi、移动数据流量
        <receiver
                android:name=".NetworkChangeReceiver"
                android:label="NetworkConnection" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
Android 监测手机联网状态 wifi、移动数据流量

 

Android 监测手机联网状态 wifi、移动数据流量,布布扣,bubuko.com

Android 监测手机联网状态 wifi、移动数据流量

上一篇:[2011山东省第二届ACM大学生程序设计竞赛]——The Android University ACM Team Selection Contest


下一篇:Android 获取让图片保持在一个区域内所需缩放的倍数