If you are facing any issue in playing video please use Firefox browser.
Now we will see that how we can practically use Broadcast Receiver in Android with Example.
For that, we will first create a new project named 'BroadcastReceiver'. And then we'll open its manifest file 'AndroidManifest.xml'.
We are using Broadcast receiver to check the network state, so for that we are using two permissions,
<uses-permission android:name=""android permission.INTERNET""/>
<uses-permission android:name=""android permission.ACCESS_NETWORK_STATE""/>
Now we will need to create a Receiver inside an application,
<action android:name=""android.net.conn.CONNECTIVITY_CHANGE"" />
Now we will see 'activity_main.xml' file in our 'layout' folder. Here we have taken a Relative layout and a Button of text 'Send Broadcast'.
Now we will see how we can design the main activity, for that we will open the 'java' folder, in which we will create a public class ConnectionReceiver,
public class ConnectionReceiver extends BroadcastReceiver
public void onReceive(Context context, Intent intent)
Toast.makeText(context,""SOME_ACTION is received"", Toast.LENGTH_LONG).show();
Intent filter basically specifies that what should be received if we give a particular element.
After that, we'll use the 'else' statement and inside it, we will use 'ConnectivityManager' and also 'getSystemService',
ConnectivityManager cn=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Now on Condition basis we will check that, if network is received then what should be done and if network is not received then what should be the action taken,
boolean isConnected=activeNetwork !=null &&
Toast.makeText(context,""Network is connected"", Toast.LENGTH_LONG).show();
Toast.makeText(context,""Network is changed or reconnected"", Toast.LENGTH_LONG).show();
Now we'll design our 'MainActivity.java',
public class MainActivity extends AppCompatActivity
Now in our activity we will use onResume(),
protected void onResume()
After that inner activity, we will use onDestroy(),
protected void onDestroy()
Now we’ll use someMethod(),
Intent intent=new Intent(""com.example.SOME_ACTION"");
Now after everything when we will go to our phone's setting when we will connect our cellular data to a network, a notification 'Network is Connected' will appear. And when we will switch off our phone's cellular data ‘Network is changed or reconnected’ notification will appear.
Have a friend to whom you would want to share this course?