BroadcastReceiver broadcast receiver (1) -- register broadcast receiver using code
MainActivity is as follows:
Package cc. testbroadcasta; import android. OS. bundle; import android. app. activity; import android. content. intent; import android. content. intentFilter;/*** Demo Description: * Register broadcast receiver in code * 1 register broadcast receiver in onCreate () * 2 register broadcast receiver in onDestroy () cancel registration of broadcast receiver */public class MainActivity extends Activity {private BroadcastReceiverTest mBroadcastReceiverTest; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (s AvedInstanceState); setContentView (R. layout. main); // register a broadcast receiver registerAReceiver (); // send a broadcast sendABroadcast ();} private void registerAReceiver () {mBroadcastReceiverTest = new BroadcastReceiverTest (); // set IntentFilterIntentFilter intentFilter = new IntentFilter (); intentFilter for the broadcast receiver. addAction (cc. test); registerReceiver (mBroadcastReceiverTest, intentFilter);} private void sendABroadcast () {Intent intent = new Inten T (); // sets Actionintent. setAction (cc. test); // carries data intent. putExtra (name, Stephen Chow); intent. putExtra (number, 9527); // send broadcast sendBroadcast (intent) ;}@ Overrideprotected void onDestroy () {super. onDestroy (); // cancel the registration of the broadcast receiver if (mBroadcastReceiverTest! = Null) {unregisterReceiver (mBroadcastReceiverTest );}}}
BroadcastReceiverTest is as follows:
Package cc. testbroadcasta; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; public class BroadcastReceiverTest extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {String name = intent. getStringExtra (name); int number = intent. getIntExtra (number, 0); System. out. println (received broadcast name = + name +, number = + number);} public static void main (String [] args ){}}
??