从 android 个应用调用并进行权限检查

Calling from android app and permission check

我有一个带有图像按钮的适配器。 OnClick ImageButton 我想拨打我正在解析的联系电话。这里要求我添加权限检查。我在这个阶段得到 class 转换异常。请帮忙。

这是我的代码:

  holder.call.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ActivityCompat.checkSelfPermission(context, permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
           ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
              } else {
                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:"+storePro.getStoreContact()));
                    callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(callIntent);
                }

            }
        });

我得到的异常是:

FATAL EXCEPTION: main 
java.lang.ClassCastException: com.example.project.app.AppController cannot be cast to android.app.Activity

粘贴此代码

 if (ContextCompat.checkSelfPermission(Activity.this,
                            Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED ) {


                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale(Activity.this,
                                Manifest.permission.CALL_PHONE)) {

                            // Show an expanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                        } else {

                            // No explanation needed, we can request the permission.

                            ActivityCompat.requestPermissions(Activity.this,
                                    new String[]{Manifest.permission.CALL_PHONE},
                                    2);


                        }
                    }
                    else {
                       // do what you want

                   }
FATAL EXCEPTION: main 
java.lang.ClassCastException: com.example.project.app.AppController cannot be cast to android.app.Activity

这意味着您向适配器传递了错误的 context 值。您应该将 activity 上下文传递给它。