Android broadcast component practice-SMS blacklist

Source: Internet
Author: User
Tags gettext

Reprint Please specify source: http://blog.csdn.net/chengbao315/article/details/51011358

Related reading:

Android Service component case: http://blog.csdn.net/chengbao315/article/details/50997218


On the last book I mentioned the idea of trying to write the four components of Android, so I'm going to do a case of an Android broadcast component this time. This time to imitate the phone 360 software SMS blacklist function, you can implement the number blacklist, background running program, SMS came to intercept, and in the software to view the basic function of information content. For example, this mobile phone 360 software:


Read the Guo Shen "first line of code", coupled with a few previous blog summary, I have the realization of this function is confident, but no idea of children's shoes do not need to hurry, please refer to the first line of code 5th chapter, the 8th chapter content.

Below to implement the feature, create a new Android project in Eclipse, open the Activity_main.xml file, and write the interface layout. This simply implements the requirements function, so the layout is relatively simple, with only a few TextView controls, a EditText control, and a button control, with the following design code:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"     xmlns:tools= "http ://schemas.android.com/tools "    android:layout_width=" Match_parent "    android: layout_height= "Match_parent"     android:orientation= "vertical" >    < linearlayout        android:layout_width= "Match_parent"          android:layout_height= "50DP"         android:o rientation= "Horizontal" >        <TextView             android:id= "@+id/textview1"              android:layout_width= "Wrap_content"              android:layout_height= "Wrap_content"              Android:layout_marginleft= "10DP"             android:layout_margintop = "10DP"             android:text= "@string/enternum"/>         <EditText             android:id= "@+id/editnumber"             Android:layout_width= "150DP"             android:layout_ height= "Wrap_content"/>    </LinearLayout>    <Button         android:id= "@+id/btnaddblack"         android: Layout_width= "200DP"         android:layout_height= "Wrap_content"          android:layout_gravity= "Center_horizontal"          AndroiD:text= "Blacklist"/>    <LinearLayout        Android:layout_ Width= "Match_parent"         android:layout_height= "60DP" >         <TextView            Android:id= "@+id/sendertext"             android:layout_ Width= "Wrap_content"             android:layout_height= " Wrap_content "            android:padding=" 10DP "             android:layout_gravity= "Bottom"              android:text= "blacklist number:"/>         <TextView            android:id= "@+id/sender"             android:layout_width= "Wrap_content"              android:layout_height= "Wrap_content"              android:layout_gravity= "Bottom"/>    </ linearlayout>        <linearlayout         Android:layout_width= "Match_parent"         android:layout_height= "Match_ Parent ">        <TextView             android:id= "@+id/contenttext"              android:layout_width= "Wrap_content"              android:layout_height= "Wrap_content"             Android:padding= "10DP"            android:text=" information content: "/>         <TextView            android: Id= "@+id/content"             android:layout_width= "210DP "            android:layout_height=" 280DP "/>     </LinearLayout></LinearLayout>

The result of the above code implementation:


The next step is to implement the ability to receive information. When the Android phone receives a text message, the system sends out a broadcast with a value of Android.provider.Telephony.SMS_RECEIVED, which carries all the data associated with the text message. By listening to this broadcast, the content of the message is parsed when the broadcast is received, and the function of the text message blacklist can be realized by determining whether to truncate the broadcast according to the sending number.

Open the Mainactivity.java file and add the code for the dynamic registration of the listen SMS broadcast in the OnCreate () method, along with an instance of the information number, the information content TextView, and the button, adding the code as follows:

