在请求并授予权限后立即执行 ACTION_CALL 意图
Posted
技术标签:
【中文标题】在请求并授予权限后立即执行 ACTION_CALL 意图【英文标题】:Perform ACTION_CALL intent immediately after the permission was requested and granted 【发布时间】:2021-10-12 06:57:16 【问题描述】:我正在制作一个应该在单击按钮后拨打号码的应用程序。我要做的就是在第一个权限请求后立即执行操作。
//everything here is in an onClickListener
//number is already specified
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(String.format("tel:%s", Uri.encode(number))));
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
activity.startActivity(callIntent);
else
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) //if Api >= 23
if(activity.shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE))
//WHY THIS PERMISSION IS NEEDED
final String why_the_permission_is_needed = "why it is needed";
new AlertDialog.Builder(activity)
.setTitle("WHY THIS PERMISSION IS NEEDED")
.setMessage(why_the_permission_is_needed)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialogInterface, int i)
dialogInterface.dismiss();
)
.create().show();
ActivityCompat.requestPermissions(activity, new String[]Manifest.permission.CALL_PHONE, DIAL_PERMISSION_REQUEST_CODE);
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
activity.startActivity(callIntent);
之前发生的事情
ActivityCompat.requestPermissions(activity, new String[]Manifest.permission.CALL_PHONE, DIAL_PERMISSION_REQUEST_CODE);
完成剩下的代码
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
activity.startActivity(callIntent);
会被处决。这意味着用户必须单击一次按钮才能获得权限,然后再次单击才能实际执行意图,这是我不想要的。
还有
ActivityCompat.requestPermissions(activity, new String[]Manifest.permission.CALL_PHONE, DIAL_PERMISSION_REQUEST_CODE);
返回无效。
【问题讨论】:
【参考方案1】:您应该在您的活动上覆盖onRequestPermissionsResult
并处理请求的权限结果。为了能够重新调用您的流程,请在函数中声明您的点击侦听器算法,并在结果准备好时调用它:
button.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
performCall();
)
然后处理结果:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults)
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0)
if (requestCode == DIAL_PERMISSION_REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED)
performCall();
【讨论】:
以上是关于在请求并授予权限后立即执行 ACTION_CALL 意图的主要内容,如果未能解决你的问题,请参考以下文章