varuni varuni - 2 months ago 17
Android Question

Calling from android app and permission check

I have an adapter which has an image button. And

OnClick
on
ImageButton
i want to call on the contact number i am parsing. Here its asking me to add permission check. I am getting class cast exception in this stage. Please help.

This is my code:

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);
}

}
});


And the exception i am getting:

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

Answer

paste this code

 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

                   }
Comments