这是一个对短信进行侦听的一个类,在一个项目中用到了,只要短信中包含你设置的关键字,就会以notifaction的形式提醒你
SMSReciver.java
import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.Toast; public class SMSReceiver extends BroadcastReceiver { /*当收到短信时,就会触发此方法*/ public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); } String s = smsMessage[0].getMessageBody(); String f = "开会|会议|生日|提醒|聚餐|聚会"; Pattern p = Pattern.compile(f); Matcher m = p.matcher(s); boolean res = false; res = m.find(); if( res == true ){ Intent in= new Intent(context,NoteActivity.class); in.putExtra("sms", "短信内容:\n"+s); PendingIntent pending = PendingIntent.getActivity( context, 0,in, 0); Notification noticed = new Notification(); noticed.icon = R.drawable.ic_launcher; noticed.tickerText = "重要通知"; noticed.defaults = Notification.DEFAULT_SOUND; // 使用默认的声音 noticed.setLatestEventInfo(context, "重要短信提醒", s, pending); NotificationManager noticedManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE); noticedManager.notify(0, noticed); } } }
下面是AndroidManifest.xml中的注册信息
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yarin.android.Examples_04_05" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Activity01" 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=".SMSReceiver" android:enabled="true"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="5" /> </manifest>