Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to fire an intent from a ContentObserver

I'd like to fire an intent from the onChange() method of my ContentObserver. I'm trying to get a Service to run when an SMS is sent, hence the ContentObserver, but Eclipse is giving me errors because it cannot resolve "context". Below is my code for the class.

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();
    }
    }
}
like image 312
Matt Harris Avatar asked Jan 12 '12 02:01

Matt Harris


1 Answers

Is there some reason you cant just pass the application context into the SmsObserver when the instance is created?

public class SmsObserver extends ContentObserver {

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

Invoking class:

new SmsObserver(handler, getApplicationContext())
like image 84
Jivings Avatar answered Sep 25 '22 06:09

Jivings