I'm developing an Android application that sends an SMS request to a remote device and receives a reply, also via SMS, which should be presented to the user.
In order to receive SMS I used the following code, which implements SmsReceiver
from a BroadcastReceiver
, showing the contents of the received message by means of 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();
}
}
}
As Toast
is a temporary message and automatically adds up, it is difficult for the user to read the content in a calm way, so I thought I would introduce it through a dialog with an OK button. So I thought about using DialogFragment
, but, according to several answers in Stack Overflow like:
and others - it was clear that this dialog can not be directly instantiated from a BroadcastReceiver
(base class used to receive SMS) but rather from a Activity
. However, this answer explains that if you register your BroadcastReceiver
on the activity using the 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 still a beginner in Java, how do I do this? Should I instantiate my class SmsReceiver
as a private class of my Activity
and then call registerReceiver
to it?