1.获取系统权限
<uses-permission android:name="android.permission.INTERNET" android:required="true"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true"/>
2.主函数
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel mChannel;
private WifiP2pManager mManager;
private WiFiDirectBroadcastReceiver receiver;
private List<WifiP2pDevice> peers = new ArrayList();
private List<String> peersStr = new ArrayList<>();
private ListView lv;
private ArrayAdapter<String> mAdapter;
// private WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
// @Override
// public void onPeersAvailable(WifiP2pDeviceList peerList) {
//
// //旧的不去,新的不来
// peers.clear();
// peers.addAll(peerList.getDeviceList());
//
// //如果AdapterView可以处理该数据,则把变更通知它。比如,如果你有可用对等点的ListView,那就发起一次更新。
// // ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
// if (peers.size() == 0) {
// Log.d("sxl", "No devices found");
// return;
// }
// }
// }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//表示Wi-Fi对等网络状态发生了改变
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
//表示可用的对等点的列表发生了改变
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
//表示Wi-Fi对等网络的连接状态发生了改变
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
//设备配置信息发生了改变
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv = (ListView) findViewById(R.id.lv);
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,peersStr);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
registerReceiver(receiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
//点击搜索周围wifiDirect设备
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
//查找初始化成功时的处理写在这里。
//实际上并没有发现任何服务,所以该方法可以置空。
//对等点搜索的代码在onReceive方法中,详见下文。
}
@Override
public void onFailure(int reasonCode) {
Log.e("sxl","sxl discoverPeers() onFailure reasonCode="+reasonCode);
//查找初始化失败时的处理写在这里。
//警告用户出错了。
}
});
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
WifiP2pDevice peer = peers.get(pos);
connect(peer);//连接
}
public void connect(final WifiP2pDevice device) {
Log.i("sxl", "connect: ");
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;//mac地址
config.wps.setup = 0;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
public void onSuccess() {
Log.e("sxl", "connect onSuccess: "+device.deviceAddress);
}
public void onFailure(int reason) {
Log.e("sxl", "connect onFailure: " + reason);
}
});
}
class WiFiDirectBroadcastReceiver extends BroadcastReceiver{
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private Activity activity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, Activity activity){
this.mManager = manager;
this.mChannel = channel;
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
//确定Wi-Fi Direct模式是否已经启用,并提醒Activity。
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// activity.setIsWifiP2pEnabled(true);
} else {
// activity.setIsWifiP2pEnabled(false);
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
//发现周围设备变化
mManager.requestPeers(mChannel, new MypeerListListener());
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
//连接状态已经改变!需要获取IP
NetworkInfo device1 = (NetworkInfo)intent.getParcelableExtra("networkInfo");
if(device1.isConnected()) {
Log.i("sxl", "onReceive: WIFI_P2P_CONNECTION_CHANGED_ACTION networkInfo.isConnected()");
this.mManager.requestConnectionInfo(this.mChannel, new WifiP2pManager.ConnectionInfoListener() {
public void onConnectionInfoAvailable(WifiP2pInfo info) {
final String ip = info.groupOwnerAddress.getHostAddress();
Log.e("sxl", "ip =" + ip + ","+getWFDMacAddress());
}
});
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
// fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
}
}
}
class MypeerListListener implements PeerListListener{
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
Log.i("sxl", "onPeersAvailable:");
MainActivity.this.peers.clear();
MainActivity.this.peersStr.clear();
MainActivity.this.peers.addAll(wifiP2pDeviceList.getDeviceList());
for (int i = 0; i <MainActivity.this.peers.size() ; i++) {
MainActivity.this.peersStr.add(MainActivity.this.peers.get(i).toString());
}
MainActivity.this.mAdapter.notifyDataSetChanged();
int size = MainActivity.this.peers.size();
Log.i("sxl", "onPeersAvailable: size " + size);
for(int i = 0; i < size; ++i) {
Log.e("sxl", i + " onPeersAvailable: for " + ((WifiP2pDevice)MainActivity.this.peers.get(i)).deviceName);
Log.i("sxl", i + " onPeersAvailable: mac " + ((WifiP2pDevice)MainActivity.this.peers.get(i)).deviceAddress);
Log.i("sxl", "");
}
}
};
public String getWFDMacAddress() {
try {
ArrayList interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
Iterator var2 = interfaces.iterator();
while(var2.hasNext()) {
NetworkInterface ntwInterface = (NetworkInterface)var2.next();
if(ntwInterface.getName().equalsIgnoreCase("p2p0")) {
byte[] byteMac = ntwInterface.getHardwareAddress();
if(byteMac == null) {
return "";
}
StringBuilder strBuilder = new StringBuilder();
for(int i = 0; i < byteMac.length; ++i) {
strBuilder.append(String.format("%02X:", new Object[]{Byte.valueOf(byteMac[i])}));
}
if(strBuilder.length() > 0) {
strBuilder.deleteCharAt(strBuilder.length() - 1);
}
return strBuilder.toString();
}
}
} catch (Exception var7) {
;
}
return "";
}
}
发送的class
public class SendText {
protected int port = 8998;
protected Socket socket;
protected Writer writer;
protected BufferedReader br;
public SendText(final String host, final String msg) {
(new Thread(new Runnable() {
public void run() {
try {
SendText.this.socket = new Socket(host, SendText.this.port);
SendText.this.writer = new OutputStreamWriter(SendText.this.socket.getOutputStream(), "UTF-8");
SendText.this.br = new BufferedReader(new InputStreamReader(SendText.this.socket.getInputStream(), "UTF-8"));
} catch (UnknownHostException var5) {
var5.printStackTrace();
} catch (IOException var6) {
var6.printStackTrace();
}
try {
if(SendText.this.writer == null) {
System.out.println("write is null");
return;
}
SendText.this.writer.write(msg);
SendText.this.writer.write("eof\n");
SendText.this.writer.flush();
SendText.this.writer.close();
SendText.this.socket.close();
} catch (IOException var4) {
var4.printStackTrace();
try {
SendText.this.writer.close();
SendText.this.socket.close();
} catch (IOException var3) {
var3.printStackTrace();
}
}
}
})).start();
}
}
3.主布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="alice.bw.com.wifidirectdemo.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="搜索周围wifiDirect设备"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv"></ListView>
</LinearLayout>