如何解决onActivityResult 已弃用,如何处理 android(Java) 片段中的谷歌登录?
@Override **//depricated**
public void onActivityResult(int requestCode,int resultCode,@Nullable @org.jetbrains.annotations.Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_OAUTH_REQUEST_CODE) {
insertAndVerifySession();
}
}
}
GoogleSignIn.requestPermissions(
fragment,REQUEST_OAUTH_REQUEST_CODE,GoogleSignIn.getLastSignedInAccount(context),fitnessOptions);
Fragment 中 GoogleSignIn 的 onActivityResult 的替代方法是什么?
解决方法
正如 here 所说,您可以通过调用 getSignInIntent
ActivityResultLauncher<Intent> exampleActivityResult= registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(result.getData());
handleSignInResult(task);
}
}
});
//call
exampleActivityResult.launch(mGoogleSignInClient.getSignInIntent());
,
有一种新方法,熟悉 AndroidX 中的 ActivityResultContracts
类。 HERE你有一些解释和教程
在活动结果被弃用后,我们使用 someActivityResultLauncher.launch
在 Java 中:
Intent intent = new Intent(this,Example.class);
someActivityResultLauncher.launch(intent);
在 Kotlin 中:
val intent = Intent(this,Example::class.java)
resultLauncher.launch(intent)
为了获取结果,我们使用 registerForActivityResult
在 Java 中:
ActivityResultLauncher<Intent> exampleActivityResult= registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
// There are no request codes in this method
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
}
}
});
在 Kotlin 中:
var exampleActivityResult= registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
// There are no request codes in this method
val data: Intent? = result.data
}
}
,
其中一种方法是注册ActivityResultContracts,我在我的项目中使用了类似的代码:
//declare ActivityResultLauncher<Intent>
ActivityResultLauncher<Intent> ResultLauncher;
在 onAttach 或 onCreate 中进行赋值
ResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
...//do stuff on result here
/*
There are no request codes
You can put request code in extra and Unpack it as your string/int e.t.c
Intent data = result.getData();
assert data != null;
String req_code = data.getStringExtra("reqCode");
if(req_code.equal(REQUEST_OAUTH_REQUEST_CODE){
...do stuff
}
*/
}
});
启动活动只需使用 .launch (intent)
Intent intent = new Intent(getContext(),SomeClass.class);
ResultLauncher.launch(intent);
您也可以查看此 answer 以了解类似问题以及如何在 Kotlin/Java 中处理它
希望有帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。