Android broadcast implements SMS listening and automatically starts activity upon startup

Source: Internet
Author: User

I. Text message listener

First, subscribe to the broadcast intent you are interested in. There are two subscription methods:
First: Subscribe using code

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

Type 2: subscribe to the <Application> node in the androidmanifest. xml file:

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

The second method is used:

In Android, to accept broadcast information, we have to implement this broadcast receiver by ourselves. We can inherit broadcastreceiver to have a broadcast receiver. There is not enough receiver. We have to rewrite the onreceiver method in broadcastreceiver. What should we do when we come to broadcast? We need to implement it ourselves !!

Public class mysmslistener extends broadcastreceiver {public void onreceive (context arg0, intent) {bundle = intent. getextras (); object [] PDUS = (object []) bundle. get ("PDUS"); If (PDUS! = NULL & PDUS. length> 0) {smsmessage [] messages = new smsmessage [PDUS. length]; for (INT I = 0; I <messages. length; I ++) {byte [] PDU = (byte []) PDUS [I]; messages [I] = smsmessage. createfrompdu (PDU);} For (smsmessage MSG: messages) {string content = MSG. getmessagebody (); string sender = MSG. getoriginatingaddress (); Date = new date (MSG. gettimestampmillis (); simpledateformat SDF = new simpledateformat ("yyyy-mm-dd hh: mm: SS"); string Sendtime = SDF. Format (date); If (sender! = NULL & sender. endswith ("5556") {system. out. println ("5556"); smsmanager = smsmanager. getdefault (); smsmanager. sendtextmessage ("5556", null, "Go !! ", Null, null); this. abortbroadcast (); // terminate broadcast }}}}}

Start two simulators here !!

The IF statement determines whether the message is sent from 5556. if the message is sent, the broadcast is terminated. if the message is sent from 5556 to 5554, the message "go to!" is sent !! ";

Here, you don't need to understand what PDUS is. You just need to remember it!

Then add the following code to the <Application> node in the androidmanifest. xml file,

Register

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

This priority is the defined permission and the value is-1000 ~ 1000;
Add the permission application:

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

OK! You can paste the code to try the effect !!

Ii. Automatically Start activity upon startup

Inherit the broadcasereceiver class

Public class startlisteneractivity extends broadcastreceiver {public void onreceive (context, intent) {log. I ("tag", "system started"); string Category = "android. intent. category. launcher "; string action =" android. intent. action. main "; intent myintent = new intent (context, dateacitivty. class); // dateacitivty is my main program interface myintent. setaction (action); myintent. addcategory (category); myintent. addflags (intent. flag_activity_new_task); context. startactivity (myintent); log. I ("tag", "activity started ");}}

Androidmanifest. xml file

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="cn.csdn.listener"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="10" />    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <receiver             android:name=".StartListenerActivity">            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED"/>            </intent-filter>        </receiver>       <activity            android:name=".DateAcitivty">           <intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>       </activity>    </application></manifest>

Finally, the activity class is given:

Public class dateacitivty extends activity {textview hello; protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Hello = (textview) findviewbyid (R. id. hello); Date = new date (); simpledateformat format = new simpledateformat ("yyyy-mm-dd hh: mm: SS"); string time = format. format (date); Hello. settext (time); toast. maketext (this, "success" + time, toast. length_long ). show ();}}

Final supplement:

In addition to text messages, boot broadcast intent, Android also has a lot of broadcast intent, such as battery power change, time change, and so on.

In Android, if you want to send a broadcast, you must use sendbroadcast to send a broadcast receiver to the system that is interested in it.

 To use broadcast, you must have an intent object that must set its action object.

To use broadcast, you must explicitly specify the broadcast object in the configuration file.

 Each time a broadcast is received, a new broadcast receiving object is generated.

Do not handle too many logic problems in broadcast. It is recommended that complicated logic be handled by activity or service.

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.