1

Я пытаюсь добиться чего-то довольно простого с последних нескольких дней, но я этого не делал.Запуск активности автоматически после входа в систему Google - Android Studio

В основном, я использовал образец приложения от Google Developers для создания процесса входа в систему для своего приложения. Мне удалось войти в систему от Google, когда нажата кнопка входа в систему, а также узнать, был ли пользователь уже зарегистрирован и прошел проверку подлинности моего приложения.

Что я хочу сделать следующее: когда пользователь запускает мое приложение и уже вошел в систему, я хочу пропустить экран входа в систему и автоматически перейти к следующему действию.

Я сделал кучу тестов, но я не буду публиковать все, что я пробовал здесь, потому что иногда это было довольно грязно. Вот код, который я использовал на данный момент:

Мой MainActivity.java:

public class MainActivity extends AppCompatActivity implements 
     GoogleApiClient.OnConnectionFailedListener, 
     View.OnClickListener { 

    private static final String TAG = "SignInActivity"; 
    private static final int RC_SIGN_IN = 9001; 

    private GoogleApiClient mGoogleApiClient; 
    private ProgressDialog mProgressDialog; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Button listeners 
     findViewById(R.id.sign_in_button).setOnClickListener(this); 

     // [START configure_signin] 
     // Configure sign-in to request the user's ID, email address, and basic 
     // profile. ID and basic profile are included in DEFAULT_SIGN_IN. 
     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
       .requestEmail() 
       .build(); 
     // [END configure_signin] 

     // [START build_client] 
     // Build a GoogleApiClient with access to the Google Sign-In API and the 
     // options specified by gso. 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) 
       .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
       .build(); 
     // [END build_client] 

     // [START customize_button] 
     // Customize sign-in button. The sign-in button can be displayed in 
     // multiple sizes and color schemes. It can also be contextually 
     // rendered based on the requested scopes. For example. a red button may 
     // be displayed when Google+ scopes are requested, but a white button 
     // may be displayed when only basic profile is requested. Try adding the 
     // Scopes.PLUS_LOGIN scope to the GoogleSignInOptions to see the 
     // difference. 
     SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button); 
     signInButton.setSize(SignInButton.SIZE_STANDARD); 
     signInButton.setScopes(gso.getScopeArray()); 
     // [END customize_button] 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); 
     if (opr.isDone()) { 
      // If the user's cached credentials are valid, the OptionalPendingResult will be "done" 
      // and the GoogleSignInResult will be available instantly. 
      Log.d(TAG, "Got cached sign-in"); 
      GoogleSignInResult result = opr.get(); 
      handleSignInResult(result); 
     } else { 
      // If the user has not previously signed in on this device or the sign-in has expired, 
      // this asynchronous branch will attempt to sign in the user silently. Cross-device 
      // single sign-on will occur in this branch. 
      showProgressDialog(); 
      opr.setResultCallback(new ResultCallback<GoogleSignInResult>() { 
       @Override 
       public void onResult(GoogleSignInResult googleSignInResult) { 
        hideProgressDialog(); 
        handleSignInResult(googleSignInResult); 
       } 
      }); 
     } 
    } 

    // [START onActivityResult] 
    @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) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
      handleSignInResult(result); 
     } 
    } 
    // [END onActivityResult] 

    // [START handleSignInResult] 
    private void handleSignInResult(GoogleSignInResult result) { 
     Log.d(TAG, "handleSignInResult:" + result.isSuccess()); 
     if (result.isSuccess()) { 
      // Signed in successfully, show authenticated UI. 
      GoogleSignInAccount acct = result.getSignInAccount(); 
      updateUI(true); 

      Intent myIntent = new Intent(MainActivity.this, SplashScreen.class); 
      startActivity(myIntent); 
      finish(); 
     } else { 
      // Signed out, show unauthenticated UI. 
      updateUI(false); 
     } 
    } 
    // [END handleSignInResult] 

    // [START signIn] 
    private void signIn() { 
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
     startActivityForResult(signInIntent, RC_SIGN_IN); 
    } 
    // [END signIn] 

    // [START signOut] 
    private void signOut() { 
     Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
       new ResultCallback<Status>() { 
        @Override 
        public void onResult(Status status) { 
         // [START_EXCLUDE] 
         updateUI(false); 
         // [END_EXCLUDE] 
        } 
       }); 
    } 
    // [END signOut] 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     // An unresolvable error has occurred and Google APIs (including Sign-In) will not 
     // be available. 
     Log.d(TAG, "onConnectionFailed:" + connectionResult); 
    } 

    private void showProgressDialog() { 
     if (mProgressDialog == null) { 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage(getString(R.string.loading)); 
      mProgressDialog.setIndeterminate(true); 
     } 

     mProgressDialog.show(); 
    } 

    private void hideProgressDialog() { 
     if (mProgressDialog != null && mProgressDialog.isShowing()) { 
      mProgressDialog.hide(); 
     } 
    } 

    private void updateUI(boolean signedIn) { 
     if (signedIn) { 
      findViewById(R.id.sign_in_button).setVisibility(View.GONE); 
     } else { 
      findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); 
     } 
    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.sign_in_button: 
       signIn(); 
       break; 
     } 
    } 
} 

Так что мой вопрос: как и где я должен поставить мои намерения, чтобы перейти к следующему действию?

Intent myIntent = new Intent(MainActivity.this, SplashScreen.class); 
      startActivity(myIntent); 

Большое вам спасибо за помощь! Скажите мне, если вам нужны дальнейшие подробности или объяснения.

+1

Сохранить в настройках параметров файла приложения а boolean означает, что пользователь зарегистрирован или нет. Поэтому, когда вы начинаете аганы, просто проверьте, что bool, если это ложно, введите регистрационную форму, если нет процедуры, в которой вы хотите пойти – Raskayu

+0

В состоянии 'if (requestCode == RC_SIGN_IN)' добавить свой 'намерение'. Или введите 'if (result.isSuccess())'. – Dhruv

ответ

0

Поместите свой класс активности, который вы хотите показать после пропуска экрана входа в систему YourClassAfterLogin.class

private void handleSignInResult(GoogleSignInResult result) { 
      Log.d(TAG, "handleSignInResult:" + result.isSuccess()); 
      if (result.isSuccess()) { 
       // Signed in successfully, show authenticated UI. 
       GoogleSignInAccount acct = result.getSignInAccount(); 
       updateUI(true); 

       Intent myIntent = new Intent(MainActivity.this, YourClassAfterLogin.class); 
       startActivity(myIntent); 
       finish(); 
      } else { 
       // Signed out, show unauthenticated UI. 
       updateUI(false); 
      } 
     } 
0
// [START handleSignInResult] 
private void handleSignInResult(GoogleSignInResult result) { 
    Log.d(TAG, "handleSignInResult:" + result.isSuccess()); 
    if (result.isSuccess()) { 
     // Signed in successfully, show authenticated UI. 
     GoogleSignInAccount acct = result.getSignInAccount(); 
     updateUI(true); 

     Intent myIntent = new Intent(MainActivity.this, SplashScreen.class); 
     startActivity(myIntent); 
     finish(); 
    } else { 
     // Signed out, show unauthenticated UI. 
     updateUI(false); 

в isSuccess вы можете поместить свое намерение ..

Смежные вопросы