我写了接收短信的申请 在我写的AndroidManifest.xml中:
<receiver
android:name=".SmsReceiver">
<intent-filter>
<action
android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
收到的所有短信都由SmsReceiver类分析。
Class SmsReceiver:
public class SmsReceiver extends BroadcastReceiver
{
private static final String SMS_RECEIVED = "com.example.remotecontrol.SMS_RECEIVED";
private static final String SMS_CONTENT_KEY = "com.example.remotecontrol.SMS_CONTENT_KEY";
@Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
SmsMessage[] message = null;
String contentMessage = "";
if(bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
message = new SmsMessage[pdus.length];
for(int i=0; i<message.length; i++)
{
message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
contentMessage += "SMS from " + message[i].getOriginatingAddress() + ": ";
contentMessage += message[i].getMessageBody() + "\n";
}
Toast.makeText(context, contentMessage, Toast.LENGTH_LONG).show();
}
Intent intentSmsReceived = new Intent();
intentSmsReceived.setAction(SMS_RECEIVED);
intentSmsReceived.putExtra(SMS_CONTENT_KEY, contentMessage);
context.sendBroadcast(intentSmsReceived);
}
}
它接收短信并向程序发送意图。
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String contentMessage = intent.getExtras().getString(SMS_CONTENT_KEY);
Toast.makeText(context, contentMessage + "text", Toast.LENGTH_LONG).show();
//TODO
//process SMS
unregisterReceiver(this);
}
}, new IntentFilter(SMS_RECEIVED));
这部分代码采用意图和流程SMS并与应用程序进行交互。
如何取消注册Android Manifest中编写的接收器?它处理所有SMS-es,我希望它只处理一个正确的和关闭。
答案 0 :(得分:2)
如果在清单中指定了广播接收器,则无法以编程方式取消注册。您需要将其从清单中取出并在代码中注册。
或者您可以将其注册并在onReceive的第一行添加检查。可能是通过布尔标志。