繁体   English   中英

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

[英]How to mute Phone's Volume in Android?

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

为此,我创建了一个使音量静音的服务 ,但logcat show exception 请帮我弄清楚。

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

您尚未初始化上下文,因此在getSystemService中收到NullPointerException错误。

您可以尝试以下任何一种方法:

onCreate() {
    context = getApplicationContext();
}

要么

getApplicationContext().getSystemService(context.AUDIO_SERVICE);

在getSystemService括号内还有另外一件事。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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