我有一個應用程序,它有一個選項複選框,當它打勾時觸發後臺服務。該服務需要權限來記錄來自用戶的音頻,因此當用戶選中該框時,我請求了首選項活動本身的許可,並在授予權限後啓動該服務。這是我的代碼:Android:從活動請求許可並啓動服務不授予服務許可?
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Log.e("voice trigger button clicked 1") ;
CheckBoxPreference cpb=(CheckBoxPreference)findPreference("keyVoiceTrigger");
cpb.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
Context context=getActivity();
public boolean onPreferenceClick(Preference preference) {
Log.e("voice trigger button clicked 1") ;
int permissionCheck1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO);
//int permissionCheck2 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if ((permissionCheck1 == PackageManager.PERMISSION_DENIED)){
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, 1);
return false;
}
context.startService(new Intent(getActivity(), com.speechrecognition.android.speak.service.VoiceService.class));
return true;
}
});
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference lp = (ListPreference) pref;
if (mKeyMaxResults.equals(key)) {
updateSummaryInt(lp, R.plurals.summaryMaxResults, lp.getEntry().toString());
} else {
pref.setSummary(lp.getEntry());
}
}
}
現在,當我運行它要求允許錄製音頻的應用程序,該服務已啓動,但是當我檢查的權限裏面的服務:
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(),"yolololo",Toast.LENGTH_LONG).show();
Log.e(LOG_TAG,"service started");
// Check if user has given permission to record audio
int permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
if (permissionCheck1 == PackageManager.PERMISSION_GRANTED) {
runRecognizerSetup();
}
return super.onStartCommand(intent, flags, startId);
}
的方法runRecognizerSetup()不啓動。請幫忙!謝謝。
您無法從服務請求權限。 –