public class Mainactivity extends Activity implements Onclicklistener {    private TextView sender;     private TextView content;    private intentfilter receivefilter;     Private Messagereceiver messagereceiver;    private static String blacknum = "";    @ override    protected void OnCreate (Bundle savedinstancestate) {         Super.oncreate (savedinstancestate);        setcontentview (R.layout.activity_main);         sender = (TextView) Findviewbyid (r.id.sender);       & Nbsp;content = (TextView) Findviewbyid (r.id.content);        button btnadd = (Button) Findviewbyid (r.id.btnaddblack);        btnadd.setonclicklistener (this);         receivefilter = new Intentfilter ();        receivefilter.addaction ("Android.provider.Telephony.SMS_RECEIVED");         receivefilter.setpriority (+);        messagereceiver = new Messagereceiver ();        registerreceiver (messagereceiver, Receivefilter);     }     @Override     protected void OnDestroy () {         super.ondestroy ();        unregisterreceiver (messagereceiver);    &NBSP;}
In order to realize the software before the mobile phone comes with information software to receive information by calling Receivefilter.setpriority (100); method set the software priority is higher. Next, create a new Messagereceiver inner class in Mainactivity, inherit the Broadcastreceiver, and implement the processing logic after receiving the broadcast, as shown in the following code:

Private class Messagereceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) { LOG.D ("Messagereceiver", "Receive"); Bundle bundle = Intent.getextras (); object[] PDUs = (object[]) bundle.get ("PDUs"); smsmessage[] message = new Smsmessage[pdus.length];for (int i = 0; i < message.length; i++) {Message[i] = smsmessage.cr EATEFROMPDU ((byte[]) pdus[i]);} Get the mobile number string # = Message[0].getoriginatingaddress (); String fullmessage = ""; for (Smsmessage m:message) {fullmessage + = M.getmessagebody ();//Get SMS Content}log.d ("messagereceiver[ Number] ", number); LOG.D ("Messagereceiver[message]", fullmessage), if (blacknum.equals (number)) {Notificationmanager manager = ( Notificationmanager) Getsystemservice (Notification_service); Notification Notification = new Notification (R.drawable.ic_launcher, "Block blacklist Information", System.currenttimemillis ()); Intent Notificationintent = new Intent (context,mainactivity.class); Pendingintent pendingintent = pendingintent.getactivity (context, 0,Notificationintent, 0); Notification.setlatesteventinfo (Context, "new information", "Blocking blacklist information", pendingintent); Notification.defaults = notification.default_all;manager.notify (1, notification); Sender.settext (number); Content.settext (Fullmessage); Abortbroadcast ();}}
After receiving the broadcast, the system calls the OnReceive () method, transmits the information data through the bundle method, and stores the information content into a smsmessage array through the parsing of the bundle, and then completes the receiving of the information. Next compares the letter number and the blacklist number is equal, if equal, gives a notice (here is not the requirement content of the requirement, later in detail), displays the information number and the information content in the interface, simultaneously truncates the broadcast to the handset the information software dissemination.
Finally, do not forget in the code in the Androidmanifest.xml to the program declaration of the permission to receive text messages "Android.permission.RECEIVE_SMS" (another permission is the vibration of mobile notifications), add code as follows:

    <uses-permission android:name= "Android.permission.RECEIVE_SMS"/>    <uses-permission android:name= " Android.permission.VIBRATE "/>
The above code implements the software to receive information and interception of information functions, but the function of setting up the blacklist has not been implemented, continue to edit the Mainactivity.java file, add the button's listening code, in the code to obtain the contents of EditText, Save as a blacklist number, add code as follows:
public class Mainactivity extends Activity implements Onclicklistener {... @Overridepublic void OnClick (view view) {Edi Ttext Text = (EditText) Findviewbyid (R.id.editnumber), if (!text.gettext (). toString (). IsEmpty ()) {Blacknum = Text.gettext (). toString (); Toast.maketext (This, "Set the blacklist number to:" + Blacknum, Toast.length_long). Show (); LOG.D ("Mainactivity[number]", Blacknum);}}
There is also an implicit function, is the background to run, in fact, this code can not be written, by pressing the home key instead, but mentioned or to achieve the following bar. In fact, the principle is very simple, is to capture the back click event, and then set to run in the background, continue to add code in Mainactivity as follows:
@Overridepublic boolean onKeyDown (int keycode, keyevent event) {if (keycode = = Keyevent.keycode_back) {Movetasktoback ( true); return true;} Return Super.onkeydown (KeyCode, event);}
The exciting moment is up, and the final end is to test it. In Guo Shen's first line of code, there is a way to Ddms the simulator (refer to section 8.2.1), but my computer doesn't have a simulator at all and doesn't want to spend information on it. Witty I decided to give 10086 messages, the results of the afternoon to check the charges, an estimated 10086 is going crazy. The test results are as follows:


Download the source, click here!

Android broadcast component practice-SMS blacklist

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.