2017-08-14 74 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'了... –