开发者

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

开发者 https://www.devze.com 2023-02-08 11:26 出处:网络
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.

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.prov开发者_运维知识库ider.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();
            }
        }
    };    
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消