如果您仍希望能够模拟权限访问/请求,您可以创建类似于
PermissionHandler
的东西,但只在您的视图类中引用它。例如 -
接口:
public interface PermissionsHandler {
boolean checkHasPermission(AppCompatActivity activity, String permission);
void requestPermission(AppCompatActivity activity, String[] permissions, int requestCode);
}
生产实现:
public class PermissionsHandlerAndroid implements PermissionsHandler {
@Override
public boolean checkHasPermission(AppCompatActivity activity, String permission) {
return ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED;
}
@Override
public void requestPermission(AppCompatActivity activity, String[] permissions, int requestCode){
ActivityCompat.requestPermissions(activity, permissions, requestCode);
}
}
模拟的类(例如,用于测试并确保您的活动正确处理 onRequestPermissionsResult
)
public class PermissionsHandlerMocked implements PermissionsHandler {
@Override
public boolean checkHasPermission(AppCompatActivity activity, String permission) {
return false;
}
@Override
public void requestPermission(AppCompatActivity activity, String[] permissions, int requestCode){
int[] grantResults = new int[permissions.length];
for (int i = 0; i < permissions.length; i++) {
grantResults[i] = PackageManager.PERMISSION_GRANTED
}
activity.onRequestPermissionResult(requestCode, permissions, grantResults);
}
}
然后在您的活动中:
PermissionsHandler permissionsHandler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permissionsHandler = Injection.providePermissionsHandler();
}
@Override
void requestLocationPermission() {
permissionsHandler.requestPermision((AppCompatActivity) this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_LOCATION};
}
fobo66,你总是可以使视图实现更通用的方法,比如checkLocationPermissionGranted()
和requestLocationPermission()
。然后你的视图实现可以根据需要引用活动,并且你的Presenter永远不必触及活动引用。