你不能改变接收到的intent,但是如果你……嘿嘿……打算修改接收到的短信,因为它是一个有序广播,你可以停止广播,修改intent的额外内容,然后重新广播它:
在 Application 标记之前将以下内容添加到 ApplicationManifest.xml:
<uses-permission android:name="android.permission.BROADCAST_SMS" />
请注意,这将显示在 Play 商店中您应用的权限页面上。准备好解释它。
并将其添加到接收器中的 Intent-Filter 标记中:
android:priority="2147483647"
这是 Java 中可能的最高整数,确保您的接收器获得第一优先级。请注意,其他应用程序(尤其是 GO SMS)中的接收者可能使用相同的策略,这可能意味着两个接收者最终会为一条消息而争吵。如果发生这种情况,您可能必须卸载其他应用程序。
然后在你的接收器中:
public void onReceive(Context context, Intent intent){
//Messages are delivered as extras in the intent
Bundle bundle = intent.getExtras();
//If this intent was rebroadcasted already, ignore it.
if(bundle.getBooleanExtra("rebroadcast", false)
return;
//Abort the broadcast
abortBroadcast();
//Some examples use regular arrays,
// but I prefer a more sophisticated solution.
ArrayList<SmsMessage> msgs = new ArrayList<SmsMessage>();
//Check to make sure we actually have a message
if(bundle != null){
//Get the SMS messages
//They are delivered in a raw format,
//called Protocol Description Units or PDUs
//Messages can sometimes be delivered in bulk,
//so that's why it's an array
Object[] pdus = (Object[]) bundle.get("pdus");
//I prefer the enhanced for-loop. Why reinvent the wheel?
for(Object pdu : pdus)
msgs.add(SmsMessage.createFromPdu((byte[])pdu));
//Do stuff with the message.
ArrayList<SmsMessage> newMessages = smsReceived(msgs);
//Convert back to PDUs
ArrayList<Object> pdus;
Iterator<SmsMessage> iterator = newMessages.iterator();
//Iterate over the messages and convert them
while(iterator.hasNext()){
pdus.add(iterator.next().getPdu())
}
//Convert back to an Object[] for bundling
Object[] pduArr = pdus.toArray();
//Redefine the intent.
//It already has the broadcast action on it,
//so we just need to update the extras
bundle.putExtra("pdus", pduArr);
//Set a rebroadcast indicator so we don't process it again
//and create an infinite loop
bundle.putExtra("rebroadcast", true);
intent.putExtras(bundle);
//Finally, broadcast the modified intent with the original permission
sendOrderedBroadcast(intent, "android.permission.RECEIVE_SMS");
else{
//For some reason, there was no message in the message.
//What do you plan to do about that? I'd just ignore it.
}
}
虽然这是一个功能示例,但我建议在新线程中执行大部分操作,以便在您的消息处理是处理器密集型的情况下不会阻塞 UI 线程。例如,我这样做是因为我使用了大量的正则表达式来操作消息,以及执行一些与消息相关的非常繁重的数据库查询。
如果我做错了什么或本可以做得更好,请不要犹豫纠正我。大部分代码都在我自己的项目中,我希望能够保证它的功能。
祝你今天过得愉快。