Broadcast Receivers: 101

An Overview of Broadcast Receivers.

Photo by Ajai Arif on Unsplash

Implicit and Statically Registered Broadcast Receivers

<receiver android:name="MyFirstBroadcastReceiver">
<
intent-filter>
<
action android:name="android.intent.action.BOOT_COMPLETED"/>
<
action android:name="android.intent.action.LOCALE_CHANGED"/>
</
intent-filter>

</
receiver>
public class MyFirstBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Toast.makeText(context, "Phone has booted successfully", Toast.LENGTH_SHORT).show();
} else if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
Toast.makeText(context,"Language is changed", Toast.LENGTH_SHORT).show();
}
}
}

Implicit Broadcast Exceptions — An Interview Question

Dynamically Registered Broadcast Receivers

public class MainActivity extends AppCompatActivity {

MyFirstBroadcastReceiver myFirstBroadcastReceiver = new MyFirstBroadcastReceiver();

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

@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_POWER_CONNECTED);
registerReceiver(myFirstBroadcastReceiver,intentFilter);
}

@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myFirstBroadcastReceiver);
}
}

Explicit Broadcast Receiver

<receiver android:name="ExplicitBroadcastReceiver" 
android:exported="true"/>

A Software Engineer and gamer at heart.