简体   繁体   中英

How to mute Phone's Volume in Android?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM