0

I want to implement a audio manager, but I can't quite figure out which class to put it in. If I put in onCreate, I can't refer to it, but if I put it in my Broadcast Receiver class, it can't find the getBaseContext() method. In the code below, it can't find the getBaseContext() method:

class SmsFilter extends BroadcastReceiver {
private final String TAG = "SMS";
public final AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
@Override
public void onReceive(Context context, Intent intent) {
    if (intent != null){
        String action = intent.getAction();
        if (action.equals("android.provider.Telephony.SMS_RECEIVED")){
           Bundle extras = intent.getExtras();
            if (extras != null){
                am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            }
        }
    }
}

}
rakeshdas
  • 2,363
  • 5
  • 20
  • 28

1 Answers1

3

First, it is highly unlikely that you need to use the getBaseContext() method.

Second, you never try to use a Context from an initializer.

Third, a manifest-registered BroadcastReceiver -- and most SMS_RECEIVED receivers are registered in the manifest -- is used for just one onReceive() call, so there is no value in having an AudioManager be a data member of the class, rather than just a local variable in the onReceive() method.

You can call getSystemService() on the Context that is passed into onReceive(), perhaps inside the if (extras != null) block.

In other words:

class SmsFilter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent != null){
        String action = intent.getAction();

        if (action.equals("android.provider.Telephony.SMS_RECEIVED")){
           Bundle extras = intent.getExtras();

            if (extras != null){
                AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
                am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            }
        }
    }
}
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • If I call it inside the `if (extras != null)` block, I get an error on `getSystemService` : `Error:(59, 67) error: non-static method getSystemService(String) cannot be referenced from a static context` – rakeshdas Aug 31 '14 at 20:49
  • @CommonsWare Please do you think you could give some ideas in this question : http://stackoverflow.com/questions/25598696/recommended-way-order-to-read-data-from-a-webservice-parse-that-data-and-inse – Axel Sep 01 '14 at 04:08