请问文件中加相应的权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="alice.bw.com.wifidirectdemo">
<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"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
主布局中activity_main
<?xml version="1.0" encoding="utf-8"?>
<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>
在我们的主页面
package alice.bw.com.wifidirectdemo;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
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.PeerListListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
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();
Collection<WifiP2pDevice> deviceList = wifiP2pDeviceList.getDeviceList();
MainActivity.this.peers.addAll(deviceList);
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 "";
}
}