Reputation: 2543
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);
}
}
}
}
}
Upvotes: 0
Views: 1581
Reputation: 1006789
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);
}
}
}
}
Upvotes: 3