Android MVVM - 如何在ViewModel中引用Activity

时间:2018-01-23 09:53:17

标签: android mvvm viewmodel android-lifecycle

MVVM架构,

这是我的观点(活动):

private MyApp app;
private MainActivityVM viewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MyApp) this.getApplication();
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

MainActivityVM.Factory factory = new MainActivityVM.Factory(app);

final MainActivityVM model = ViewModelProviders.of(this, factory)
.get(MainActivityVM.class);

viewModel = model;
binding.setVm(viewModel);
viewModel.onCreate();

和查看模型:

public class MainActivityVM extends AndroidViewModel implements ViewModel {

    public MainActivityVM(@NonNull Application application) {
        super(application);
    }

    @Override public void onCreate() {
         model = new MyService();
         model.getData(); /* <-- how do i pass the activity here? */
    }

    @Override public void onPause() { }

    @Override public void onResume() { }

    @Override public void onDestroy() { }

    public static class Factory extends ViewModelProvider.NewInstanceFactory {

        @NonNull
        private final Application mApplication;

        public Factory(@NonNull Application application) {
            mApplication = application;
        }

        @Override
        public <T extends android.arch.lifecycle.ViewModel> T create(Class<T> modelClass) {
            return (T) new MainActivityVM(mApplication);
        }
    }
}

和型号:

public class myService{

    public getData(){
        if(permissionacquired(){
            getdata()
        }else{
            requestPermission();
        }
    }

    private void requestPermission() {
        PermissionKey permKey = new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, PermissionType.READ);
        HealthPermissionManager pmsManager = new HealthPermissionManager(mStore);
        try {
            // Show user permission UI for allowing user to change options

            /* BELOW CODE REQUIRE Activity reference to PASS */

            pmsManager.requestPermissions(Collections.singleton(permKey), MainActivity.this).setResultListener(result -> {

            /* ABOVE CODE REQUIRE Activity reference to PASS */

            Log.d(APP_TAG, "Permission callback is received.");
            Map<PermissionKey, Boolean> resultMap = result.getResultMap();

                if (resultMap.containsValue(Boolean.FALSE)) {
                    updateStepCountView("");
                    showPermissionAlarmDialog();
                } else {
                    // Get the current step count and display it
                    mReporter.start(mStepCountObserver);
                }
            });
        } catch (Exception e) { Log.e(APP_TAG, "Permission setting fails.", e); }
    }

}

编辑:如果您在我的模型中看到我的请求权限,则API要求传递活动 - 如何将活动引用传递给请求权限?

我有一个来自Model的获取权限方法。我的服务提供商的此获取权限方法需要活动,例如requestPermission(Activity)

所以在我的ModelView中,我有一个模型对象,它是来自另一个源的dataService。

然后,我如何在ViewModel中引用Activity,以便在我的ViewModel中调用model.requestPermission(Activity);

来自here的理解:

  

警告:ViewModel绝不能引用视图,生命周期或任何视图   可能包含对活动上下文的引用的类。

1 个答案:

答案 0 :(得分:0)

只要在onCreate()方法中需要权限,您就可以将带有权限请求的逻辑移到活动中,并将请求结果传递到viewModel中。