关于实时监听手机wifi信号和电量情况以及网络形式的改变

来源:互联网 发布:程序员mysql 书籍推荐 编辑:程序博客网 时间:2024/04/29 20:11

注册广播

private void registerBroadCast() {    receiver = new PadReceiver();    IntentFilter filter = new IntentFilter();    filter.addAction(Intent.ACTION_BATTERY_CHANGED);    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);    registerReceiver(receiver,filter);}
private class PadReceiver extends BroadcastReceiver{    @Override    public void onReceive(Context context, Intent intent) {        switch (intent.getAction()) {            case Intent.ACTION_BATTERY_CHANGED://电池模块                int current = intent.getExtras().getInt("level", -1);//获得当前电量                int total = intent.getExtras().getInt("scale", -1);//获得总电量                int status = intent.getIntExtra("status", -1);                int health = intent.getIntExtra("health", -1);                int percent = current * 100 / total;                charge.setText("电量" + percent + "%");                alarmCharge(status, health);//发出提醒等操作                break;            case WifiManager.WIFI_STATE_CHANGED_ACTION://wifi模块                WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);                int level = Math.abs(wifiManager.getConnectionInfo().getRssi());//获取绝对值                int wifi_state = intent.getIntExtra("wifi_state", 0);//获取wifi状态                changeState(wifi_state);//发出提醒等操作                break;
            case ConnectivityManager.CONNECTIVITY_ACTION://网络形式改变2g,3g,4g,wifi
                String type = NetUtil.getNetType(this);//http://blog.csdn.net/lzy20ls/article/details/72769838 获取当前手机网络信息工具类
break;
        }    }}private void changeState(int wifi_state) {    switch (wifi_state) {        case WifiManager.WIFI_STATE_DISABLING://wifi正在关闭            break;        case WifiManager.WIFI_STATE_DISABLED://wifi不可用            break;        case WifiManager.WIFI_STATE_ENABLING://wifi正在打开            break;        case WifiManager.WIFI_STATE_ENABLED://wifi可用            break;        case WifiManager.WIFI_STATE_UNKNOWN://未知wifi信息            break;    }}private void alarmCharge(int status,int health) {    if (BatteryManager.BATTERY_HEALTH_OVERHEAT == health) {//电池状态很好    } else {        switch (status) {            case BatteryManager.BATTERY_STATUS_UNKNOWN://监控不到电池                break;            case BatteryManager.BATTERY_STATUS_CHARGING://电池状态改变                break;            case BatteryManager.BATTERY_STATUS_DISCHARGING://电池未充电                break;            case BatteryManager.BATTERY_STATUS_NOT_CHARGING://电池没电了                break;        }    }}


阅读全文
0 0
原创粉丝点击