I am using a Broadcast Receiver to receive a Broadcast when the phone boots up, and from there I’d like to register a PhoneStateListener and ContentObserver. Unfortunately it won’t let me use the setReceiver() method for the ContentObserver like in my main activity. There was a similar problem with PhoneStateListener and startService(), but I was able to use the passed context to make it work. This does not solve the problem for setReceiver. What is the correct way of calling this method?
By the way the error it gives is “The method setReceiver(SmsObserver) is undefined for the type Context”
My code:
public class BootReceiver extends BroadcastReceiver {
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
// Get the telephony manager
TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
// Create a new PhoneStateListener
PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_IDLE) {
Intent update = new Intent(mContext,
UpdateService.class);
mContext.startService(update);
}
}
@Override
public void onDataActivity(int direction) {
if (direction == TelephonyManager.DATA_ACTIVITY_NONE) {
Intent update = new Intent(mContext,
UpdateService.class);
mContext.startService(update);
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
telephonyManager.listen(listener,
PhoneStateListener.LISTEN_DATA_ACTIVITY);
SmsObserver smsSentObserver = new SmsObserver(new Handler(), mContext);
//Unable to call this method
mContext.setReceiver(smsSentObserver);
}
}
Tactically, there is no
setReceiver()method anywhere in Android. IfSmsObserveris supposed to be aContentObserver, you would use aContentResolverandnotifyChange()to register it.Strategically, your code is useless, as your process can be terminated shortly after
onReceive()ends, making all this work moot.