我有Subcomponent
这样的应用
-------- ApplicationComponent ------------
| |
| |
| |
Service Component Activity Component
|
|
|
Fragment Component
一切正常,但我想做一件事。
Android M requires runtime permissions so I decided to create
控制器, something like helper class that will be injected into
片段or
活动
通用接口
public interface PermissionController {
boolean hasPermissionInManifest(String permissionName);
boolean isPermissionGranted(String permission);
/**
* Request permission for Android 6
*
* @param permission permission that is requested
* @param requestCode request code
* @return if user is going to be asked about permission so we need to handle callback, otherwise
* user was already asked or permission is not required cause of android lower version
*/
boolean requestPermission(int requestCode, String permission);
void requestPermissions(int requestCode, String... permissions);
}
来自不同实现的一种方法PermissionActivityManager
和PermissionFragmentManager
@Override
public boolean requestPermission(int requestCode, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (mContext.checkSelfPermission(permission)
!= PackageManager.PERMISSION_GRANTED) {
mContext.requestPermissions(new String[]{permission},
requestCode);
return true;
}
}
return false;
}
Fragment
实施
@Override
public boolean requestPermission(int requestCode, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(mFragment.getActivity(), permission)
!= PackageManager.PERMISSION_GRANTED) {
mFragment.requestPermissions(new String[]{permission},
requestCode);
return true;
}
}
return false;
}
希望你有个主意。
但是关于这个问题,我的FragmentComponent
是ActivityComponent
他们都有PermissionModule
@PerActivity
@Subcomponent(
modules = {
ActivityModule.class,
PermissionModule.class
})
public interface ActivityComponent {
Activity activity();
FragmentComponent fragmentComponent(FragmentModule module);
void inject(BaseActivity baseActivity);
void inject(MainAppActivity mainAppActivity);
}
适用于Fragment
@Subcomponent(
modules = {
FragmentModule.class,
ProviderModule.class,
PermissionModule.class
})
@PerFragment
public interface FragmentComponent {
Fragment fragment();
void inject(BaseFragment baseFragment);
}
除了注释和返回的实例之外,模块是相同的。
@PerFragment
@Module
public class PermissionModule {
@PerFragment
@Provides
PermissionController providePermissionController(Fragment fragment) {
return new PermissionFragmentManager(fragment);
}
}
@PerActivity
@Module
public class PermissionModule {
@PerActivity
@Provides
PermissionController providePermissionController(Activity activity) {
return new PermissionActivityManager(activity);
}
}
所以我的问题是 - 如果有任何方法来覆盖父组件中使用的provide
方法,或者有另一种方法来解决问题?
因为在我的情况下注入了PermissionActivityManager
。
答案 0 :(得分:1)
@Subcomponent
继承超级组件的所有绑定。在这种情况下,这是@ActivityScope
组件。
如果要控制继承的依赖项,则必须使用组件依赖项。组件依赖性允许您仅继承由提供方法指定的绑定。
如果您不想修改新的构建器,那么我建议使用@Named("activity")
和@Named("fragment")
注释来指定您要注入的权限处理程序的类型。您必须将其放在@Inject
带注释的字段和@Provides
带注释的方法上。