2012-01-12 42 views
7

我想從我的ContentObserveronChange()方法中引發意圖。我試圖讓SMS在發送時運行,因此ContentObserver,但Eclipse給我錯誤,因爲它無法解析「上下文」。以下是我的課程代碼。試圖激發ContentObserver的意圖

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(); 
    } 
    } 
} 

回答

11

是否有某些原因導致您無法在創建實例時將應用程序上下文傳遞到SmsObserver中?

public class SmsObserver extends ContentObserver { 

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

調用類:

new SmsObserver(handler, getApplicationContext()) 
+1

謝謝!這工作。 – 2012-01-12 16:37:07

+4

只是要小心,並通過應用程序上下文和_not_一個活動上下文! – espinchi 2013-10-08 20:51:08