我有一个应用程序,它在首选项中有一个选项复选框,当它勾选时触发后台服务。该服务需要允许记录来自用户的音频,因此当用户选中该框时,我请求偏好活动本身的许可,并在授予权限后启动该服务。这是我的代码:
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()方法没有启动。请帮忙!感谢。
答案 0 :(得分:1)
requestPermissions
不是同步操作:它向用户显示必须批准权限的对话框。只有onRequestPermissionsResult()才能了解用户是否批准了该权限。
您应该将来电startService
移至onRequestPermissionsResult()
方法,并仅在请求获得批准后启动。
答案 1 :(得分:0)
我认为你必须要求服务许可。但是从我记忆中来看,这有点棘手。
您可能需要
检查服务中的权限
If it's denied: Display notification through activity and request permission
我会看看我是否可以挖掘出如何解决它。