0123WIFI网络操作(一)

 1 package mars.wifi;
 2 
 3 import android.app.Activity;
 4 import android.content.Context;
 5 import android.net.wifi.WifiManager;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.view.View.OnClickListener;
 9 import android.widget.Button;
10 import android.widget.Toast;
11 
12 public class WifiActivity extends Activity {
13     /** Called when the activity is first created. */
14     private Button startButton = null;
15     private Button stopButton = null;
16     private Button checkButton = null;
17     private WifiManager wifiManager = null;
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22         startButton = (Button)findViewById(R.id.startWifi);
23         stopButton = (Button)findViewById(R.id.stopWifi);
24         checkButton = (Button)findViewById(R.id.checkWifi);
25         startButton.setOnClickListener(new StartWifiListener());
26         stopButton.setOnClickListener(new StopWifiListener());
27         checkButton.setOnClickListener(new CheckWifiListener());
28     }
29     class StartWifiListener implements OnClickListener{
30 
31         @Override
32         public void onClick(View v) {
33             wifiManager = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
34             wifiManager.setWifiEnabled(true);
35             System.out.println("wifi state --->" + wifiManager.getWifiState());
36             Toast.makeText(WifiActivity.this, "当前Wifi网卡状态为" + wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
37         }
38     }
39     class StopWifiListener implements OnClickListener{
40 
41         @Override
42         public void onClick(View arg0) {
43             // TODO Auto-generated method stub
44             wifiManager = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
45             wifiManager.setWifiEnabled(false);
46             System.out.println("wifi state --->" + wifiManager.getWifiState());
47             Toast.makeText(WifiActivity.this, "当前Wifi网卡状态为" + wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
48         }
49     
50     }
51     
52     class CheckWifiListener implements OnClickListener{
53 
54         @Override
55         public void onClick(View v) {
56             wifiManager = (WifiManager)WifiActivity.this.getSystemService(Context.WIFI_SERVICE);
57             System.out.println("wifi state --->" + wifiManager.getWifiState());
58             Toast.makeText(WifiActivity.this, "当前Wifi网卡状态为" + wifiManager.getWifiState(), Toast.LENGTH_SHORT).show();
59         }
60         
61     }
62 }

为什么是WifiActivity.this.getSystemService(Context.WIFI_SERVICE);?因为监听器是一个内部类,而现在要操作WifiActivity这个外部的类,所以必须要有this指明

Activity ,Serivce都是 Context的一个子类,拥有父类所有的属性

posted @ 2010-10-08 14:22  Kstyjobx!!  阅读(258)  评论(0编辑  收藏  举报