how to solve discovering other device via Wi-Fi (android API)?

喜夏-厌秋 提交于 2019-12-28 04:34:05

问题


recently I follow the steps given from Developer.Android.Com

But it seems i have a few luck over there. I tried to discover the available peers nearby, put 'em into the arraylist but seems no luck. I didnt get anything.

My Actual 2 Devices are actually android 4.1 and 4.2 Since Wifi Direct is based on API Level 14 which is android 4.0+ so i think my real device is not the problem.

The concept I use is using 1 activity and 1 BroadCast Receiver.

Please take a look at my code, did I put it wrongly or something I forgot?

Chat1Activity.java

package com.example.androtut;

import java.util.ArrayList;

import others.MyBroadcastReceiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;

import android.content.IntentFilter;
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.Bundle;
import android.view.View;

import android.widget.Button;

import android.widget.Toast;

public class Chat1Activity extends Activity {

    private final IntentFilter mintentFilter = new IntentFilter();
    private Channel mChannel;
    private WifiP2pManager mManager;
    private BroadcastReceiver mReceiver;
    private ArrayList peers = new ArrayList();
    private PeerListListener myPeerListListener = new PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {

            // Out with the old, in with the new.
            peers.clear();
            peers.addAll(peerList.getDeviceList());

            // 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.

            if (peers.size() == 0) {
                Toast.makeText(getApplicationContext(),"Nothing found!", Toast.LENGTH_LONG).show();
                return;
            } else {
                Toast.makeText(getApplicationContext(),"We've found " + peers.size() + " users", Toast.LENGTH_LONG).show();
            }


        }
    };


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

        //Toast.makeText(getApplicationContext(), "Wifi is okay", Toast.LENGTH_LONG).show();    

        prepareIntentFilter();

        Button btn_startchat = (Button) findViewById(R.id.btn_startchat);

        // Listening to News Feed button click
        btn_startchat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // Launching News Feed Screen
                detectPeers();
            }
        });

        mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);
    }


    private void detectPeers(){

        mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess() {
                // Code for when the discovery initiation is successful goes here.
                // No services have actually been discovered yet, so this method
                // can often be left blank.  Code for peer discovery goes in the
                // onReceive method, detailed below.
            }

            @Override
            public void onFailure(int reasonCode) {
                // Code for when the discovery initiation fails goes here.
                // Alert the user that something went wrong.
            }
    });




    }


    @Override
    protected void onResume() {
        super.onResume();
        mReceiver = new MyBroadcastReceiver(mManager, mChannel, this, myPeerListListener);
        registerReceiver(mReceiver, mintentFilter);
    }
    /* unregister the broadcast receiver */
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    private void prepareIntentFilter() {

        mintentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        // Indicates a change in the list of available peers.
        mintentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        // Indicates the state of Wi-Fi P2P connectivity has changed.
        mintentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        // Indicates this device's details have changed.
        mintentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    }


}

And the MyBroadcastReceiver.java

package others;

import java.util.ArrayList;

import com.example.androtut.Chat1Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
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.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {

    private WifiP2pManager mManager;
    private Channel mChannel;
    private Chat1Activity mActivity;
    private PeerListListener myPeerListListener;



    public MyBroadcastReceiver(WifiP2pManager manager, Channel channel,
            Chat1Activity activity, PeerListListener obPeerList) {
        super();
        this.mManager = manager;
        this.mChannel = channel;
        this.mActivity = activity;
        this.myPeerListListener = obPeerList;
    }

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

        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
            // Check to see if Wi-Fi is enabled and notify appropriate activity
        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
            // Call WifiP2pManager.requestPeers() to get a list of current peers

            if (mManager != null) {
                mManager.requestPeers(mChannel, myPeerListListener);
            }



        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION
                .equals(action)) {
            // Respond to new connection or disconnections
        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION
                .equals(action)) {
            // Respond to this device's wifi state changing



        }

        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                // Wifi P2P is enabled
                Toast.makeText(mActivity.getApplicationContext(),"Wifi is okay", Toast.LENGTH_LONG).show();

            } else {
                // Wi-Fi P2P is not enabled
                Toast.makeText(mActivity.getApplicationContext(),
                        "Wifi is not okay", Toast.LENGTH_LONG).show();
            }
        }

    }

}

回答1:


I guess you did't add PeerListListener to your activity. so it won't reply.

you can try to implement PeerListListener in your activity

public class Chat1Activity extends Activity implements WifiP2pManager.PeerListListener

and override onPeerAvailable method in your activity

 @Override
  public void onPeersAvailable(WifiP2pDeviceList peers) {

   //put your code here

  }

and change requestPeers method in your Receiver

 if (mManager != null) {
            mManager.requestPeers(mChannel, mActivity);
 }

Hope this help!!




回答2:


Have you check whether your device support Wifi Direct? Having a rom > 4.0 does not means it has wifi direct hardware support. Try to check that with PackageManager's API: http://developer.android.com/reference/android/content/pm/PackageManager.html#hasSystemFeature(java.lang.String)



来源:https://stackoverflow.com/questions/24357892/how-to-solve-discovering-other-device-via-wi-fi-android-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!