I wrote application, that receive SMS.
In the AndroidManifest.xml I wrote:
<receiver
android:name=".SmsReceiver">
<intent-filter>
<action
android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
All the SMS-es that are received are analyzed by the class 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);
}
}
It receive SMS and send intent to the program.
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));
This part of the code takes the intent and process SMS and interact with application.
How to unregister receiver written in Android Manifest? It process all SMS-es, I want it to process only one correct and the close.
If your broadcast receiver is specified in the manifest, it cannot be unregistered programmatically. You will need to take it out of the manifest and register it from within your code.
alternatively you can leave it registered and add check at first line of onReceive . might be through a Boolean flag .