Android应用程序测试Wifi非常简单,只需要调用系统的Wifi服务即可对Wifi进行管理,但是由于模拟器中不能使用Wifi的功能,所以测试的操作需要在手机上运行,下面是实例代码:
public class WifiActivity extends Activity {
private Button button1;
private Button button2;
private Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 如果这里直接写this.而不是WifiActivity.this,代表的只是这个内部类的对象,而不是这个Activity的对象
WifiManager wifiManager=(WifiManager)WifiActivity.this.getSystemService(Service.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
Toast.makeText(WifiActivity.this, "当前Wifi的状态-->"+wifiManager.getWifiState(), Toast.LENGTH_LONG).show();
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WifiManager wifiManager=(WifiManager)WifiActivity.this.getSystemService(Service.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
Toast.makeText(WifiActivity.this, "当前Wifi的状态-->"+wifiManager.getWifiState(), Toast.LENGTH_LONG).show();
}
});
button3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WifiManager wifiManager=(WifiManager)WifiActivity.this.getSystemService(Service.WIFI_SERVICE);
Toast.makeText(WifiActivity.this, "当前Wifi的状态-->"+wifiManager.getWifiState(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_wifi, menu);
return true;
}
}
但同时不要忘记添加一些管理的权限,否则系统会报错:
<!-- 访问Wifi和网络所需要的一些权限 -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>