Android wifi p2p同行可见性

时间:2015-06-23 19:05:20

标签: java android wifi-direct

我尝试使用wifi直接连接2台设备,让我们说设备A和设备B与android> 4.1。如果我在设备A上按下按钮以搜索其他设备,则它的行为始终不会相同。

例如,如果我按下设备A上的搜索按钮,它也无法找到任何内容,直到我按下设备B上的搜索按钮,即使应用程序同时进行。 因此,设备B在开始搜索其他设备之前不可见

其他时候,如果我搜索带有设备A的设备,它会找到设备B,即使应用程序最近在设备B上关闭,如果我尝试连接到设备B也可以。 问题是我只想在两台设备上运行时建立连接。

有时当设备A发现设备B并且它试图连接到设备B时,它在设备B开始寻找设备之前不起作用。 因此,当我开始在设备B上搜索时,它会收到来自A的连接请求,但在此之前没有任何内容。

其他时候,按下设备A上的搜索按钮后,会显示某些设备当时没有启用wifi或超出范围

这是我的代码:

MainActivity.java

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.GroupInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnItemClickListener, PeerListListener {

    private WifiP2pManager mManager;
    private Channel mChannel;
    private BroadcastReceiver mReceiver;
    private IntentFilter mIntentFilter;
    private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
    private List<WifiP2pDevice> peersConnect = new ArrayList<WifiP2pDevice>();
    private ArrayList<String> peersName = new ArrayList<String>();
    private ListView list;
    private Button bSearch;
    private Button bConnect;
    private Button bDisconnect;
    private int nSelectedDevices = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);

        try {
            Class<?> wifiManager = Class
                    .forName("android.net.wifi.p2p.WifiP2pManager");

            Method method = wifiManager
                    .getMethod(
                            "enableP2p",
                            new Class[] { android.net.wifi.p2p.WifiP2pManager.Channel.class });

            method.invoke(mManager, mChannel);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);

        bSearch = (Button) this.findViewById(R.id.searcher);
        bSearch.setOnClickListener(new OnClickListener() {
            public void onClick (View v) {
                list.setVisibility(ListView.INVISIBLE);
                bConnect.setVisibility(View.INVISIBLE);
                bDisconnect.setVisibility(View.INVISIBLE);
                nSelectedDevices = 0;
                peersConnect.clear();
                peers.clear();
                peersName.clear();
                searchDevices();        
            }
        });

        bConnect = (Button) this.findViewById(R.id.connecter);
        bConnect.setOnClickListener(new OnClickListener() {
            public void onClick (View v) {
                bDisconnect.setVisibility(View.VISIBLE);
                connectDevices();       
                bConnect.setVisibility(View.INVISIBLE);
                nSelectedDevices = 0;
                peersConnect.clear();
            }
        });

        bDisconnect = (Button) this.findViewById(R.id.disconnecter);
        bDisconnect.setOnClickListener(new OnClickListener() {
            public void onClick (View v) {
                disconnectDevices();
                peersConnect.clear();
                bDisconnect.setVisibility(View.INVISIBLE);
            }
        });

        list = (ListView) this.findViewById(R.id.list);
        list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
         //--   text filtering
        list.setTextFilterEnabled(true);


    }

    /* register the broadcast receiver with the intent values to be matched */
    @Override
    protected void onResume() {
        super.onResume();
        mReceiver = new WifiReceiver(mManager, mChannel, this);
        registerReceiver(mReceiver, mIntentFilter);
    }

    /* unregister the broadcast receiver */
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }



    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        CheckedTextView item = (CheckedTextView) v;
        if(item.isChecked()) {
            nSelectedDevices++;
            peersConnect.add(peers.get(position));
        }
        else {
            nSelectedDevices--;
            peersConnect.remove(peers.get(position));
        }
        if(nSelectedDevices == 1)
            bConnect.setVisibility(View.VISIBLE);
        else if(nSelectedDevices == 0)
            bConnect.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {

        // Out with the old, in with the new.
        peers.clear();
        peers.addAll(peerList.getDeviceList());
        getDeviceName();
        list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, peersName));
        list.setOnItemClickListener(this);
        list.setVisibility(ListView.VISIBLE);
        // If an AdapterView is backed by this data, notify it
        // of the change.  For instance, if you have a ListView of available
        // peers, trigger an update.
        //((ListAdapter) getListAdapter()).notifyDataSetChanged();
        if (peers.size() == 0) {
            return;
        }
    }

    private void searchDevices() {
        mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                //Toast.makeText(MainActivity.this, "Inizio ricerca...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reasonCode) {
                //Toast.makeText(MainActivity.this, "Ricerca fallita!", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void connectDevices() {
        for(int i = 0; i < peersConnect.size(); i++) {

            // Picking the first device found on the network.
            WifiP2pDevice device = peersConnect.get(i);

            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress = device.deviceAddress;
            config.wps.setup = WpsInfo.PBC;

            mManager.connect(mChannel, config, new ActionListener() {

                @Override
                public void onSuccess() {
                    // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
                    Toast.makeText(MainActivity.this, "Connection requested...", Toast.LENGTH_SHORT).show();
                }

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

    public void disconnectDevices() {
        if (mManager != null && mChannel != null) {
            mManager.requestGroupInfo(mChannel, new GroupInfoListener() {
                @Override
                public void onGroupInfoAvailable(WifiP2pGroup group) {
                    if (group != null && mManager != null && mChannel != null && group.isGroupOwner()) {
                        mManager.removeGroup(mChannel, new ActionListener() {
                            @Override
                            public void onSuccess() {

                            }

                            @Override
                            public void onFailure(int reason) {

                            }
                        });
                    }
                }
            });
        }
    }


    private void getDeviceName() {
        int i = 0;
        peersName.clear();
        while(i < peers.size()) {
            peersName.add(peers.get(i).deviceName);
            i++;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

WifiReceiver.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.widget.Toast;

public class WifiReceiver extends BroadcastReceiver {

    private WifiP2pManager mManager;
    private Channel mChannel;
    private MainActivity mActivity;

    public WifiReceiver(WifiP2pManager manager, Channel channel, MainActivity activity) {
        super();
        this.mManager = manager;
        this.mChannel = channel;
        this.mActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { // check if wifi is enabled/disabled
            System.out.println("Connection changed");
            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)) {
            // Call WifiP2pManager.requestPeers() to get a list of current peers
            // 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()
            System.out.println("Peers changed");
            if (mManager != null) {
                mManager.requestPeers(mChannel, mActivity);

            }
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
            // Respond to new connection or disconnections
            System.out.println("Connection changed");
        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
            // Respond to this device's wifi state changing
            System.out.println("This device changed");
        }
        else if (WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION.equals(action)) {
            // Respond to this device's wifi state changing
            System.out.println("Search peers");
        }
    }

}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:id="@+id/linearlayout1" >
        <Button
            android:id="@+id/searcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_send" />

        <Button
            android:id="@+id/connecter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_connect"
            android:visibility="invisible" />

        <Button
            android:id="@+id/disconnecter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_disconnect"
            android:visibility="invisible" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearlayout1" >

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="380dp"
            android:layout_alignParentLeft="true"
            android:visibility="invisible" >
        </ListView>
    </LinearLayout>
"

</RelativeLayout>

我不明白工作方式mManager.discoverPeers()mManager.requestPeers()

感谢您的关注!!

2 个答案:

答案 0 :(得分:4)

实际上你有有效的观察结果,这就是API实际运作的方式:

  1. 因此,设备B在未开始搜索之前不可见 其他设备
  2. 这就是API的工作方式。基本上为了能够被其他设备看到,WiFi接口需要上电和激活,到目前为止,我已经看到它正在发生,当设备正在进行主动发现或具有活动连接时。

    1. 问题是我要建立一个 仅当应用程序在两个设备上运行时才建立连接
    2. 基本上,我认为你可以做的最好是在应用程序运行时宣传服务,并在连接时发现服务。这不仅仅是100%准确,因此,您也可以实现连接&amp;从客户端到组所有者的握手,以完全检查两端是否正常并且存在。如果握手失败,则断开连接。

      1. 因此,当我开始在设备B上搜索时,它会收到连接请求 来自A,但直到那时都没有。
      2. 这个我没有直接答案,基本上可能是某些东西不对。我知道如果设备B不活动它不应该是可见的,并且如果设备B不在API的实际发现对等列表中,那么对它的所有连接尝试都将失败,因此可能是某些问题的组合是什么真的发生在这里。

        1. 它显示了一些当时没有启用wifi或超出范围的设备。
        2. 假设API似乎确实缓存了一些结果,但是不得不承认我没有看到这个问题,我通常会在关闭附近的设备时获得对等更改事件,然后服务发现没有给出任何设备上的任何结果都不会真正存在,所以在获得Peers Changed事件后,请务必尝试服务发现。

答案 1 :(得分:0)

我有类似的问题。 我的某些设备找不到其他任何设备,但其他设备可能已与它们连接。

问题是我没有请求位置许可。

Manifest.permission.ACCESS_COARSE_LOCATION;