to address the security of the broadcast simply, Android introduced a set of local broadcast mechanisms that broadcast broadcasts only from within the program, and only from broadcasts from the application. Otherwise, when we send some broadcasts that carry critical data, some malicious programs may also send a variety of spam broadcasts to our broadcast receivers.
Use the following: (mainly using Localbroadcastmanager to manage the broadcast and to provide methods for registering broadcasts and sending broadcasts).
PackageCom.example.xch.localbroadcast;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.support.v4.content.LocalBroadcastManager;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public classMainactivityextendsappcompatactivity {PrivateIntentfilter Intentfilter; PrivateButton Sendbroadcast; PrivateLocalreceiver Localreceiver; PrivateLocalbroadcastmanager Localbroadcastmanager; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Localbroadcastmanager=localbroadcastmanager.getinstance ( This);//get an example of Localbroadcastmanager by getinstance ()Sendbroadcast=(Button) Findviewbyid (r.id.sendbroadcast); Sendbroadcast.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//send a local broadcastIntent intent=NewIntent ("Com.example.LOCAL_BROADCAST"); Localbroadcastmanager.sendbroadcast (Intent); } }); //registering a local broadcast listenerIntentfilter=NewIntentfilter (); Intentfilter.addaction ("Com.example.LOCAL_BROADCAST"); Localreceiver=NewLocalreceiver (); Localbroadcastmanager.registerreceiver (Localreceiver,intentfilter); } classLocalreceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {toast.maketext (context,"Accept to local broadcast", Toast.length_short). Show (); }} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Localbroadcastmanager.unregisterreceiver (localreceiver);//Turn off broadcast }}
Android Learning summary-local broadcast mechanism