如何在Android中静音手机的音量?

时间:2017-08-14 02:48:45

标签: android audio

我正在尝试使用我的应用程序在后台连续静音手机音量

出于目的,我创建了一个静音音量的服务,但 logcat显示异常。 请帮我搞清楚。

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");


}

这是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

1 个答案:

答案 0 :(得分:0)

您尚未初始化上下文,因此getSystemService中出现 NullPointerException 错误。

你可以尝试以下任何一个:

onCreate() {
    context = getApplicationContext();
}

getApplicationContext().getSystemService(context.AUDIO_SERVICE);

getSystemService括号中的另一个内容是适当的情况。