Android WI-Fi直连实现
生活随笔
收集整理的這篇文章主要介紹了
Android WI-Fi直连实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
P2P Demo
整個的調用流程已經用編號在代碼中編寫好,跟隨代碼即可理順邏輯
參考至官方文檔
鏈接: WI-FI直連
MainActivity
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() {@Overridepublic 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() {@Overridepublic 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);}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initListView();//1.申請權限Log.v(TAG,"1.申請權限");getPermission();//2.初始化 P2p Manager 和 ChannelLog.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() {@Overridepublic void onClick(View v) {// 3.服務器創建 GroupLog.v(TAG,"3.服務器創建 Group");createP2PGroup();}});findViewById(R.id.sacn_p2p_group).setOnClickListener(new View.OnClickListener() {@Overridepublic 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() {@Overridepublic void onSuccess() {Log.v(TAG,"4.啟動搜索對等設備 p2p搜索是否啟動成功 : true");//搜索啟動 成功}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onSuccess() {// WiFiDirectBroadcastReceiver notifies us. Ignore for now.Log.v(TAG,"6.點擊,連接設備 連接是否啟動成功 : true");}@Overridepublic void onFailure(int reason) {Log.v(TAG,"6.點擊,連接設備 連接是否啟動成功 : false");}});}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(mReceiver);//最后,一定要退群和取消連接cancelConnect();removeGroup();}public void cancelConnect() {mManager.cancelConnect(mChannel, new WifiP2pManager.ActionListener() {@Overridepublic void onSuccess() {Log.v(TAG,"取消連接 成功");}@Overridepublic void onFailure(int reason) {Log.v(TAG,"取消連接 失敗");}});}public void removeGroup() {mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() {@Overridepublic void onSuccess() {Log.v(TAG,"移除組群 成功");}@Overridepublic void onFailure(int reason) {Log.v(TAG,"移除組群 失敗");}});}@SuppressLint("MissingPermission")private void createP2PGroup() {setDeviceName("My_P2P_Group");mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() {@Overridepublic void onSuccess() {// Device is ready to accept incoming connections from peers.Log.v(TAG,"3.服務器創建 Group 創建是否成功 : true");}@Overridepublic 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() {@Overridepublic void onSuccess() {Log.v(TAG,"setDeviceName succeeded");}@Overridepublic 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>(){@Overrideprotected Void doInBackground(Void... voids) {try {//8.創建serverSocketLog.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>(){@Overrideprotected Void doInBackground(Void... voids) {try {//9.創建ClientSocketLog.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());} }activity_main 布局
<?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"><Buttonandroid:id="@+id/create_p2p_group"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="create_p2p_group"/><Buttonandroid:id="@+id/sacn_p2p_group"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="sacn_p2p_group"/><ListViewandroid:id="@+id/device_list"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout>WiFiDirectBroadcastReceiver
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")@Overridepublic 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)) {}} }總結
以上是生活随笔為你收集整理的Android WI-Fi直连实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nextcloud php 部署,Cen
- 下一篇: java 下载限速_Java 文件下载限