我有一个问题,所以我成功地在Google上实现了Sing in,但是如果我已经登录并且不知道该怎么做,我想跳过登录活动,我已经在互联网上找到了解决方案但我无法实现它...有人可以帮助我吗?我是Android新手。
先谢谢您。
代码:
package com.example.ipill;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static final int RC_SIGN_IN = 0;
private static final String TAG = "LogIn";
private GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
TextView name;
FirebaseAuth auth;
Context context = null;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
private FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
name =findViewById(R.id.name);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
auth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
});
fetchLocation();
statusCheck();
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
} catch (ApiException e) {
Log.w(TAG, "Google sign in failed", e);
}
handleSignInResult(task);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
}
// ...
}
});
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
System.out.println("TEST");
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(MainActivity.this,Menu.class);
startActivity(intent);
finish();
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
private void fetchLocation() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Required Location Permission")
.setMessage("You have to give this permission to acess this feature")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create()
.show();
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
//Check location
public void statusCheck() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
//If location is OFF -> Pop UP message to active it
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
答案 0 :(得分:1)
首选逻辑是如果您拥有HomeActivity(在清单中将其设置为启动器活动)
在HomeActivity onCreate中:
if(FirebaseAuth.getInstance().getCurrentUser==null)
{
startActivity(new Intent(this,MainActivity.class));
}
因此,每次启动HomeActivity时。如果user为null,则将用户重定向到MainActivity。 如果用户已登录,则可以重定向到HomeActivity。 会话由Firebase本身管理。无需创建SharedPreferences。
答案 1 :(得分:0)
每次登录或登录过程完成后,请保存用户数据(例如用户名, 电子邮件,移动设备等。无论您希望在应用程序使用过程中何时使用它),都可以使用共享首选项或您希望在应用程序中使用其他数据库。
在初始屏幕上,检查用户保存的数据是否可用,如果可用,则跳过登录活动并将用户转到直接的家庭活动,否则请让用户先登录。
答案 2 :(得分:0)
如果您有Splash_Screen
。您可以每次检查Session
。如果您有会话,则不需要显示Login
页面,或者如果您没有Session
,则可以将用户转发到Login
页面。
为您的SharedPreferences
做一堂课:
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
在“ onActivityResult”中:
private Session session;//global variable
然后在onCreate()
中对其进行初始化:
session = new Session(cntx); //in oncreate
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
// from data you can get username
} catch (ApiException e) {
Log.w(TAG, "Google sign in failed", e);
}
handleSignInResult(task);
}
}
现在,您可以在Preference
屏幕上检查此Splash
:
首先在Preferences
屏幕上启动Splash
。然后从onCreate
拨打电话:
if(prefs.getUserName ! = null && prefs.getUserName != ""){
//Go to the your app main screen
}else{
// Go to the login screen
}