短信弹出:当我收到短信时,AlertDialog不显示

时间:2011-02-05 04:02:15

标签: android sms alertdialog

我看到很多应用程序都在做短信弹出窗口。为什么我不能让我的应用程序工作?如果收到短信,我希望它能在屏幕上弹出。

这是我的代码:

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 个答案:

答案 0 :(得分:0)

我认为问题在于上下文对象。从,

  

onReceive(上下文上下文,意图意图)

您应该将onRecive中收到的上下文传递给..

  

private void displayAlert(Context context

然后, 改变,

  

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

  

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

现在它应该起作用了。这有帮助。

干杯。