我有一个在Java中使用MVVM实现Google登录的问题。
在这里,你会看到Google提供的一段普通的示例代码:
问题:
在你的Activity中:
@Override
public void onCreate(Bundle savedInstanceState) {
/* Here is the Issue:
* Google Object is defined in View - Activity
* I would like to have Google Object defined in my ViewModel
*/
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
// when Google Button CLicked
@Override
public void onClick(View v) { signIn(); }
private void signIn() {
/* Here is the Issue:
* I have to get this process done in View Model
* so view will not reference any Google Object
*/
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Below will be processed in ViewModel
GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
问题:*见评论
所以我想到了以下的想法:
在Activity中:
// when Google Button CLicked
@Override
public void onClick(View v) { viewModel.loginGoogle(); }
private void subscribeUi() {
// register startActivityForResult Event to ViewModel and set this activity as receiver...
// viewModel.startActivityForResultEvent.setEventReceiver(this Activity)
// How to do this?
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// send the result to View Model
viewModel.onResultFromActivity(requestCode,resultCode,data);
// escallate to super
super.onActivityResult(requestCode, resultCode, data)
}
现在在ViewModel中:
public void viewModelOnCreate() {
// This is what i want: Google object defined in View Model
// but I dont know how to call startActivityForResult from here?
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
mGoogleSignInClient = GoogleSignIn.getClient(getApplication(), gso);
}
// triggered when login button pressed
public void loginGoogle(){
// send Trigger startActivityForResult(getGoogleSignInIntent(), GOOGLE_SIGN_IN) this event should be catch later in my Activity
// How to do this?
// maybe something like:
// startActivityForResultEvent.sendEvent( ActivityNavigation.startActivityForResult startActivityForResult(getGoogleSignInIntent(), GOOGLE_SIGN_IN)
}
public void onResultFromActivity(int requestCode, int resultCode, Intent data){
// do whatever needed here after received result from Google
// for example:
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
有任何想法如何实现这个? 一直在努力想办法解决这个问题... 感谢并非常感激您的帮助 :)
loginGoogle()
中不能将活动上下文作为参数传递吗? - Pavel Poley