跨多个活动使用Android WifiP2P

时间:2014-09-15 19:35:37

标签: java android android-wifi wifi-direct wifip2p

我在Android应用程序中使用Android Wifi P2P技术在多个设备之间发送简单的数据传输。我正在阅读开发人员指南Wifi p2p,但实现似乎只是为一个活动构建使用Wifi直接服务。

按照指南,我创建了这个BroadcastReceiver类来监听Wifi Direct事件:

import android.app.Activity;
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;

public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
    private WifiP2pManager manager;
    private Channel channel;
    private WifiActivity activity;

    public WifiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel, WifiActivity activity){
        this.manager = manager;
        this.channel = channel;
        this.activity = activity;
    }

    @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
        }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
        }
    }
}

但是,构造函数似乎只适用于一个活动。我是否必须为使用Wifi Direct的每项活动制作接收器?如何在不必每次都建立连接的情况下将连接传递给不同的活动(即查找对等体,连接到对等体等)?

1 个答案:

答案 0 :(得分:3)

虽然答案太晚了,但由于没有人回答,我想提供解决方案。

您需要使用多个活动注册广播接收器,并使用以下代码更改构造函数

public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,Context activity) {
        super();
        this.manager = manager;
        this.channel = channel;
        this.activity = activity;
    }

无论您需要根据活动更改代码,只需选中此

即可
if(activity instanceof yourActivityName){
// your code based on the current activity
}

使用此

在您的活动中注册您的广播记录
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
        registerReceiver(receiver, intentFilter);

希望这有帮助