Android的短信接收类
Android的短信接收类 继承自BroadcastReceiver类,需要重写onReceive方法,当收到短信时就会自动触发onReceive方法,在onReceive方法中通过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]); } //产生一个Toast Toast toast = Toast.makeText(context, "短信内容: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG); //设置toast显示的位置 toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 200); //显示该Toast toast.show(); } } 因为在项目中使用了短信接口,所以需要在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>
相关推荐
fengyeezju 2020-06-25
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30