SMS Popup: AlertDialog does not show as I get a SMS message

限于喜欢 提交于 2019-12-13 05:39:02

问题


I see a lot of applications that do SMS popups. Why can't I get my app working? If a SMS message comes in, I would like it to popup on the screen.

Here's my code:

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";


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

回答1:


I think problem here is with context object. From,

onReceive(Context context, Intent intent)

You should pass context received in onRecive to like..

private void displayAlert(Context context)

and then, change ,

AlertDialog.Builder builder = new AlertDialog.Builder(this);

TO

AlertDialog.Builder builder = new AlertDialog.Builder(context);

now it should work.hope this helps.

Cheers.



来源:https://stackoverflow.com/questions/4905050/sms-popup-alertdialog-does-not-show-as-i-get-a-sms-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!