gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:43:14 25 4
gpt4 key购买 nike

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

为此,我创建了一个服务来使音量静音,但是 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

最佳答案

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

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

onCreate() {
context = getApplicationContext();
}


getApplicationContext().getSystemService(context.AUDIO_SERVICE);

在getSystemService括号Context中的另一件事将是在适当的情况下。

关于android - 如何在Android中静音手机的音量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45666802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com