我正在建立一个登录活动(Firebase,Google登录),该活动仅在该应用程序的首次运行时开始。问题在于,即使在身份验证过程完成之后,活动仍会继续产生。
我正在合并实时数据库,以便在注册新用户时将用户数据存储到数据库中。
我已经通过身份验证过程运行了调试器,该调试器未返回任何错误或意外行为。我还可以确认是否按预期查询了实时数据库。
应用程序是用Java和Kotlin的组合编写的。
这是我在应用程序的首次运行(Java)时在SignInActivity
中调用MainActivity
的方式
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Check if this is application's first run
sharedPreferences = getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
startActivity(new Intent(MainActivity.this, SignInActivity.class));
}
@Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("first", true)) {
startActivity(new Intent(MainActivity.this, SignInActivity.class));
sharedPreferences.edit().putBoolean("first", false).apply();
}
}
这是开始验证过程的Kotlin函数
private fun authenticateWithGoogle(account: GoogleSignInAccount?) {
if (account != null) {
val credential: AuthCredential = GoogleAuthProvider.getCredential(account.idToken, null)
firebaseAuth.signInWithCredential(credential).addOnCompleteListener{
if (it.isSuccessful) {
databaseReference.addValueEventListener(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {}
override fun onDataChange(dataSnapshot: DataSnapshot) {
databaseReference.child(account.id!!)
val userModel: UserModel? = dataSnapshot.getValue(UserModel::class.java)
if (userModel == null) {
databaseReference.child(account.id!!).setValue(UserModel(account.id, account.displayName, account.email))
startActivity(Intent(this@SignInActivity, MainActivity::class.java))
}
startActivity(Intent(this@SignInActivity, MainActivity::class.java))
}
})
}
}
}
}
从MainActivity
到SignInActivity
的初始转换之后,身份验证过程在按下按钮时开始。函数authenticateWithGoogle
将按预期方式被调用,并查询数据库以获取是否存在用户的信息。如果用户存在,则只需过渡回MainActivity
,否则,将其数据存储到数据库中,然后过渡至MainActivity
。
这时,应将用于存储MainActivity
中第一次运行状态的共享首选项设置为false,但显然不是,因此,为什么再次调用SignInActivity
。
任何帮助将不胜感激。
答案 0 :(得分:0)
我按照shubham-vashisht的建议以不同的方式解决了这个问题。
所以,这是我的做法:
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Check if it's application's first run
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean state = sharedPreferences.getBoolean("firstrun", false);
if (!state) {
Editor editor = sharedPreferences.edit();
editor.putBoolean("firstrun", true);
editor.apply();
startActivity(new Intent(MainActivity.this, SignInActivity.class));
}
}