在Android中,要接收和处理短信,你需要创建一个BroadcastReceiver,而这个BroadcastReceiver将在短信到达时被系统调用。以下是一个简单的示例。
首先,我们需要在AndroidManifest.xml文件中声明需要的权限和注册我们的BroadcastReceiver。
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<receiver android:name=".SmsReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
然后,我们创建一个名为SmsReceiver的BroadcastReceiver:
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "SmsReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Intent received: " + intent.getAction());
if (intent.getAction() == SMS_RECEIVED) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
// get sms objects
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
// large message might be broken into many
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
String message = sb.toString();
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
// prevent any other broadcast receivers from receiving broadcast
abortBroadcast();
}
}
}
}
这个BroadcastReceiver将在短信到达时被调用,它将解析那个信息并打印它。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/171288.html