我想仅在用户授予存储权限时才从活动中启动片段。我的主要活动布局如下所示
VerticalAlignment
现在,在主要活动开始时会显示此布局。我设置代码以获得存储权限。并希望用我的片段布局替换这个布局,但只有在授予存储权限后,它才能正常工作,我的片段正在加载一切正常,除了我的片段在授予权限之前启动。有没有办法在权限函数上设置回调方法,只有在授予权限的情况下才启动片段?
我的onCreate方法看起来像
Top
我的获取权限方法如下所示
<Border BorderThickness="1" Margin="44,135,0,0" BorderBrush="#FF000000" HorizontalAlignment="Left" VerticalAlignment="Top">
<Image x:Name="imageHelmet" HorizontalAlignment="Left" Height="116" Margin="-1" VerticalAlignment="Top" Width="127" MouseEnter="helmet_MouseEnter"/>
</Border>
当我授予权限时,getPermission返回true,但是当应用程序首次运行时,它会在获取getPermission()方法的结果之前启动片段,当我第二次运行应用程序时,它会显示片段布局。 / p>
答案 0 :(得分:1)
您应该使用onRequestPermissionsResult
来处理结果:
private static final int REQUEST_CODE = 404;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
// Your code
if (savedInstanceState == null) {
tryToOpenHomeFragment();
}
}
private void tryToOpenHomeFragment() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
showHomeFragment();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
showHomeFragment();
} else {
// Permission was not granted
}
}
}
private void showHomeFragment() {
HomeFragment fragment = new HomeFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.root_container, fragment)
.commit();
}
答案 1 :(得分:0)
您需要做的是:授予权限后,打开。
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
HomeFragment fragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.root_container, fragment).commit();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
按照授予检查权限的https://developer.android.com/training/permissions/requesting上的示例进行操作。