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

标签 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

最佳答案

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

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

onCreate() {
    context = getApplicationContext();
}


getApplicationContext().getSystemService(context.AUDIO_SERVICE);

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

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

相关文章:

android - 删除自动添加的字符到自定义 PhoneNumberTextWatcher (XXX) XXX-XXXX 时出现问题

android - 在 Bootstrap 3 上工作的 Bootstrap 所见即所得文本区域编辑器

android - 检查用户是否通过 Cognito 认证

java - Fresco - setDownsampleEnabled 真/假?

amazon-web-services - 用于为 Lex 转换 MP3 输入的 AWS Lambda 代码

android - Android显示在线音乐播放列表

javascript - 通过javascript获取音频文件的音量信息

android - 如何通过 Firebase 中的存储引用获取文件大小

python - 使用 Python 验证和转换音频文件的快速方法?

linux - 在 linux 中播放 wave 文件