android使用wifi实例

package com.example.wifitest1;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tv;
	private Button btn;

	// wifi管理器
	private WifiManager wifimanager;
	// 扫描结果
	private ScanResult result;
	// 扫描结果列表
	private List<ScanResult> scanlist;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		wifimanager = (WifiManager) MainActivity.this
				.getSystemService(Context.WIFI_SERVICE);
		tv = (TextView) findViewById(R.id.textView1);
		btn = (Button) findViewById(R.id.button1);

		if (!wifimanager.isWifiEnabled()) {
			wifimanager.setWifiEnabled(true);
		}
		wifimanager.saveConfiguration();
		scanlist = wifimanager.getScanResults();

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 定义一个可变的字符串
				StringBuilder sb = new StringBuilder();
				sb.append("start:\n");
				if (scanlist != null) {
					for (int i = 0; i < scanlist.size(); i++) {
						result = scanlist.get(i);
						sb.append(result.toString()).append("\n");
					}
				}
				tv.setText(sb.toString());
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}


另外需要在Androidmanifest.xml中添加user-permission权限,在<manifest></manifest>之间添加

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

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

即可

打印出周围的wifi热点。。。


你可能感兴趣的:(android,service,import,NetWork,button,menu)