尝试从ContentObserver触发意图(Intent)

7

我想从 ContentObserveronChange() 方法中触发一个意图。我正在尝试在短信发送时运行一个服务,因此使用了 ContentObserver,但是Eclipse错误提示无法解析“context”。以下是该类的代码。

public class SmsObserver extends ContentObserver {

public SmsObserver(Handler handler) {
    super(handler);
    // TODO Auto-generated constructor stub
}

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);

    // On outgoing SMS, do this
    Intent update = new Intent(context, UpdateService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, update, 0);

    try {
        pendingIntent.send();
    } catch (CanceledException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}
1个回答

13

你为什么不能在创建SmsObserver实例时将应用程序上下文直接传递进去呢?

public class SmsObserver extends ContentObserver {

    private Context context;
    public SmsObserver(Handler handler, Context context) {
        super(handler);
        this.context = context;
    }
}

调用的类:

new SmsObserver(handler, getApplicationContext())

4
请注意,传递应用程序上下文而不是活动上下文! - espinchi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接