android中wifidirect的操作学习

android4.0以后增加了wifidirect直接连接,两台手机可以通过wifidirect直接连接,方便快速传递东西。

其中涉及到了几个常用的类

WifiP2pDevice表示具体的wifi设备

WifiManager用于代开关闭wifi状态的

WifiP2pManager用来控制整个连接过程操作的类

WifiP2pInfo用于获取连接设备信息的类

具体流程:

首先自定义一个广播接收者,用于监听mWifiP2pManager.initialize(MainActivity.this,getMainLooper(),null);返回的wifidirect状态,包含四个action,WifiDirectBroadReceiver.java

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();

		if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {//P2P功能是否打开
			int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);// EXTRA_WIFI_STATE 为发现wifi P2p是否可见的key
			if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
				Log.d(TAG, "t"+state);
			}else{
				Log.d(TAG, "f"+state);
			}
		}
		if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {// 发现对等p2p
			if (manager != null) {
				manager.requestPeers(channel, (PeerListListener)activity);//
				Log.d(TAG, "WIFI_P2P_PEERS_CHANGED_ACTION请求当前对等信息执行");
			}
		}
		if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {//显示自己p2p信息
			activity.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
			Log.d(TAG,"显示自己的设备信息");
		}
		if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {//连接action
			if (null == manager) {
				return;
			}
			NetworkInfo netWorkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
			if (netWorkInfo.isConnected()) {
				manager.requestConnectionInfo(channel,(ConnectionInfoListener)activity);
			}else {
				activity.resetData();
			}

		}
	}
新建类FindPeers实现PeerListListener接口,当搜索到可用的wifi设备时候,回调onPeersAvailable(WifiP2pDeviceList deviceList)方法

FindPeers.java

public class FindPeers implements PeerListListener {
	private static final String TAG = "findpeers";
	private List<WifiP2pDevice>list = new ArrayList<WifiP2pDevice>();
	private ProgressDialog progressDialog = null;
	private Context context;
	private WifiManager manager;
	private ListView listView;
	private Handler handler;
	
	public FindPeers(Context context,Handler handler) {
		this.context = context;
		manager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
		this.handler = handler;
	}
	
	/**
	 * 搜索对等的peers 启动WIFI_P2P_STATE_ENABLED action
	 */
	@Override
	public void onPeersAvailable(WifiP2pDeviceList deviceList) {
		
		list.clear();
		list.addAll(deviceList.getDeviceList());
		handler.sendEmptyMessage(1);
	}
	
	public boolean isWifiEnable() {
		if (manager != null) {
			return manager.isWifiEnabled();
		}else{
			return false;
		}
	}
	
	public void openWifi() {
		manager.setWifiEnabled(true);
	}
	
	public List<WifiP2pDevice> getP2pDevice() {
		return list;
	}

}

最后在MainActivity中的oncreate方法中进行IntentFilter必要的初始化,以及在onresume中注册已经写好的广播接受者

MainActivity.java

