无法保存Firebase活动状态

时间:2018-06-19 14:49:02

标签: java android firebase firebase-authentication

function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U'); 
$u_modified_time = get_the_modified_time('U'); 
if ($u_modified_time >= $u_time + 86400) { 
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a'); 
$custom_content .= '<p class="last-updated">Last updated on '. 
$updated_date . ' at '. $updated_time .'</p>';  
} 

$content .= $custom_content;
return $content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );

此文件是配置文件设置活动

The Main Dashboard File of the App
Dashboard.java
package com.abc.farmersconsult;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

 public class RegisterActivity extends AppCompatActivity {


  private EditText editText;
  private Spinner spinner;
  FirebaseAuth mAuth;
  DatabaseReference userRef;

  FirebaseAuth.AuthStateListener mAuthStateListener;

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

    spinner = findViewById(R.id.spinner_countries);
    spinner.setAdapter(new ArrayAdapter<String>(this, 
 android.R.layout.simple_spinner_dropdown_item, 
  CountryData.countrynames));

    editText = findViewById(R.id.Phone);


    findViewById(R.id.Continue).setOnClickListener(new View.OnClickListener() 
   {
        @Override
        public void onClick(View v) {
            String code = 
  CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];

            String number = editText.getText().toString().trim();

            if (number.isEmpty() || number.length() < 10) {
                editText.setError("Valid number is required");
                editText.requestFocus();
                return;
            }

            String phoneNumber = "+" + code + number;

            Intent intent = new Intent(RegisterActivity.this, 
            VerifyPhone.class);
            intent.putExtra("phonenumbers", phoneNumber);
            startActivity(intent);

        }
       });
      }


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

    FirebaseUser currentUser=FirebaseAuth.getInstance().getCurrentUser();
    UpdateUI(currentUser);
  /*
     if (FirebaseAuth.getInstance().getCurrentUser() != null) {
        Intent intent = new Intent(this, Dashboard.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 
        Intent.FLAG_ACTIVITY_CLEAR_TASK);

        startActivity(intent);
    } */





   }

   private void UpdateUI(FirebaseUser currentUser) {
      if(currentUser!=null){
        Intent intent=new Intent(RegisterActivity.this, Dashboard.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| 
     Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }




    }
   }

RegisterPhone.java

package com.abc.farmersconsult;

SetupProfile.java
public class SetupProfile extends AppCompatActivity {
EditText editText;
Button button;
private FirebaseAuth mAuth;
DatabaseReference mUserRef;
String CurrentUserID;

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

    mAuth=FirebaseAuth.getInstance();
    CurrentUserID=mAuth.getCurrentUser().getUid();

    mUserRef=FirebaseDatabase.getInstance().getReference().
    child("Users").child(CurrentUserID);
    button=(Button)findViewById(R.id.save);
    editText=(EditText)findViewById(R.id.editText);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveAccount();
        }
    });
}

private void saveAccount() {

String username=editText.getText().toString().trim();
if(username.isEmpty()){
    Toast.makeText(this,"Enter valid name", Toast.LENGTH_LONG).show();
}
else{
    HashMap userMap= new HashMap();
    userMap.put("username",username);
    mUserRef.updateChildren(userMap).addOnCompleteListener(new 
    OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
         if(task.isSuccessful()){
             Toast.makeText(SetupProfile.this,"Account 
       create",Toast.LENGTH_LONG).show();
             sendHome();
         }
        }
    });
}

}

    private void sendHome() {
     Intent intent=new Intent(SetupProfile.this, Dashboard.class);



    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
    Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    finish();
    }


     }



This File Contains Verification of the OTP file
VerifyPhone.java
public class VerifyPhone extends AppCompatActivity {

   private String verificationId;
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener mAuthStateListener;
    private EditText editText;
    DatabaseReference userRef;
   private ProgressBar progressBar;

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

    mAuth = FirebaseAuth.getInstance();

    progressBar = findViewById(R.id.progressBar);
    editText = findViewById(R.id.verify_otp);

      String phonenumber = getIntent().getStringExtra("phonenumbers");
      sendVerificationCode(phonenumber);

       findViewById(R.id.Sign).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String code = editText.getText().toString().trim();

            if (code.isEmpty() || code.length() < 6) {

                editText.setError("Enter code...");
                editText.requestFocus();
                return;
            }
            verifyCode(code);
        }
       });

      }













   private void verifyCode(String code) {
    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
    signInWithCredential(credential);
   }

     private void checkExistence() {

    }

    private void SendUserToSetup() {
    Intent intent=new Intent(VerifyPhone.this, SetupProfile.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
    }




       private void signInWithCredential(PhoneAuthCredential credential) {
       mAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if (task.isSuccessful()) {
                        final String current_userid=mAuth.getCurrentUser().getUid();
                        userRef= FirebaseDatabase.getInstance().getReference().child("Users");
                        userRef.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {


                                if(!dataSnapshot.hasChild(current_userid)){
                                    SendUserToSetup();
                                }



                                else {
                                    Intent intent = new Intent(VerifyPhone.this, Dashboard.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                                    startActivity(intent);
                                }

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });





                    } else {
                        Toast.makeText(VerifyPhone.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            });
}


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



}

private void sendVerificationCode(String number) {
    progressBar.setVisibility(View.VISIBLE);
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            number,
            60,
            TimeUnit.SECONDS,
            TaskExecutors.MAIN_THREAD,
            mCallBack
    );

}

private PhoneAuthProvider.OnVerificationStateChangedCallbacks
        mCallBack = new 
 PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

    @Override
    public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken 
forceResendingToken) {
        super.onCodeSent(s, forceResendingToken);
        verificationId = s;
    }

    @Override
     public void onVerificationCompleted(PhoneAuthCredential credential) {

        String code = credential.getSmsCode();
        if (code != null) {
            editText.setText(code);
            verifyCode(code);
        }
        signInWithCredential(credential);

    }


    @Override
    public void onVerificationFailed(FirebaseException e) {
        Toast.makeText(VerifyPhone.this, e.getMessage(), 
     Toast.LENGTH_LONG).show();
      }
    };
   }

有四个文件,分别是Dashboard.java,VerifyPhone.java,RegisterPhone.java和SetupProfile.java,我能够成功执行OTP身份验证并将其移至Setup Profile Activity,然后将应用程序移至Dashboard.java

问题是,如果我退出以Dashboard.java开头的应用程序,它将无法继续进行配置文件设置活动。 每当我执行登录时,它都会直接登录到信息中心,我希望该应用在打开应用后恢复未完成的帐户设置

1 个答案:

答案 0 :(得分:0)

尝试理解您的代码(需要改进如何在StackOverflow中编写代码)之后,我认为问题是因为您只是在应用程序退出时忘记了注销。

即使您退出应用程序,Firebase也会保持您的用户登录状态。这就是为什么在您的RegisterActivity中,结果始终会实现的原因,因为FirebaseUser中始终有一个FirebaseAuth。解决方法是:您必须确保他们重新输入应用程序后退出。

建议

您可以在每次活动被销毁时(或每次用户打开应用程序时)注销。确保它们总是从新开始。