标签:
首先,需要配置AndroidMainfest文件,添加权限
<uses-permission android:name="android.permission.READ_SMS"/> <uses-permission android:name="android.permission.RECEIVE_SMS"/>
然后注册广播,静态或动态注册都可以。我用的静态注册,在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>
然后新建一个类继承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, Intent 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());//时间 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); //在这里写自己的逻辑 if (msg.getOriginatingAddress().endsWith(num)) {
} } } } }
这样就可以使Activity在接收到短信广播后启动了。BroadCast向Activity传值请参考我的另一篇博文。
标签:
原文地址:http://www.cnblogs.com/liutanrong/p/4541803.html