好吧,我正在创建一个用于录制音频的应用程序,为此,我对该程序赋予了两个权限,使其可以完美运行。当用户获得许可时,我想播放和音频。但是我的代码在权限提示的同时播放音频。有人可以帮我吗?
这是我用于获取权限的功能: 私人void requestPermission(){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
在这里我使用这些功能并播放音频:
if(!checkPermission()){
requestPermission();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (isFirstRun) {
MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.instruction);
mediaPlayer1.start();
// Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_LONG).show();
getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).apply();
}
答案 0 :(得分:0)
您执行2个异步任务:requestPermission()并播放音频。 不要将代码与Thread.sleep()同步。
if(!checkPermission()){
//it is async call, you never know when result come.
requestPermission();
}
@Override
public void onRequestPermissionsResult(
final int requestCode,
@NonNull final String[] permissions,
@NonNull final int[] grantResults
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionGranted()) {
playMusic();
}
}
有了这个方法,您不需要'isFirsRun'变量。