Home » Java » java – From where value of intent is coming on which I am calling getAction() function? (This is overridden method of BroadcastReceiver class)-Exceptionshub

java – From where value of intent is coming on which I am calling getAction() function? (This is overridden method of BroadcastReceiver class)-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created a broadcast receiver class Which is working fine. I am confused about from where the value of intent comes in onReceive method.

 @Override
    public void onReceive(Context context, Intent intent) {

       String action = intent.getAction();

       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){
               Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
           }
           else 
           {
               Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
           }
        }
}

Main Activity code where I have made an Intent Filter, where I have added an action.

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

        wifiP2pManager =  (WifiP2pManager) 

getSystemService(Context.WIFI_P2P_SERVICE);
    channel = wifiP2pManager.initialize(this,getMainLooper(),null);

        broadcastReceiver = new WiFiDirectBroadcastReceiver(wifiP2pManager, channel, this);

      intentFilter =  new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);



        }
How to&Answers:

If your BroadcastReceiver works, then you must have initialized wifiP2pManager and called a function on the object. When tbe state changes an intent is being broadcasted. With the receiver you subscribe to those intents.

You can read in more detail about the WifiP2pManager in the Android documentation Wi-Fi Direct (peer-to-peer or P2P) overview