Android Wi-Fi P2P:在ListView中显示对等体

时间:2016-04-27 07:42:47

标签: android wifi p2p wifi-direct wifip2p

我正在尝试使用Google API连接2台设备和Wi-Fi Direct。我想在ListView中看到设备列表,但它失败了。我的代码出了什么问题?

MainActivity

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.IntentFilter;
    import android.net.wifi.p2p.WifiP2pDevice;
    import android.net.wifi.p2p.WifiP2pDeviceList;
    import android.os.Build;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.net.wifi.p2p.WifiP2pManager;
    import android.net.wifi.p2p.WifiP2pManager.Channel;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

public TextView search_result;

private WifiP2pManager manager;
public static final String TAG = "wifidirectdemo";

private final IntentFilter intentFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
public String test;
private ArrayAdapter<String> WifiP2parrayAdpter;
private Button seachBt;
private ListView mListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    search_result = (TextView)findViewById(R.id.result_search);
    mListView = (ListView) findViewById(R.id.listView);

    WifiP2parrayAdpter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item);
    mListView.setAdapter(WifiP2parrayAdpter);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

    receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        channel = manager.initialize(this, getMainLooper(), null);
    }

    seachBt = (Button) findViewById(R.id.go_bt);
    seachBt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            search(v);

        }
    });

}

public void search (View view) {

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {



            @Override
            public void onSuccess() {

                search_result.setText("מחפש.......");



            }

            @Override
            public void onFailure(int reason) {

                search_result.setText("ארעה שגיאה. נסה שוב");

            }
        });
    }


}



/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(receiver, intentFilter);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

public void dysplayPeers (WifiP2pDeviceList peerList) {


    WifiP2parrayAdpter.clear();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        for (WifiP2pDevice peer : peerList.getDeviceList()) {


            WifiP2parrayAdpter.add(peer.deviceName + "\n" + peer.deviceAddress);

            search_result.setText(peer.deviceName);


        }
    }


}

}

WiFiDirectBroadcastReceiver

import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.net.NetworkInfo;
    import android.net.wifi.p2p.WifiP2pConfig;
    import android.net.wifi.p2p.WifiP2pDevice;
    import android.net.wifi.p2p.WifiP2pDeviceList;
    import android.net.wifi.p2p.WifiP2pManager;
    import android.net.wifi.p2p.WifiP2pManager.Channel;
    import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
    import android.os.Build;
    import android.util.Log;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.List;


     public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {


    private WifiP2pManager manager;
    private Channel channel;
    private MainActivity activity;
    private List<WifiP2pDevice> mPeers;
    private List<WifiP2pConfig> mConfigs;

    /**
     * @param manager WifiP2pManager system service
     * @param channel Wifi p2p channel
     * @param activity activity associated with the receiver
     */
    public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
                                       MainActivity activity) {
        super();
        this.manager = manager;
        this.channel = channel;
        this.activity = activity;
    }

    /*
     * (non-Javadoc)
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
     * android.content.Intent)
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        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

            } else {


            }

        } 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) {

                Toast.makeText(activity, "this is my Toast message!!! =)",
                        Toast.LENGTH_LONG).show();

                mPeers = new ArrayList<WifiP2pDevice>();
                mConfigs = new ArrayList<WifiP2pConfig>();

                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        final PeerListListener peerListListener = new PeerListListener() {


                            @Override
                            public void onPeersAvailable(WifiP2pDeviceList peerList) {


                                mPeers.clear();
                                activity.dysplayPeers(peerList);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                    mPeers.addAll(peerList.getDeviceList());
                                }


                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                    for (int i = 0; i < peerList.getDeviceList().size(); i++) {

                                        WifiP2pConfig config = null;
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                            config = new WifiP2pConfig();
                                        }
                                        config.deviceAddress = mPeers.get(i).deviceAddress;
                                        mConfigs.add(config);



                                    }
                                }

                            }
                        };
                    }



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




        }



            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

            } else {
                // It's a disconnect

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


        }
    }
}

活动主要

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.news.kikar.wifiapp.MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="SEARCH"
    android:id="@+id/textView"
    android:layout_marginTop="44dp"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="GO!"
    android:id="@+id/go_bt"
    android:layout_below="@+id/textView"
    android:layout_alignRight="@+id/textView"
    android:layout_alignEnd="@+id/textView" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="        "
    android:id="@+id/result_search"
    android:layout_marginTop="42dp"
    android:layout_below="@+id/go_bt"
    android:layout_centerHorizontal="true" />

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

1 个答案:

答案 0 :(得分:0)

至少你缺少对WifiP2pManager :: requestPeers()的调用,因此没有人知道调用peerListListener。

我还会考虑将peerListListener作为teh类的成员变量。

可以在under my Github repos

找到能够很好地找到同伴的示例实现