Android SMS and broadcast mechanisms

Source: Internet
Author: User

Broadcast Introduction


Broadcast is divided into two different types: Normal broadcast (Normal broadcasts) and Ordered broadcast (Ordered broadcasts )". Normal broadcast is completely asynchronous and can be received by all receivers at the same time (logically). The efficiency of message transmission is relatively high, but the disadvantage is: the receiver cannot pass the processing result to the next receiver, and cannot terminate the propagation of the broadcast Intent. However, the ordered broadcast is based on the priority stated by the receiver (declared in the android of the intent-filter element: in the priority attribute, the higher the data priority level, the value range is-1000 to 1000. You can also call setPriority () of the IntentFilter object to set the value. The receiver receives the broadcast in sequence. For example, if the level of A is higher than that of B and the level of B is higher than that of C, broadcast is first transmitted to A, then to B, and finally to C. After A receives the broadcast, it can store the data in the broadcast. When the broadcast passes to B, B can obtain the data stored by A from the broadcast.

 

Context. sendBroadcast () sends a normal broadcast. All subscribers have the opportunity to obtain and process the broadcast.

Context. sendOrderedBroadcast () sends an ordered broadcast. The system executes the receivers one by one based on the priority level stated by the receiver. The previous receiver has the right to terminate the broadcast (BroadcastReceiver. abortBroadcast (), if the broadcast is terminated by the previous receiver, the subsequent receiver will no longer be able to obtain the broadcast. For ordered broadcast, the previous receiver can save the processing result to the broadcast Intent and then pass it to the next receiver.

SendStickyBroadcast () means that if registerReceiver (BroadcastReceiver, IntentFilter) is executed only after the broadcast is sent, this method is still acceptable. In other words, in ReceiverActivity, Recevier is registered through code instead of Manifest. The last Intent sent by sendStickyBroadcast will be retained. The next time the Recevier is active, it will be accepted. The BROADCAST_STICKY permission is required. Otherwise, SecurityException is thrown.

 

 


SMS messages in Android phones are suitable for Broadcast Monitoring and must be registered for broadcasting. In addition, it can also be used to filter out text messages based on the content and phone number.

Upload the main code to the storage disk, so that you can retrieve it when you forget it.

 

 

First, subscribe to the broadcast Intent you are interested in. There are two subscription methods:

First: Subscribe using code

Java code

IntentFilter filter = new IntentFilter ("android. provider. Telephony. SMS_RECEIVED ");

RegisterClass extends ER = new registerClass ();

RegisterReceiver (receiver, filter );

 

Type 2: subscribe to the <application> node in the AndroidManifest. xml file:

Html code

<Cycler android: name = ". IncomingSMSReceiver">

<Intent-filter>

<Action android: name = "android. provider. Telephony. SMS_RECEIVED"/>

</Intent-filter>

</Cycler>


I use the second

 


Package com. lan. www;

Import android. content. BroadcastReceiver;
Import android. content. Context;
Import android. content. Intent;
Import android. OS. Bundle;
Import android. telephony. SmsMessage;
Import android. util. Log;
// This is the broadcast class that needs to inherit from the system
Public class SmsReciver extends BroadcastReceiver {
Private final String MagicString = "lan ";


// The onReceive life cycle is 10 seconds, so the operation in it cannot exceed 10 seconds


@ Override
Public void onReceive (Context context, Intent intent ){
// TODO Auto-generated method stub
If (intent. getAction ()! = Null) & (intent. getAction (). equals ("android. provider. Telephony. SMS_RECEIVED") // This action is exclusive to System text messages
{
StringBuffer sb = new StringBuffer ();
Bundle bundle = intent. getExtras (); // If a text message is sent, the Android system uses a Bundle to store the text message.
If (bundle! = Null)
{
// The SMS header is a pdus
Object [] pdus = (Object []) bundle. get ("pdus"); // one text message (about 70 characters in Chinese, about 140 characters in English, including punctuation marks), may contain more than one, but each entry has a pdus

SmsMessage [] msgs = new SmsMessage [pdus. length]; // The number of SMS messages that can be sent
For (int I = 0; I <msgs. length; I ++ ){
// Text message content
Msgs [I] = SmsMessage. createFromPdu (byte []) pdus [I]);
}
// Get the phone number. Generally, you can get the phone number of the first text message. If you want to be rigorous, you should get the phone number for each text message, because other people may be sending a text message,
String telnumber = msgs [0]. getOriginatingAddress ();
For (SmsMessage smsMessage: msgs ){
Sb. append (smsMessage. getMessageBody ());
}

If (smgs. length ()> 0 ){


Date date = new Date (smgs [0]. getTimestampMillis ());
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
String time = format. format (date); // get the sending time

}

 

Log. I ("lan", "SMS telnumber =" + telnumber + "info =" + sb. toString ());
// Filter text messages
If (sb. indexOf (MagicString )! =-1)
{
// Clear the filtered text message content in it
Sb = null;
// Stop Broadcast
This. abortBroadcast ();
}
If (sb! = Null & sb. length ()! = 0)
{
Intent it = new Intent (context, SMS1Activity. class). putExtra ("info", sb. toString (). setFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
Context. startActivity (it); // I passed it to another interface
}
}
// This method is sometimes difficult to use. If it is not easy to use, add it here.
// This. abortBroadcast ();
}
}

}
Configure in the AndroidManifest. xml file:

<Cycler android: name = "SmsReciver">
<Intent-filter android: priority = "1000"> // The higher the permission, the execution can be ensured. Currently, the maximum value is int,
<Action android: name = "android. provider. Telephony. SMS_RECEIVED"/>

</Intent-filter>
</Cycler>

 


<Uses-permission android: name = "android. permission. RECEIVE_SMS"/> <! -- Receive SMS -->
<Uses-permission android: name = "android. permission. SEND_SMS"/> <! -- Send SMS permission -->

 


Send another text message

SmsManager sms = SmsManager. getDefault (); // obtain the sms manager of the system.
ArrayList <String> texts = sms. divideMessage (text. toString (); // you can separate multiple text messages.
PendingIntent pi = PendingIntent. getBroadcast (// This class is used when not necessarily occurring
Sendpolicy. this,
0,
New Intent (),
0 );
For (String string: texts ){
For (int I = 0; I <phones. length; I ++ ){
Sms. sendTextMessage (phones [I], null, string, pi, null); // send sms
}
}

 


 

If you want to add a special prompt to the phone number or add the area code and 12593 discount number by default, you need to listen to the phone number for processing:


When a phone call is made, the system sends an ordered broadcast. Although the broadcast is eventually received by the broadcast receiver in the dial-up device, however, we can get the broadcast before the broadcast is passed to the broadcast receiver, and then clear the phone number sent to the broadcast receiver. When the broadcast receiver receives the broadcast, because the phone number is null, cancel the call.

Public class OutgoingCallReceiver extends BroadcastReceiver {
Public void onReceive (Context context, Intent intent ){
SetResultData (null); // clear the call. After the broadcast is sent to the receiver of the system, cancel the call because the call is null.

// Similarly, if you want to modify the phone number of the outbound caller, you can do this.
// String phone = getResultData (); // obtain the outgoing call.
// SetResultData ("12593" + phone); // Add 12593 in front of the phone
}
}


Receive an outbound call broadcast Intent and subscribe to this Intent in the <application> node in the AndroidManifest. xml file:
<Cycler android: name = ". OutgoingCallReceiver">
<Intent-filter android: priority = "1">
<Action android: name = "android. intent. action. NEW_OUTGOING_CALL"/>
</Intent-filter>
</Cycler>
And you need to declare the permission:
<Uses-permission android: name = "android. permission. process_outgoing_cils"/>

 

 

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.