后退按钮无法正常工作 - Android

时间:2017-02-07 23:38:23

标签: java android onbackpressed

当我按下手机中的后退按钮时,此活动将重新启动,而不是离开应用程序。(这是用户打开应用时显示的活动)

这是代码,它只是一个简单的登录活动,没什么不同。

public class LoginActivity extends AppCompatActivity {

    public static final int RC_SIGN_IN = 1;
    private GoogleApiClient mGoogleApiClient;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    public static final String TAG = "MAIN_ACTIVITY";
    private String email, password;

    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    @BindView(R.id.google_button)
    SignInButton mGoogleBtn;

    @BindView(R.id.register_button)
    TextView mRegisterBtn;


    @BindView(R.id.email_edit_text)
    EditText mEmail;

    @BindView(R.id.password_edit_text)
    EditText mPassword;

    @BindView(R.id.login_button)
    ImageButton mLogin;


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

        ButterKnife.bind(this);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() != null) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                }
            }
        };

        if (mAuth.getCurrentUser() != null) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                        Toast.makeText(LoginActivity.this, R.string.connection_failed, Toast.LENGTH_LONG).show();

                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();


    }

    @OnClick(R.id.register_button)
    public void register() {
        startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
    }

    @OnClick(R.id.google_button)
    public void loginUsingGoogle() {
        signIn();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        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) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // ...
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // ...
                    }
                });
    }

    @OnClick(R.id.login_button)
    public void login() {
        email = mEmail.getText().toString();
        password = mPassword.getText().toString();

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
            return;
        }

        progressBar.setVisibility(View.VISIBLE);

        //authenticate user
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        progressBar.setVisibility(View.GONE);
                        if (!task.isSuccessful()) {
                            // there was an error
                            if (password.length() < 6) {
                                mPassword.setError(getString(R.string.minimum_password));
                            } else {
                                Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                });
    }
}

我已经尝试过了:

@Override
public void onBackPressed() {
    super.onBackPressed();
    moveTaskToBack(true);
}

这样:

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

和此:

@Override
public void onBackPressed() {
    super.onBackPressed();
    System.exit(0);
}

这是日志

java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
com.intellij.openapi.extensions.impl.PicoPluginExtensionInitializationException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:96)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getExtension(ExtensionComponentAdapter.java:119)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapters(ExtensionPointImpl.java:249)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.getExtensions(ExtensionPointImpl.java:194)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:100)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:87)
    at com.intellij.openapi.extensions.ExtensionPointName.getExtensions(ExtensionPointName.java:49)
    at com.intellij.tasks.TaskRepositoryType.getRepositoryTypes(TaskRepositoryType.java:40)
    at com.intellij.tasks.impl.TaskManagerImpl.loadRepositories(TaskManagerImpl.java:618)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:612)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:78)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistentComponent(ComponentStoreImpl.kt:291)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:520)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:123)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:107)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:90)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:282)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:231)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.access$300(ProjectManagerImpl.java:68)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:531)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:527)
    at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:198)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$8.run(CoreProgressManager.java:357)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.application.impl.ApplicationImpl$13$1.run(ApplicationImpl.java:633)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:160)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentImplementation(ExtensionComponentAdapter.java:66)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:73)
    ... 37 more
Caused by: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:157)
    ... 39 more
Caused by:

java.lang.RuntimeException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:160)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentImplementation(ExtensionComponentAdapter.java:66)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:73)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getExtension(ExtensionComponentAdapter.java:119)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapters(ExtensionPointImpl.java:249)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.getExtensions(ExtensionPointImpl.java:194)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:100)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:87)
    at com.intellij.openapi.extensions.ExtensionPointName.getExtensions(ExtensionPointName.java:49)
    at com.intellij.tasks.TaskRepositoryType.getRepositoryTypes(TaskRepositoryType.java:40)
    at com.intellij.tasks.impl.TaskManagerImpl.loadRepositories(TaskManagerImpl.java:618)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:612)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:78)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistentComponent(ComponentStoreImpl.kt:291)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:520)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:123)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:107)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:90)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:282)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:231)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.access$300(ProjectManagerImpl.java:68)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:531)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:527)
    at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:198)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$8.run(CoreProgressManager.java:357)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.application.impl.ApplicationImpl$13$1.run(ApplicationImpl.java:633)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:157)
    ... 39 more

3 个答案:

答案 0 :(得分:2)

我能想到为什么系统会重新启动一个Activity的唯一原因是因为它崩溃了。请检查logcat,并将其添加到问题中。

答案 1 :(得分:1)

尝试从代码中删除onBackPressed()方法并清理项目

答案 2 :(得分:1)

在onBackPressed中添加此意图以关闭应用程序:

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            intent.putExtra("EXIT", true);

            startActivity(intent);