super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mGestureDetector = new GestureDetector(this, new MyGestureListener());
//注册广播接受者java代码
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//创建广播接受者对象
BatteryReceiver batteryReceiver = new BatteryReceiver();
//注册receiver
registerReceiver(batteryReceiver, intentFilter);
}
//level2 为wifi强度,值是 0-50 50-70 70 - 100 自己分档 数值越小强度越大。
//wifi状态:0 连接上,1 是未连接, 2还是3 是连接中
class BatteryReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
int status=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
if(status==BatteryManager.BATTERY_STATUS_CHARGING)
{
Log.i("tt","mylog:rrr");
}
int wifi_state = intent.getIntExtra("wifi_state", 0);
int level2 = Math.abs(((WifiManager)getSystemService(WIFI_SERVICE)).getConnectionInfo().getRssi());
Log.i("tt","mylog:wifilevel = "+level2);
// TODO Auto-generated method stub
//判断它是否是为电量变化的Broadcast Action
if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())){
//获取当前电量
int level = intent.getIntExtra("level", 0);
//电量的总刻度
int scale = intent.getIntExtra("scale", 100);
//把它转成百分比
Log.i("tt","mylog:电量为:"+(level*100/scale));
}
Log.i("tt","mylog: wifi_state: "+wifi_state);
switch (wifi_state) {
case WifiManager.WIFI_STATE_DISABLING:
Log.i("TAG", "1111:" + WifiManager.WIFI_STATE_DISABLING);
break;
case WifiManager.WIFI_STATE_DISABLED:
Log.i("TAG", "2222:" + WifiManager.WIFI_STATE_DISABLED);
break;
case WifiManager.WIFI_STATE_ENABLING:
Log.i("TAG", "33333:" + WifiManager.WIFI_STATE_ENABLING);
break;
case WifiManager.WIFI_STATE_ENABLED:
Log.i("TAG", "4444:" + WifiManager.WIFI_STATE_ENABLED);
break;
case WifiManager.WIFI_STATE_UNKNOWN:
Log.i("TAG", "5555:" + WifiManager.WIFI_STATE_UNKNOWN);
break;
}
//if(Intent.)
}
}
这是在网上找到的结果,但是经过实测,当wifi信号切断再连接上时,信号强度检测变化特别慢。所以我使用的是开个线程,在每5秒检测 int level2 = Math.abs(((WifiManager)getSystemService(WIFI_SERVICE)).getConnectionInfo().getRssi()); 然后这么就可以实时点。