2017-08-14 73 views
0

我正在尝试使用我的应用程序将手机的音量连续静音。如何在Android中静音手机的音量?

为目的,我创建了一个服务是静音音量,但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 
+0

可能重复[什么是NullPointerException,以及如何解决它?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -it) –

+0

你的问题在于你没有初始化'context'。 'getSystemService'不是静态的,需要一个'Context'的引用。因为'服务'是'上下文',所以你不需要定义它,所以只需从'context.getSystemService'中删除你定义的行和'context.' –

回答

0

您还没有初始化的情况下是这样,你在getSystemService得到NullPointerException异常错误。

你可以试试下面的任何一个为:

onCreate() { 
    context = getApplicationContext(); 
} 

OR

getApplicationContext().getSystemService(context.AUDIO_SERVICE); 

还有一两件事,getSystemService支架上下文中会在适当的情况下。

+1

他不需要应用程序'Context','Service已经是'Context'了... –