WiFi P2P添加本地服务失败

时间:2014-05-26 00:55:59

标签: android wifi p2p

我正在尝试使用WiFi P2P和网络服务发现在Android上开发基本服务器应用程序。 不幸的是,我坚持了,因为我仍然无法将本地服务添加到我的wifi p2p管理器。每次我要运行app onFailure方法执行。找不到原因。

import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;

public class ServerMainActivity extends Activity
{
    private IntentFilter mIntentFilter;
    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private ServerBroadcastReceiver mReceiver;


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

        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);

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

        mChannel = mManager.initialize(this, getMainLooper(), null);

        mReceiver = new ServerBroadcastReceiver(mManager, mChannel, this);

        startRegistration();
    }

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

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.server_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void startRegistration() {

        mManager.clearLocalServices(mChannel, new ActionListener() {

            @Override
            public void onFailure(int arg0) {

                Log.d("Server Main Activity", "cannot clear local services " + arg0);
            }

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                Log.d("Server Main Activity", "local services cleared.");
                //  Create a string map containing information about your service.
                Map<String,String> record = new HashMap<String,String>();
                record.put("listenport", "0");
                record.put("buddyname", "John Doe" + (int) (Math.random() * 1000));
                record.put("available", "visible");

                // Service information.  Pass it an instance name, service type
                // _protocol._transportlayer , and the map containing
                // information other devices will want once they connect to this one.
                WifiP2pDnsSdServiceInfo serviceInfo =
                        WifiP2pDnsSdServiceInfo.newInstance("_SynchroMusic", "_tcp", record);

                // Add the local service, sending the service info, network channel,
                // and listener that will be used to indicate success or failure of
                // the request.
                mManager.addLocalService(mChannel, serviceInfo, new ActionListener() {
                    @Override
                    public void onSuccess() {
                        // Command successful! Code isn't necessarily needed here,
                        // Unless you want to update the UI or add logging statements.
                        Log.d("Server Main Activity", "local servica added.");
                    }

                    @Override
                    public void onFailure(int arg0) {
                        // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                        Log.d("Server Main Activity", "faliture" + arg0);
                    }
                });
            }
        });

    }
}

这些代码大部分是基于官方的android开发人员教程,所以我想它应该可行。在HTC One X上运行cyanogenmod 11(Android 4.4.2)。

如果需要,这是我的BroadcastReceiver类:

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.util.Log;

public class ServerBroadcastReceiver extends BroadcastReceiver {
    public ServerBroadcastReceiver() {
    }

    private WifiP2pManager mManager;
    private WifiP2pManager.Channel mChannel;
    private ServerMainActivity mActivity;

    public ServerBroadcastReceiver(WifiP2pManager manager, Channel channel,
            ServerMainActivity 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)) {
            // Determine if Wifi P2P mode is enabled or not, alert
            // the Activity.
            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                //activity.setIsWifiP2pEnabled(true);
                Log.d("ServerBroadcast", "Wifi on");
            } else {
                //activity.setIsWifiP2pEnabled(false);
                Log.d("ServerBroadcast", "Wifi off");
            }
        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

            // The peer list has changed!  We should probably do something about
            // that.
            Log.d("ServerBroadcast", "peers Changed action");
        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

            // Connection state changed!  We should probably do something about
            // that.
            Log.d("ServerBroadcast", "Con Changed");

        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
           // DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
            //        .findFragmentById(R.id.frag_list);
            //fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
              ///      WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
            Log.d("ServerBroadcast", "Dev Changed");
        }

        //throw new UnsupportedOperationException("Not yet implemented " + action);
        else throw new UnsupportedOperationException("Not yet implemented " + action);
    }
}

<击> 当行

//throw new UnsupportedOperationException("Not yet implemented " + action);

未注释它会抛出错误

Not yet implementedandroid.net.wifi.p2p.STATE_CHANGED

1 个答案:

答案 0 :(得分:0)

您必须等待WIFI_P2P_STATE_ENABLED,然后注册您的服务。