Android learning notes (Broadcast Mechanism) and android learning notes
1. Introduction to the broadcast mechanism of Android
Listening to a radio is also a kind of broadcast. There are many radio stations in the radio, and the content played by each radio station is different. When receiving a broadcast, the broadcast (sender) does not care how we (receiver) handle the broadcast. For example, when we listen to the broadcast of the traffic station, the TV station tells us how we are doing in traffic conditions, but it does not care about how we handle the broadcast. This is not a question that the broadcast should be concerned about, okay. Here we have understood broadcast from some small examples in our lives. How do we operate broadcast in Android?
There are a variety of broadcasts in Android, such as battery usage, telephone reception and text message reception, application developers can also listen to these broadcasts and process program logic.
A classic phone blacklist first stores the blacklist number in the database. When a call arrives, we receive the incoming broadcast and match the blacklist number with a certain data in the database, if yes, handle the problem, such as phone disconnection or mute.
2. Functions of BroadcaseReceiver
1. messaging within the same component of the same app (between one or more threads );
2. messaging between different components in the same app (a single process );
3. Message Communication between different components of the same app with multiple processes;
4. Message Communication between components of different apps;
5. Message Communication Between the Android system and the App in specific circumstances.
3. BroadcaseRecevier Implementation Method
1. Create a class, inherit from BroadcastRecevier, and override the onRecevier () method. The onRecevier method is the callback Method for receiving listening events.
package com.example.broadcasereceiverdemo;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class TestReceiver extends BroadcastReceiver{ public TestReceiver(){ System.out.println("TestReceiver create"); } @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub System.out.println("onReceive///"); }}
2. Register Broadcast
There are two methods to register Broadcast
1. Register in the AndroidManifrst. xml file
Creates a receiver tag, intentfilter, and sets the event type to be answered. Android: name: Class name, Intent-filter: filters broadcast events sent, only events that match the action will be received and processed.
For example, to monitor the battery status, you need to use this method for registration.
2. Register in the program code
The registration method is flexible. When you want to use it, you can register it and disable it when you do not use it.
1. registerReceiver (receiver, filter); Registration, reciver object, filtered event
2. unregisterReceiver (receiver); cancel registration, reciver object
If a BroadcaseReceiver is used to update the UI, this method is usually used to register at startup and cancel registration when invisible.
// TODO Auto-generated method stub // 1. create a broadcast receiver object TestBroadcastRecevier test = new TestBroadcastRecevier (); // 2. create an Intent-filterIntentFilter filter = new IntentFilter (); // 3. add Actionfilter for Intent-Filter. addAction ("android. provider. telephony. SMS_RECEIVED "); // 4. register the broadcast receiver MainActivity. this. registerReceiver (test, filter );
4. Android built-in BroadcaseAction
5. Example
1. Broadcast in Activity
1. Define a class, inherit from BroadcastRecevier, and re-use the onRecevier Method
Package com. example. broadcastrecevierdemo; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; public class TestBroadcastRecevier extends BroadcastReceiver {public TestBroadcastRecevier () {System. out. println ("TestBroadcastRecevier object creation") ;}@ Override public void onReceive (Context arg0, Intent arg1) {// TODO Auto-generated method stub System. out. println ("onReceiver ");}}
2. Register Broadcast
<Application android: allowBackup = "true" android: icon = "@ drawable/ic_launcher" android: label = "@ string/app_name" android: theme = "@ style/AppTheme"> <activity android: name = ". mainActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> <! -- Register the broadcast listener --> <receiver er android: name = ". testBroadcastRecevier "> <intent-filter> <action android: name =" android. inent. action. EDIT "/> </intent-filter> </receiver> </application>
3. Send broadcast events
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendBtn = (Button) findViewById(R.id.sendBtn); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setAction(Intent.ACTION_EDIT); MainActivity.this.sendBroadcast(intent); } }); }
Click the button to run the program.
Declaration cycle Description: From the Demo above, we can see that once you call the constructor method and then call the onReceive method, you can know that after the processing is complete, the broadcast receiver object will become invalid, call again next time and recreate the object
2. Receive System broadcast
1. Define a class, inherit from BroadcastRecevier, reonrecevier method, and receive text message content
Public class TestBroadcastRecevier extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// TODO Auto-generated method stub System. out. println ("xx"); // The receiving parameter Bundle bundle = intent. getExtras (); Object [] obj = (Object []) bundle. get ("pdus"); SmsMessage [] message = new SmsMessage [obj. length]; System. out. println (message. length); for (int I = 0; I <obj. length; I ++) {message [I] = SmsMessage. createFromPdu (byte []) obj [I]); System. out. println (message [I]. getDisplayMessageBody (); Toast. makeText (context, message [I]. getDisplayMessageBody (), Toast. LENGTH_SHORT ). show ();}}}
2. Bind the listening code of the broadcast receiving Class
/*** Bind broadcast event processing ** @ author Administrator **/class MyRegistClick implements OnClickListener {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub // 1. create a broadcast receiver object test = new TestBroadcastRecevier (); // 2. create an Intent-filter IntentFilter filter = new IntentFilter (); // 3. add Action Filter for Intent-filter. addAction (SMS_ACTION); // 4. register the broadcast receiver MainActivity. this. registerReceiver (test, filter); Toast. makeText (MainActivity. this, "bound successfully", Toast. LENGTH_SHORT ). show ();}}
Click Event listening code for unbinding
/*** Unbroadcast ** @ author Administrator **/class MyUnRegistClick implements OnClickListener {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub MainActivity. this. unregisterReceiver (test); Toast. makeText (MainActivity. this, "unbound successfully", Toast. LENGTH_SHORT ). show ();}}
3. added the SMS receiving permission.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreciverdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
4. Use Emalator Controller to send text messages to the simulator through Eclipse