在我的应用程序中,我创建了一个名为call_action方法的方法,该方法支持允许用户拨打电话的运行时权限。我在片段类中实现了这个方法。现在在我的应用程序中,我已经多次将此方法用于活动和片段。我知道这样我必须在每个片段和活动中多次编写这段代码。但是我想用这个方法创建一个类,通过它我可以在活动和片段中调用这个方法。因为我在android开发和软件开发方面都很新。我没有得到逻辑如何做到这一点。这是我在Fragments中实现的代码
(*SKIP)
}
答案 0 :(得分:0)
你可以这样做
public class Permissions {
private Context mContext;
private Activity mActivity;
public Permissions(Context context, Activity mActivity){
this.mContext=context;
this.mActivity=mActivity;
}
public void call_action(){
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phoneNumber));
mContext.startActivity(callIntent);
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(mContext,android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
mActivity.requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
}
您必须将此方法保留在您请求权限的活动或片段中
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity().getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
在活动
中使用它Permissions p=new Permissions(this,this);
p.isPermissionGranted();
如果是碎片,
Permissions p=new Permissions(getActivity(),getActivity());
p.isPermissionGranted();