2
I’m developing an Android app that sends an SMS request to a remote device and receives back a reply, also via SMS, which should be presented to the user.
To receive the SMS I used the following code, which implements SmsReceiver
from a BroadcastReceiver
, presenting the content of the message received through a Toast
:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
}
Like the Toast
is a temporary message and automatically disappears, it is difficult for the user to read the content calmly, so I thought of presenting it through a dialog with an OK button. That way, I thought I’d use a DialogFragment
, but according to several responses in Stack Overflow (in English) as:
https://stackoverflow.com/questions/9667790/showing-an-alertdialog-from-receiver
and others - it became clear that this dialogue cannot be directly instantiated from a BroadcastReceiver
(base class used to receive the SMS) but yes from a Activity
. However, this answer (also in English), explains that if you register your BroadcastReceiver
activity through the method registerReceiver
instead of having it declared in Manifest - which is what is currently done in my application - I could simply use this same activity to present my dialog.
Since I’m a bit of a beginner still in Java, how do I do this? Should I instantiate my class SmsReceiver
as a private class of mine Activity
and then call the registerReceiver
for her?