我正在使用Firebase开发Android应用程序。
根据我的经验,即使数据库几乎为空,我正在执行的每项任务(例如Login,使用OnDataChanged获取数据等)都会以极大的延迟完成。当我调试代码时,我看到程序流程一直在运行,并且"跳过" firebase侦听器,然后只有在程序达到更晚的状态后才执行它们。这导致了许多竞争条件,我通常试图通过主线程上的睡眠来解决,但这会使我的应用程序更慢,并使其不稳定。例如,我在下面发布了LoginActivity的代码,它使用了UserLoginTask,我在其中调用Firebase的AuthWithPassword方法,一旦auth成功,我就调用了一个OnDataChanged方法从数据库中检索用户的数据并将其存储在MyAppModel上,这是一个单例模型。如果你能看到它并试着告诉我我做错了什么,我会很高兴的。谢谢!
package com.biu.ap2.mysitter;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.auth.AuthResult;
public class LoginActivity extends ActionBarActivity {
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world", "a@a:a"
};
private UserLoginTask mAuthTask = null;
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private Button mRegisterView;
private View mLoginFormView;
myAppModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
//populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mRegisterView = (Button) findViewById(R.id.register);
mRegisterView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(i);
}
});
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login_btnLogin || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.login_btnLogin);
mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_btnLogin);
mProgressView = findViewById(R.id.login_progress);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
// return email.contains("@");
return true;
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
// return password.length() > 0;
return true;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
boolean flag = false;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean getFlag() {
return this.flag;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
Firebase.setAndroidContext(LoginActivity.this);
final Firebase ref = new Firebase("https://mybabysit.firebaseio.com/");
ref.authWithPassword(mEmail, mPassword, new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
setFlag(true);
setUser(mEmail);
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {
Log.d("blah", firebaseError.getMessage());
System.out.println(firebaseError.getMessage());
}
});
try {
// Simulate network access.
Thread.sleep(8000);
} catch (InterruptedException e) {
return false;
}
if (getFlag())
return true;
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
}
finish();
Intent i = new Intent(LoginActivity.this, IntroductionActivity.class);
i.putExtra("email", mEmail);
LoginActivity.this.startActivity(i);
} else {
mPasswordView.setError(getString(R.string.failed));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public void setUser(final String email) {
model = model.getInstance();
final String mEmail=email;
Firebase ref = new Firebase("https://mybabysit.firebaseio.com");
Firebase userRef = ref.child("users");
// Firebase uidref=ref.child("uid").child(ref.getAuth().getUid());
// Attach an listener to read the data at our sitterPosts reference
userRef.addValueEventListener(new ValueEventListener() {
//ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot UserSnapshot : snapshot.getChildren()) {
User myUser = UserSnapshot.getValue(User.class);
if (mEmail.equals(myUser.getEmail()))
model.getInstance().setLoggedUser(myUser);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
}
//*/
更新****:似乎响应缓慢是由于&#34; SetUser&#34; OnAuthenticate内部的方法。从数据库中获取一个位图对象,并且收到一个Bitmap需要很长时间。从那里删除它并将Bitmap压缩得更轻,使得查询速度提高了近5倍,3秒钟的睡眠似乎就可以完成。
谢谢大家的回复!
答案 0 :(得分:0)
更新:似乎响应缓慢是OnAuthenticate中的“SetUser”方法。从数据库中获取一个位图对象,并且收到一个Bitmap需要很长时间。从那里删除它并将Bitmap压缩得更轻,使得查询速度提高了近5倍,现在只需3秒的睡眠即可完成工作。
谢谢大家的回复!