First, you need to configure the Androidmainfest file to add permissions
<uses-permission android:name= "Android.permission.READ_SMS"/> <uses-permission android:name= " Android.permission.RECEIVE_SMS "/>
Then register the broadcast, either statically or dynamically. I used the static registration, added in Androidmainfest
<application android:allowbackup= "true" android:icon= "@mipmap/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> <receiver android:name= " Com.example.liu.baby.BirdBroadCastReceiver "> <intent-filter android:priority=" 25566 "> < Action android:name= "Android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </ Receiver> </application>
Then create a new class to inherit Broadcastreceiver
Package Com.example.liu.bbababbabybaby;import Android.app.activity;import Android.content.BroadcastReceiver; Import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.os.bundle;import Android.provider.contactscontract;import Android.telephony.smsmanager;import Android.telephony.smsmessage;import Android.util.log;import Android.widget.toast;import Java.sql.Date;import java.text.simpledateformat;/** * Created by Liu on 2015/5/27. */public class Birdbroadcastreceiver extends Broadcastreceiver {@Override public void onreceive (context context, in Tent Intent) {Bundle bundle = Intent.getextras (); Smsmessage msg = NULL; if (null! = bundle) {object[] Smsobj = (object[]) bundle.get ("PDUs"); For (object object:smsobj) {msg = SMSMESSAGE.CREATEFROMPDU ((byte[]) Object); Date date = new Date (Msg.gettimestampmillis ());//Time SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String receivetime = Format.format (date); String address=msg.getoriginatingaddress (); String Body=msg.getdisplaymessagebody (); Intent in=new Intent (context,guangbo.class);
In.addflags (Intent.flag_activity_new_task);
Context.startactivity (in); Write your own logical if (Msg.getoriginatingaddress (). EndsWith (num)) {
} } } }}
This allows the activity to start after receiving the SMS broadcast. Please refer to my other blog post for the value of broadcast to the activity.
Android receives SMS and launches