javaandroidnetwork-service

NsdManager can't be found using context.getSystemService


I'm having an issue with using context.getSystemService(Context.NSD_SERVICE). It just crashes. The code is below:

My network service discovery helper:

public NetworkServiceDiscoveryHelper(Context context)
{
    mContext = context;
    mNetworkDiscoveryManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}

My Activity Class:

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


    mNsdHelper = new NetworkServiceDiscoveryHelper(this);
    mNsdHelper.initializeNsd();


}

I've been following sample code from http://developer.android.com/training/connect-devices-wirelessly/nsd.html, their activity constructor is slightly different:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mStatusView = (TextView) findViewById(R.id.status);

    mUpdateHandler = new Handler() {
            @Override
        public void handleMessage(Message msg) {
            String chatLine = msg.getData().getString("msg");
            addChatLine(chatLine);
        }
    };

    mConnection = new ChatConnection(mUpdateHandler);

    mNsdHelper = new NsdHelper(this);
    mNsdHelper.initializeNsd();

}

Can somebody explain to me, why my implementation is not working, do I need extra functionality? I'm basically was just trying to set test this functionality by creating a service and then using the same phone to find that service again. I've only implemented a network service helper and the activity so far. Do I need to set up any additional functionality.


Solution

  • In order to use Wi-Fi Direct, add the CHANGE_WIFI_STATE, ACCESS_WIFI_STATE, and INTERNET permissions to your manifest.

    <uses-permission
            android:required="true"
            android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission
            android:required="true"
            android:name="android.permission.CHANGE_WIFI_STATE"/>
        <uses-permission
            android:required="true"
            android:name="android.permission.INTERNET"/>