hamedata
hamedata

Reputation: 125

discoverpeers in simple android wifip2pmanager code

i going to start a project in android via wifip2pmanager. it seem the channel successfully created ("initialize"). but for next step my code do not work("discoverPeers or creategroup"). is any problem in below code?

public class MainActivity extends Activity {
        WifiP2pManager wifiMgr;
        Channel channel;

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

        wifiMgr = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
        channel = wifiMgr.initialize(this,getMainLooper(),null);
        wifiMgr.discoverPeers(channel, new ActionListener(){

            @Override
            public void onFailure(int arg0) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "discover fail."+arg0, 
                          Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "discover succ.", 
                          Toast.LENGTH_SHORT).show();
            }

        }); 
    }


}

Upvotes: 0

Views: 1036

Answers (1)

Oleg Kleiman
Oleg Kleiman

Reputation: 31

Google documentation states that "Registering an application handler with initialize(Context, Looper, WifiP2pManager.ChannelListener) requires the permissions ACCESS_WIFI_STATE and CHANGE_WIFI_STATE to perform any further peer-to-peer operations." So you should add these permissions to manifest.xml. The next step in your code then should be handling the various WIFI_P2P_STATE_XXX actions received by the broadcast receiver which you'll supply and register ( usually inside onResume() )

Upvotes: 1

Related Questions