How to show the content of a received SMS on Android in a text dialog?

Asked

Viewed 1,333 times

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/3835160/how-can-i-display-a-dialog-from-an-android-broadcast-receiver

https://stackoverflow.com/questions/7229951/how-to-raise-an-alert-dialog-from-broadcastreceiver-class

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?

1 answer

2


After several hours of searching and trying, I finally got the desired result, which really was based on the use of a BroadcastReceiver instantiated directly in my activity rather than declared way Manifest. To summarize the problem, consider that my activity is called MainActivity. In it, I declared a private variable message, which is intended to receive text from the SMS body. In the method onResume of the activity is then instantiated the BroadcastReceiver, which brings the implementation of the method onReceive already mounting the String in the variable message activity (such as the BroadcastReceiver is now an object of MainActivity he has access to her private variables), which in turn is passed to TextViewFragment (via object Bundle) to be shown in the dialogue he instantiated:

public class MainActivity extends FragmentActivity {

    //Objeto responsável pela recepção de SMS
    BroadcastReceiver smsReceiver;
    //String destinada a receber o conteúdo do SMS, o qual deverá ser apresentado
    //ao usuário por meio de um diálogo de texto
    private String message;

    @Override
    public void onResume() {
        super.onResume();

        //Instancia BroadcastReceiver responsável pelo recebimento de SMS
        smsReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                //Obtém a mensagem do SMS recebido
                Bundle bundle = intent.getExtras();
                SmsMessage[] msgs = null;
                message = "";
                if (bundle != null)
                {
                    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]);
                        message += msgs[i].getMessageBody().toString();
                        message += "\n";
                    }
                }
                //Instancia fragmento responsável pelo diálogo que 
                //apresentará o conteúdo do SMS ao usuário
                Bundle bundleEventReport = new Bundle();
                bundleEventReport.putInt("title_id", R.string.label_events_report);
                bundleEventReport.putString("text", message);
                TextViewFragment eventReportFragment = new TextViewFragment();
                eventReportFragment.setArguments(bundleEventReport);
                eventReportFragment.show(getSupportFragmentManager(), "eventReport");
            }
        };
        //Registra o objeto BroadcastReceiver como recebedor de SMS
        registerReceiver(smsReceiver,
                         new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(smsReceiver);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.