当前位置:   article > 正文

Android WI-Fi直连实现_android wifi直连

android wifi直连

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() {
        @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());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
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">

    <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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
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")
    @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)) {


        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/295440
推荐阅读
相关标签
  

闽ICP备14008679号