如何制作自己的设备客户端或发送者

时间:2019-09-07 15:00:18

标签: android wifip2p

我正在开发一个共享应用程序,其中我使用wifip2p框架连接两个设备,一个是发送方,另一个是接收方。我面临的问题是,谁将成为发送者,谁将成为接收者被自动选择。

我正在使用以下代码连接到设备。

/**
 * @param device to connect
 */
@Override
public void connect(WifiP2pDevice device) {
    WifiP2pConfig config = new WifiP2pConfig();
    config.groupOwnerIntent = 0;
    config.deviceAddress = device.deviceAddress;
    config.wps.setup = WpsInfo.PBC;
    manager.connect(channel, config, new WifiP2pManager.ActionListener() {

        @Override
        public void onSuccess() {
            Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(getApplicationContext(), "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
}

并删除我在下面的代码中使用的先前创建的组。

/**
 *  @deletePersistentGroups delete all created groups
 */

private void deletePersistentGroups(){
    try {
        Method[] methods = WifiP2pManager.class.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals("deletePersistentGroup")) {
                // Delete any persistent group
                for (int netid = 0; netid < 32; netid++) {
                    methods[i].invoke(manager, channel, netid, null);
                }
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

此onConnectionInfoAvailable函数在两个设备都成功连接并且我面临问题时触发,即如果我单击设备1上的connect按钮,有时它充当发送者或接收者,我想实现的目标是该设备1必须始终是发送方和其他设备接收方


  /**
     * @param wifiP2pInfo connection information after device connected to desire device
     */
    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        if (wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner ) {
            Toast.makeText(getApplicationContext(), "Owner", Toast.LENGTH_LONG).show();
            new FileServerAsyncTask(this).execute();
        }
        else if (wifiP2pInfo.groupFormed){
            Toast.makeText(getApplicationContext(), "Client", Toast.LENGTH_LONG).show();
            Intent serviceIntent = new Intent(getApplicationContext(), FileTransferService.class);
            serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
            serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, path);
            serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, wifiP2pInfo.groupOwnerAddress.getHostAddress());
            serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
            startService(serviceIntent);
        }
    }

0 个答案:

没有答案