0

I am trying to mute the phone's volume continuously in background using my application.

For the Purpose, I have created a service that mutes the volume, But the logcat show exception. Please help me figure it out .

public class MyService extends Service implements RecognitionListener {
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
private final int MY_PERMISSIONS_RECORD_AUDIO = 1;
String LOG_TAG="---------->";
SpeechRecognizer speech;
Intent recognizerIntent;
int maxVolume = 15;
Context context;

static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;

@Override
public void onCreate() {
    Toast.makeText(this, "SErivce Runnng", Toast.LENGTH_SHORT).show();
    Log.d("-------->","SErvice is Runnign");
    speech = SpeechRecognizer.createSpeechRecognizer(this);
    speech.setRecognitionListener(this);
    recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);

    Log.e("------------>","Running here");
    AudioManager audioManager=(AudioManager)context.getSystemService(context.AUDIO_SERVICE);
    audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
    Toast.makeText(context, "Set on Vibration", Toast.LENGTH_SHORT).show();
    Log.e("------------>","VIbration Set");


}

This is the logcat

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Ken White Aug 14 '17 at 02:51
  • Your problem is that you haven't initialized `context`. `getSystemService` is not static and needs a reference of a `Context`. Because `Service`s are `Context`s you do not need to define one, so just remove the line you defined it and `context.` from `context.getSystemService` – Stam Kaly Aug 14 '17 at 03:08

1 Answers1

0

You have not initialized context so, you got NullPointerException error in getSystemService.

You can try below any one for that:

onCreate() {
    context = getApplicationContext();
}

OR

getApplicationContext().getSystemService(context.AUDIO_SERVICE);

And one more thing that inside getSystemService bracket Context will be on proper case.

Sagar Chavda
  • 125
  • 1
  • 2
  • 12