Как подключиться с помощью Wi-Fi Direct для передачи файла?

Я хочу создать приложение, используя Wi-Fi Direct для передачи файлов, и я использую NFC, чтобы сократить время сопряжения. Я уже следовал инструкциям в http://developer.android.com/guide/topics/connectivity/wifip2p.html и http://developer.android.com/training/connect-devices-wirelessly/wifi-direct.html но мои приложения не будут подключаться. и я взял код из прямой демонстрации Wi-Fi из примера Android.

Когда я прослеживаю проблему, когда приемник прямого вещания Wi-Fi WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION информация о сети не будет связываться с другим устройством, поэтому в моем основном классе, который реализует ConnectionInfoListener у которых есть метод onConnectionInfoAvailable это никогда не срабатывает.

Может кто-нибудь мне помочь? спасибо, прежде чем

код такой

Приемник Wifi Direct BroadCast

   public void onReceive(Context arg0, Intent intent) {

    // TODO Auto-generated method stub
    String action = intent.getAction();
    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // UI update to indicate wifi p2p status.
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            // Wifi Direct mode is enabled
            activity.setIsWifiP2pEnabled(true);
        } else {
            activity.setIsWifiP2pEnabled(false);
            //activity.resetData();
        }
        //Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        // request available peers from the wifi p2p manager. This is an
        // asynchronous call and the calling activity is notified with a
        // callback on PeerListListener.onPeersAvailable()
        if (manager != null) {

        }
        //Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

        if (manager == null) {
            return;
        }

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

        if (networkInfo.isConnected()) {
            // we are connected with the other device, request connection
            // info to find group owner IP

            manager.requestConnectionInfo(channel, activity);

        } else {
            // It's a disconnect

        }
    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {

            WifiP2pDevice device = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
            activity.myname = device.deviceName + " " + device.deviceAddress + " " + device.primaryDeviceType + " " + device.secondaryDeviceType + " " + device.status;
    }
}`

мой основной класс

`

    // how to connect
    WifiP2pConfig config = new WifiP2pConfig();
    config.deviceAddress = names[1];
    config.wps.setup = WpsInfo.PBC;
    config.groupOwnerIntent = 15;
    connect(config);

    public void connect(WifiP2pConfig config) {

    manager.connect(channel, config, new ActionListener() {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.

        }

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

    public void disconnect() {
    manager.removeGroup(channel, new ActionListener() {

        @Override
        public void onFailure(int reasonCode) {
            //Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
            Toast.makeText(getApplicationContext(), "Disconnect failed. Reason :" + reasonCode, Toast.LENGTH_SHORT).show();
        }

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

    });
}


    public void onChannelDisconnected() {
    // we will try once more
    if (manager != null && !retryChannel) {
        Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
        //resetData();
        retryChannel = true;
        manager.initialize(this, getMainLooper(), this);
    } else {
        Toast.makeText(this,
                "Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
                Toast.LENGTH_LONG).show();
    }
}


  public void onConnectionInfoAvailable(WifiP2pInfo info) {
    // TODO Auto-generated method stub
    this.info = info;

    // After the group negotiation, we can determine the group owner.
    if (info.groupFormed && info.isGroupOwner) {
        // Do whatever tasks are specific to the group owner.
        // One common case is creating a server thread and accepting
        // incoming connections.
        Toast.makeText(getApplicationContext(), "Owner", Toast.LENGTH_SHORT).show();
    } else if (info.groupFormed) {
        // The other device acts as the client. In this case,
        // you'll want to create a client thread that connects to the group
        // owner.
        Toast.makeText(getApplicationContext(), "Client", Toast.LENGTH_SHORT).show();
    }
}

`

onConnectionInfoAvailable никогда не будет выполняться, потому что networkInfo.isConnected() никогда не выполняется.

Пожалуйста, помогите мне.. Thx..

0 ответов

Другие вопросы по тегам