How to show the contents of an SMS received in Android in a text dialog?

2

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:

link

link

link

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?

    
asked by anonymous 19.03.2014 / 14:52

1 answer

1

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

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);
    }

}
    
19.03.2014 / 22:38