9

AlertDialog from within BroadcastReceiver? Can it be done? I am working on a app that will pop up a Dialog box if I get SMS message. I am trying to code this within a BroadcaseReceiver. But I cant use this line of code AlertDialog.Builder builder = new AlertDialog.Builder(this);. Can someone please help me with a hint!

public class SMSPopUpReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = "SMSReceiver";
    public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    public void onReceive(Context context, Intent intent) {
        Log.i(LOG_TAG, "onReceive");

        if (intent.getAction().equals(SMSPopUpReceiver.ACTION)) {
            StringBuilder sb = new StringBuilder();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");

            for (Object pdu : pdus){
                    SmsMessage messages =
            SmsMessage.createFromPdu((byte[]) pdu);

            sb.append("Received SMS\nFrom: ");
            sb.append(messages.getDisplayOriginatingAddress());
            sb.append("\n----Message----\n");
            sb.append( messages.getDisplayMessageBody());
            }
            }
            Log.i(SMSPopUpReceiver.LOG_TAG,
            "[SMSApp] onReceiveIntent: " + sb);
            Toast.makeText
            (context, sb.toString(), Toast.LENGTH_LONG).show();
            }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       dialog.cancel();
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
    }

}
Java Review
  • 427
  • 2
  • 9
  • 20
  • Why are you unable to use `AlertDialog.Builder builder = new AlertDialog.Builder(this);` is it not happy with the `this` reference? If that's the case try to replace it with a call to `getApplicationContext()`. I'm not sure if this is the problem you are having through. I feel like in this case the dialog box would only flash on the screen for a second before the BroadcastReceiver returns. – Will Tate Jan 30 '11 at 16:47
  • cant use getApplicationContext() ! – Java Review Jan 30 '11 at 22:30
  • Having a dialog pop up spontaneously (from the user's point of view) sounds like bad UI design to me. Why not use a notification? That's what they're for. – Edward Falk May 02 '13 at 07:14
  • this is the complete example, go through the link http://stackoverflow.com/a/41137562/4344659 – Sanjeev Sangral Dec 14 '16 at 11:51

5 Answers5

13

Principal issue: try to avoid placing time consuming functionalities into BroadcastReceiver. It should just receive and initiate further processing in bound Activity/Service.

UPDATE:

Please check following sources that might be helpful:

Similar questions on StackOverflow:

How to send data from BroadcastReceiver to an Activity in android?

Android SMS receiver not working

Android SDK demo example:

android-sdk-windows\samples\android-8\ApiDemos\src\com\example\android\apis\os\SmsMessagingDemo.java

And of course standard Android API documentation: http://developer.android.com/reference/android/content/BroadcastReceiver.html

UPDATE2:

Added app skeleton as it should look. Please note that no content view is defined. It is because your app will have transparent screen. To achieve that

@android:style/Theme.Translucent

is entered under Theme tag for this activity in AndroidManifest.xml.

public class NotifySMSReceived extends Activity 
{
    private static final String LOG_TAG = "SMSReceiver";
    public static final int NOTIFICATION_ID_RECEIVED = 0x1221;
    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IntentFilter filter = new IntentFilter(ACTION);
        this.registerReceiver(mReceivedSMSReceiver, filter);
    }

    private void displayAlert()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to exit?").setCancelable(
                false).setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION.equals(action)) 
            {
                //your SMS processing code
                displayAlert();
            }
        }
    };    
}
Community
  • 1
  • 1
Zelimir
  • 11,008
  • 6
  • 50
  • 45
  • I think your are right. can you please help me out with this! – Java Review Jan 30 '11 at 17:14
  • I would recommend you to create Service or Activity with transparent background and bind BroadcastReceiver to that. Check some Android SDK example. Also, I have some useful question/answer about that under my profile. – Zelimir Jan 30 '11 at 17:31
  • can you please tell me where to look, i am new to all this. googletalk me if you would like StutteringJohnSmith – Java Review Jan 30 '11 at 17:40
  • Updated my answer to include useful sources of knowledge. – Zelimir Jan 30 '11 at 18:20
  • zelimir i am looking at the code but I still dont understand it. can you help off line – Java Review Jan 30 '11 at 20:44
  • Updated again my answer. Sorry but I have no time for offline help. – Zelimir Jan 31 '11 at 07:31
  • Should not be the case. But since you solved your issue, I will not comment it further. – Zelimir Feb 02 '11 at 07:27
  • How come. I saw your last question, and see that you have app designed in the way I suggested to you. So, it should work, maybe some minor issue remains unresolved. If I find time, I will check your app on monday and see why it does not work. Regards. – Zelimir Feb 05 '11 at 10:07
  • did you have any luck Zelimir – Java Review Feb 07 '11 at 23:20
  • Added my answer under http://stackoverflow.com/questions/4905050/sms-popup-alertdialog-does-not-show-as-i-get-a-sms-message where you asked the same question again. – Zelimir Feb 08 '11 at 06:53
  • @Zelimir how to display the dialog from the activity after triggering the event from the command prompt? – AndroidOptimist Dec 18 '13 at 06:45
  • You mean using adb (because you mention command prompt)? You can define broadcast Intent and send it from command prompt to your phone connected via adb (please look at the documentation). You can adapt your app to react on receiving that broadcast and trigger some Activities accordingly. Is that what you asked about or complete fail? – Zelimir Dec 18 '13 at 10:43
7

I've been looking into it and the documentation of the BroadcastReceiver actually says:

public abstract void onReceive (Context context, Intent intent)

Since: API Level 1 This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values. The function is normally called within the main thread of its process, so you should never perform long-running operations in it (there is a timeout of 10 seconds that the system allows before considering the receiver to be blocked and a candidate to be killed). You cannot launch a popup dialog in your implementation of onReceive().

You cannot launch a popup dialog in your implementation of onReceive()

So it seems it is not possible

ccheneson
  • 49,072
  • 8
  • 63
  • 68
3

This is late but this may help someone.

You cannot use alert dialog inside broadcast receiver, we can use this only in activity or service. Try like this

In your onReceive method of broadcastreceiver add

Intent i = new Intent(context, yourclass.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);

and in yourclass set your dialog message, so that it will appear when you trigger the receiver event. I tried this and it worked me. Hope this may help some one :-)

AndroidOptimist
  • 1,419
  • 3
  • 23
  • 38
0

you can create a new transparent activity and then create Alert Dialog in that activity, whenever your alert is to be displayed call that activity from your broadcast reciever ,this could work, not tested

Pankaj Mehra
  • 134
  • 1
  • 3
  • 7
-1

replace the word "this" inside the AlertDilaog with "context" -- the first parameter on you onRecieve method.

 public void onReceive(Context context, Intent intent)
Umesh
  • 4,406
  • 2
  • 25
  • 37
  • I tryed using the context but I never see the Dilaog – Java Review Jan 30 '11 at 17:13
  • It never shows up because you have to `show()` it . `AlertDialog alert = builder.create(); alert.show();` – ccheneson Jan 30 '11 at 19:43
  • 2
    how I got this errror: 01-30 16:03:21.748: WARN/WindowManager(34): Attempted to add window with non-application token WindowToken{43c345e8 token=null}. Aborting. – Java Review Jan 30 '11 at 21:04
  • @Java Review: Have you changed your code to ` AlertDialog.Builder builder = new AlertDialog.Builder(context);` as Umesh suggested? – ccheneson Jan 30 '11 at 21:57