broadcast
There are a lot of online tutorials, not responsible for framework development, but usually come into contact with it, so implement it yourself
dynamic broadcast,
Dynamically registered broadcasts are affected by the Activity declaration cycle, and if the Activity dies, the broadcast cannot be received
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;//过滤器
private ClickReceiver clickReceiver;
private Button button1;
private Button button2;
public static String action1 = "android.button.click1";
public static String action2 = "android.button.click2";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction(action1);
intentFilter.addAction(action2);
clickReceiver = new ClickReceiver();
registerReceiver(clickReceiver, intentFilter);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(action1);
sendBroadcast(intent);
}
});
button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(action2);
sendBroadcast(intent);
}
});
}
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(clickReceiver);
}
class ClickReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
if(intent.getAction().equals(action1))
Toast.makeText(context, "Receiver button1 finished",Toast.LENGTH_SHORT).show();
else if(intent.getAction().equals(action2))
Toast.makeText(context, "Receiver button2 finished",Toast.LENGTH_SHORT).show();
}
}
}
static broadcast
The difference between the two is in AndroidManifest.xml, which is not affected by the Activity life cycle. Even if the process is killed, the broadcast can still be received
AndroidManifest.xml
<receiver
android:name=".StaticReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.button.click1"/>
</intent-filter>
</receiver>
//发送前指定包名和类名
intent.setComponent(new ComponentName("com.example.javalearn",
"com.example.javalearn.StaticReceiver"));
public class StaticReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Receiver finished",Toast.LENGTH_SHORT).show();
}
}