赞
踩
链接: WI-FI直连
public class MainActivity extends AppCompatActivity { private static String TAG = "P2P_Test MainActivity"; private final static int SERVER_PROt = 8888; private ListView mListView; private ArrayAdapter<String> mWiFiPeerListAdapter; private WifiP2pManager.Channel mChannel; private WifiP2pManager mManager; private IntentFilter intentFilter = new IntentFilter(); private WiFiDirectBroadcastReceiver mReceiver; private boolean mIsWifiP2pEnabled = false; private List<WifiP2pDevice> mPeers = new ArrayList<>(); private List<String> mDeviceNames = new ArrayList<>(); private WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() { @Override public void onPeersAvailable(WifiP2pDeviceList peerList) { Collection<WifiP2pDevice> refreshedPeers = peerList.getDeviceList(); mPeers.clear(); mDeviceNames.clear(); mPeers.addAll(refreshedPeers); for (WifiP2pDevice peer : refreshedPeers){ mDeviceNames.add(peer.deviceName); } mWiFiPeerListAdapter.notifyDataSetChanged(); } }; private WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() { @Override public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) { // InetAddress from WifiP2pInfo struct. String groupOwnerAddress = wifiP2pInfo.groupOwnerAddress.getHostAddress(); //7.连接成功!! Log.v(TAG,"7.连接成功!!"); if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner) { //群主 Log.v(TAG,"Group ---- > 群主?"); createServerSocket(); } else if (wifiP2pInfo.groupFormed) { //组员 Log.v(TAG,"Group ---- > 组员?"); createClientSocket(groupOwnerAddress); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initListView(); //1.申请权限 Log.v(TAG,"1.申请权限"); getPermission(); //2.初始化 P2p Manager 和 Channel Log.v(TAG,"2.初始化 P2p Manager 和 Channel"); mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); Log.v(TAG,"3.启动广播监听器"); // Indicates a change in the Wi-Fi P2P status. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); // Indicates a change in the list of available peers. intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); // Indicates the state of Wi-Fi P2P connectivity has changed. intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); // Indicates this device's details have changed. intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this,peerListListener,connectionInfoListener); registerReceiver(mReceiver, intentFilter); findViewById(R.id.create_p2p_group).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 3.服务器创建 Group Log.v(TAG,"3.服务器创建 Group"); createP2PGroup(); } }); findViewById(R.id.sacn_p2p_group).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //4.启动搜索对等设备 Log.v(TAG,"4.启动搜索对等设备"); sacnP2PGroup(); } }); } @SuppressLint("MissingPermission") private void sacnP2PGroup() { Log.v(TAG,"4.启动搜索对等设备 p2p是否可用 : " + mIsWifiP2pEnabled); if (mIsWifiP2pEnabled){ mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.v(TAG,"4.启动搜索对等设备 p2p搜索是否启动成功 : true"); //搜索启动 成功 } @Override public void onFailure(int reasonCode) { Log.v(TAG,"4.启动搜索对等设备 p2p搜索是否启动成功 : false"); //搜索启动 失败 } }); } } public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled){ mIsWifiP2pEnabled = isWifiP2pEnabled; } private void getPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { boolean location = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; boolean changeWifiState = checkSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE) == PackageManager.PERMISSION_GRANTED; boolean accessWifiState = checkSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED; boolean changeNetworkState = checkSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED; boolean internet = checkSelfPermission(android.Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED; boolean accessNetWorkState = checkSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED; boolean result = location && changeWifiState && accessWifiState && changeNetworkState && internet && accessNetWorkState; if (!result){ requestPermissions(new String[]{ android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.CHANGE_WIFI_STATE, android.Manifest.permission.ACCESS_WIFI_STATE, android.Manifest.permission.CHANGE_NETWORK_STATE, android.Manifest.permission.INTERNET, android.Manifest.permission.ACCESS_NETWORK_STATE, },233); } } } private void initListView() { mListView = findViewById(R.id.device_list); mWiFiPeerListAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_expandable_list_item_1, mDeviceNames ); mListView.setAdapter(mWiFiPeerListAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //6.点击,连接设备 Log.v(TAG,"6.点击,连接设备"); connect(position); } }); } @SuppressLint("MissingPermission") public void connect(int position) { // Picking the first device found on the network. WifiP2pDevice device = mPeers.get(position); WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; config.wps.setup = WpsInfo.PBC; mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver notifies us. Ignore for now. Log.v(TAG,"6.点击,连接设备 连接是否启动成功 : true"); } @Override public void onFailure(int reason) { Log.v(TAG,"6.点击,连接设备 连接是否启动成功 : false"); } }); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); //最后,一定要退群和取消连接 cancelConnect(); removeGroup(); } public void cancelConnect() { mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.v(TAG,"取消连接 成功"); } @Override public void onFailure(int reason) { Log.v(TAG,"取消连接 失败"); } }); } public void removeGroup() { mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.v(TAG,"移除组群 成功"); } @Override public void onFailure(int reason) { Log.v(TAG,"移除组群 失败"); } }); } @SuppressLint("MissingPermission") private void createP2PGroup() { setDeviceName("My_P2P_Group"); mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() { @Override public void onSuccess() { // Device is ready to accept incoming connections from peers. Log.v(TAG,"3.服务器创建 Group 创建是否成功 : true"); } @Override public void onFailure(int reason) { Log.v(TAG,"3.服务器创建 Group 创建是否成功 : false"); } }); } public void setDeviceName(String devName) { try { Class[] paramTypes = new Class[3]; paramTypes[0] = WifiP2pManager.Channel.class; paramTypes[1] = String.class; paramTypes[2] = WifiP2pManager.ActionListener.class; Method setDeviceName = mManager.getClass().getMethod( "setDeviceName",paramTypes); setDeviceName.setAccessible(true); Object arglist[] = new Object[3]; arglist[0] = mChannel; arglist[1] = devName; arglist[2] = new WifiP2pManager.ActionListener() { @Override public void onSuccess() { Log.v(TAG,"setDeviceName succeeded"); } @Override public void onFailure(int reason) { Log.v(TAG,"setDeviceName Failed" + reason); } }; setDeviceName.invoke(mManager,arglist); } catch (Exception e) { Log.v(TAG,e.getMessage()); e.printStackTrace(); } } private void createServerSocket() { new AsyncTask<Void,Void,Void>(){ @Override protected Void doInBackground(Void... voids) { try { //8.创建serverSocket Log.v(TAG,"8.创建serverSocket"); ServerSocket serverSocket = new ServerSocket(SERVER_PROt); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); String text = readText(is); //11.接收客户端数据 Log.v(TAG,"11.接收客户端数据 : " + text); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(); } private void createClientSocket(String groupOwnerAddress) { new AsyncTask<Void,Void,Void>(){ @Override protected Void doInBackground(Void... voids) { try { //9.创建ClientSocket Log.v(TAG,"9.创建ClientSocket"); Socket socket = new Socket(groupOwnerAddress,SERVER_PROt); OutputStream os = socket.getOutputStream(); PrintStream ps = new PrintStream(os); //10。连接后发送数据 Log.v(TAG,"10。连接后发送数据"); ps.println("!!!群主好!!!"); ps.flush(); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute(); } public static String readText(InputStream inputStream) throws IOException { if (inputStream == null) { return null; } byte[] bytes = new byte[inputStream.available()]; int length = inputStream.read(bytes); return new String(bytes, 0, length, Charset.defaultCharset()); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <Button android:id="@+id/create_p2p_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="create_p2p_group"/> <Button android:id="@+id/sacn_p2p_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="sacn_p2p_group"/> <ListView android:id="@+id/device_list" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver { private static String TAG = "P2P_Test WiFiDirectBroadcastReceiver"; private WifiP2pManager mManager; private WifiP2pManager.Channel mChannel; private MainActivity mActivity; private WifiP2pManager.PeerListListener mListener; private WifiP2pManager.ConnectionInfoListener mConnectionListener; public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, MainActivity activity, WifiP2pManager.PeerListListener listener, WifiP2pManager.ConnectionInfoListener connectionListener) { mManager = manager; mChannel = channel; mActivity = activity; mListener = listener; mConnectionListener = connectionListener; } @SuppressLint("MissingPermission") @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.v(TAG,"action --- > " + action); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // Determine if Wifi P2P mode is enabled or not, alert // the Activity. int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { mActivity.setIsWifiP2pEnabled(true); } else { mActivity.setIsWifiP2pEnabled(false); } } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { //5.获取搜索结果,并返回 Log.v(TAG,"5.获取搜索结果"); if (mManager != null) { mManager.requestPeers(mChannel, mListener); } } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { if (mManager == null) { return; } NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); if (networkInfo.isConnected()) { Log.v(TAG,"6.点击,连接设备 连接成功"); mManager.requestConnectionInfo(mChannel, mConnectionListener); }else { Log.v(TAG,"6.点击,连接设备 连接失败"); } } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。