我已经使用隐式广播接收器来接收数据短信,但是现在有了android O,就不可能了
<receiver android:name=".receiver.SMSReceiver">
<intent-filter>
<action android:name="android.intent.action.DATA_SMS_RECEIVED"/>
<data android:scheme="sms"/>
<data android:port="10013"/>
</intent-filter>
</receiver>
关于如何在android O及更高版本上实现数据短信的任何想法?
答案 0 :(得分:0)
在清单文件中声明广播接收器
<receiver android:name=".SMSReader">
<intent-filter android:priority="999" android:exported="true">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
广播接收器类
public class SMSReader extends BroadcastReceiver {
private String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private Intent smsIntent;
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction() != null && intent.getAction().equalsIgnoreCase(SMS_RECEIVED)) {
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
long time = currentMessage.getTimestampMillis();
String senderNum = phoneNumber;
if (senderNum.contains("UPI")) ;
{
String message = currentMessage.getDisplayMessageBody();
if (message.contains("debit")) {
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
smsIntent = new Intent("read");
smsIntent.putExtra("message", message);
smsIntent.putExtra("sender", senderNum);
LocalBroadcastManager.getInstance(context).sendBroadcast(smsIntent);
}
}
}
}
} catch (Exception e) {
Log.e("SMSReader", "Exception" + e.toString());
}
}
}
}
在onCreate()
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("read"));
创建一个单独的方法来处理SMS
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("read")) {
final String message = intent.getStringExtra("message");
final String sender = intent.getStringExtra("sender");
formatMessage(message,sender);
}
}
};