package com.example.wifidirect;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements  PeerListListener,ConnectionInfoListener,ChannelListener {

	private static final String TAG = "MainActivity";

	private final IntentFilter mIntentFilter = new IntentFilter();
	private WifiP2pManager mWifiP2pManager;
	//连接设备信息
	private WifiP2pInfo mInfo;
	private boolean isP2pEnabled = false;
	private List<WifiP2pDevice> mpeers =new ArrayList<WifiP2pDevice>();
	private ProgressDialog mProgressDialog = null;
	private WifiP2pDevice mWifiP2pDevice;
	private WifiP2pManager.Channel mChannel;
	private ListView mListView ;
	WifiPeerListAdapter adapter;
	private Button mSearchBtn;
	private FindPeers findPeers;
	private boolean retryChanel = false;
	private WifiDirectBroadReceiver mReceiver;
	/**自己设备的状态	 */
	private String mStatus = "avaliable";

	private TextView mRename;

	private static final int DIALOG_DISCONNECT  = 1;
	private static final int DIALOG_CANCEL_CONNECT = 2;
	private static final int DIALOG_RENAME = 3;

	String deviceName = "temp";

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				setAdapter();
				break;

			default:
				break;
			}

		};
	};



	@SuppressLint("ShowToast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		init();

		/**可以探测到有效距离内的对等设备*/
		mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {

			@Override
			public void onSuccess() {//只会对成功探测到对等设备这一事件做出通知,而并不会提供任何关于已发现的对等设备的具体信息:
			}

			@Override
			public void onFailure(int arg0) {
				// TODO Auto-generated method stub

			}
		});

	}




	private void init() {

		mListView = (ListView) findViewById(R.id.lv);
		mRename = (TextView) findViewById(R.id.rename);
		mSearchBtn = (Button) findViewById(R.id.search);
		findPeers = new FindPeers(MainActivity.this,mHandler);

		mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
		mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
		mIntentFilter
				.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
		mIntentFilter
				.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

		mWifiP2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
		if (null != mWifiP2pManager) {
			mChannel = mWifiP2pManager.initialize(MainActivity.this,getMainLooper(),null);
			if (mChannel == null) {
				Log.d(TAG,"setup connection fail");
				mWifiP2pManager = null;
			}
		}else{
			Log.d(TAG, "mWifiP2pManager is null");
		}

		mSearchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!findPeers.isWifiEnable()) {
					findPeers.openWifi();
				}
				mpeers.clear();
				setAdapter();

				mWifiP2pManager.discoverPeers(mChannel, new ActionListener() {

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						Toast.makeText(MainActivity.this,"discover success",Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onFailure(int arg0) {
						// TODO Auto-generated method stub
						Toast.makeText(MainActivity.this,"discover fail",Toast.LENGTH_SHORT).show();
					}
				});
			}
		});


	}

	/**
	 * 自定义显示adapter
	 * @author user
	 *
	 */
	private class WifiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {

		private List<WifiP2pDevice>items;
		public WifiPeerListAdapter(Context context,	int textViewResourceId, List<WifiP2pDevice> objects) {
			super(context, textViewResourceId, objects);
			items = objects;
		}

		public List<WifiP2pDevice> getItems() {
			return items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (null == v) {
				v = LayoutInflater.from(MainActivity.this).inflate(R.layout.row_devices1,null);
			}
			final WifiP2pDevice deviceInfo = items.get(position);
			if (deviceInfo != null) {
				TextView deviceName = (TextView) v.findViewById(R.id.device_name);
				TextView deviceDetail = (TextView) v.findViewById(R.id.device_details);
				if (null != deviceName) {
					deviceName.setText(deviceInfo.deviceName);
				}
				if (null != deviceDetail) {
					deviceDetail.setText(getStateStatus(deviceInfo.status));
				}
				final Button connect = (Button) v.findViewById(R.id.connect);
				if ("avaliable".equalsIgnoreCase(getStateStatus(deviceInfo.status))) {
					connect.setText("链接");
				}
				if ("connnected".equalsIgnoreCase(getStateStatus(deviceInfo.status))) {
					connect.setText("断开");
				}

				connect.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						if (connect.getText().equals("链接")) {
							connect(createP2pConfig(deviceInfo));
						}
						if (connect.getText().equals("断开")) {
							cancleConnect(deviceInfo);
						}
					}
				});

			}
			return v;
		}

	}

	/**
	 * 得到链接的状态
	 * @param deviceStatus
	 * @return
	 */
	private static String getStateStatus(int deviceStatus) {
		switch (deviceStatus) {
		case WifiP2pDevice.AVAILABLE:
			return "avaliable";
		case WifiP2pDevice.CONNECTED:
			return "connnected";
		case WifiP2pDevice.FAILED:
			return "failed";
		case WifiP2pDevice.INVITED:
			return "invited";
		case WifiP2pDevice.UNAVAILABLE:
			return "unavailable";
		default:
			return "unknow";
		}

	}
	/**
	 * 连接指定的peer
	 * @param config
	 */
	public void connect(WifiP2pConfig config) {
		mWifiP2pManager.connect(mChannel, config, new ActionListener() {

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
//				Log.d(TAG, "链接到设备:"+mWifiP2pDevice.deviceName+"ipaddress:"+mWifiP2pDevice.deviceAddress);
			}

			@Override
			public void onFailure(int arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this,"connectfail",Toast.LENGTH_SHORT).show();
			}
		});
	}
	/**
	 * 根据device的信息,创建配置信息
	 * @param device
	 * @return
	 */
	public WifiP2pConfig createP2pConfig(WifiP2pDevice device) {
		WifiP2pConfig config = new WifiP2pConfig();
		config.deviceAddress = device.deviceAddress;
		config.wps.setup = WpsInfo.PBC;
		return config;
	}

	public void cancleConnect(WifiP2pDevice device) {
		if (null != mWifiP2pManager) {
			if (device == null || device.status == WifiP2pDevice.CONNECTED) {
				disConnect();
			}else if (device.status == WifiP2pDevice.AVAILABLE || device.status == WifiP2pDevice.INVITED) {
				mWifiP2pManager.cancelConnect(mChannel, new ActionListener() {

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						Toast.makeText(MainActivity.this,"cancleConnect success",Toast.LENGTH_LONG).show();
					}

					@Override
					public void onFailure(int arg0) {
						// TODO Auto-generated method stub
						Toast.makeText(MainActivity.this,"cancleconnect fail error"+arg0,Toast.LENGTH_LONG).show();
					}
				});
			}
		}



	}



	/**
	 * 断开连接
	 */
	public void disConnect() {
		mWifiP2pManager.removeGroup(mChannel, new ActionListener() {

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				mpeers.clear();
				setAdapter();
			}

			@Override
			public void onFailure(int arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this,"disconnect fail error"+arg0,Toast.LENGTH_LONG).show();
			}
		});
	}

	public void setAdapter() {
		if (null == adapter) {
			adapter = new WifiPeerListAdapter(MainActivity.this,R.layout.row_devices,mpeers);
			mListView.setAdapter(adapter);
		}else{
			for (WifiP2pDevice device: mpeers) {
				String name = device.deviceName;
				String sta = getStateStatus(device.status);
			}
			((WifiPeerListAdapter)mListView.getAdapter()).notifyDataSetChanged();
		}
	}

	/**
	 * action WIFI_P2P_THIS_DEVICE_CHANGED_ACTION检测自身device 显示自身设备信息
	 * @param device
	 */
	public void updateThisDevice(WifiP2pDevice device) {
		this.mWifiP2pDevice = device;
		TextView viewOne = (TextView) this.findViewById(R.id.tv);
		TextView viewTwo = (TextView) this.findViewById(R.id.tv1);
		String name = device.deviceName;
		String status = device.status+"";
		viewOne.setText(device.deviceName);
		viewTwo.setText(getStateStatus(device.status));
		mStatus = getStateStatus(device.status);
		Log.d(TAG, "连接前自己的地址"+device.deviceAddress);
	}

	/**
	 * 清空自身信息
	 */
	public void resetData() {
		mWifiP2pDevice = null;
		mpeers.clear();
		setAdapter();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mReceiver == null) {
			mReceiver = new WifiDirectBroadReceiver(mWifiP2pManager, mChannel, this, findPeers);
		}
		registerReceiver(mReceiver, mIntentFilter);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mWifiP2pManager != null) {
			mWifiP2pManager.stopPeerDiscovery(mChannel, null);
		}
		unregisterReceiver(mReceiver);
	}


	@Override
	public void onPeersAvailable(WifiP2pDeviceList deviceList) {
		// TODO Auto-generated method stub
		mpeers.clear();
		mpeers.addAll(deviceList.getDeviceList());
		((WifiPeerListAdapter)mListView.getAdapter()).notifyDataSetChanged();
		if (mpeers.size() == 0) {
			Log.d(TAG, "no peer found");
		}
		mHandler.sendEmptyMessage(1);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mStatus.equalsIgnoreCase("Connect")) {
				disConnect();
			}
		}

		return super.onKeyDown(keyCode, event);
	}



	@Override
	public void onChannelDisconnected() {
		// TODO Auto-generated method stub
		if (mWifiP2pManager != null || ! retryChanel) {
			resetData();
			retryChanel = true;
			mWifiP2pManager.initialize(MainActivity.this,getMainLooper(),this);
		}
	}




	@Override
	public void onConnectionInfoAvailable(WifiP2pInfo arg0) {
		// TODO Auto-generated method stub

	}

}

源码连接: http://download.csdn.net/detail/mockingbirds/8121401


你可能感兴趣的:(android,wifi,NetWork,p2p)