我可以在contentObserver中创建Alert和Toast吗?

时间:2012-03-30 05:08:24

标签: android alert toast

我无法编写代码来在sms的ContentObserver中创建警报和吐司。我无法获取ContentObserver的上下文。有人请帮帮我。提前谢谢。

 MyObserver yourObserver = new MyObserver(new Handler());

        ContentResolver contentResolver = this.getContentResolver();
        contentResolver.registerContentObserver(Uri.parse("content://sms"),true, yourObserver);

&安培;

class YourObserver extends ContentObserver {

    //Context context = new ContentObserver()
    AlertDialog.Builder builder;
    AlertDialog alert;
    public YourObserver(Handler handler) {
        super(handler);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
       Toast.makeText(???,"SENT..!!", Toast.LENGTH_LONG).show();
        System.out.println("Hey =++++++++++++++++++++++_______+++++++++++++++++++++++++++++");
        builder = new AlertDialog.Builder(???);
        builder.setMessage("Are you sure??");
        builder.setCancelable(false);
        builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(???, "Okay",Toast.LENGTH_LONG).show();
            }
        });

        builder.setNegativeButton("No",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                alert.cancel(); 
            }
        });
        alert = builder.create();
        alert.show();
    }
}

2 个答案:

答案 0 :(得分:3)

您可以使用handler.post()来显示Toast。

public SMSSentObserver(Handler handler, Context context) {
    super(handler);
    this.handler = handler;
    m_Context = context;
}

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    handler.post(new Runnable() {

        @Override
        public void run() {

            Toast.makeText(m_Context, "Toast", Toast.LENGTH_SHORT).show();
        }
    });

答案 1 :(得分:2)

您可以将活动的上下文传递给ContentObserver类,

ContentResolver observer = this.getContentResolver();
        observer.registerContentObserver(SMS_URI, true,
                                   new MyObserver(new Handler(), this));

MyObserver类中的使用上下文

   Activity mActivity;
    public MyContentObserver(Handler handler, Activity mActivity) {
        super(handler);
        this.mActivity= mActivity;
    }