Android BroadcastReceiver Example
BroadcastReceiver is one of the building blocks in Android. You can sendBroadcast with an action in an Intent and the Receiver can receive this action and do something about it. Here is an example of sending some custom intents and a receiver will receive them and act accordingly.
The keys here in the following example are:
"com.example.simplebroadcastreceiver.CUSTOM_INTENT1" "com.example.simplebroadcastreceiver.CUSTOM_INTENT2"
1st, create a receiver class SimpleReceiver.java to receive intents.
public class SimpleReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() == "com.example.simplebroadcastreceiver.CUSTOM_INTENT1") { Toast.makeText(context, "Intent 1 Detected.", Toast.LENGTH_SHORT).show(); } else if (intent.getAction() == "com.example.simplebroadcastreceiver.CUSTOM_INTENT2") { Toast.makeText(context, "Intent 2 Detected.", Toast.LENGTH_SHORT).show(); } } }
2nd, register the above receiver class inside the application tag of the manifest file.
3rd, create an Activity class to send the broadcast intents. When one of the button is clicked, it sends a broadcast with an action in an Intent, and that intent will be received in the onReceive method in the SimpleReceiver class.
public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // broadcast a custom intent. public void broadcastIntent1(View view) { Intent intent = new Intent(this, SimpleReceiver.class); intent.setAction("com.example.simplebroadcastreceiver.CUSTOM_INTENT1"); sendBroadcast(intent); } // broadcast a custom intent. public void broadcastIntent2(View view) { Intent intent = new Intent(this, SimpleReceiver.class); intent.setAction("com.example.simplebroadcastreceiver.CUSTOM_INTENT2"); sendBroadcast(intent); } }
The layout for the activity class
Search within Codexpedia
Search the entire web