当我在android中按回为啥不退出应用程序?

Posted

技术标签:

【中文标题】当我在android中按回为啥不退出应用程序?【英文标题】:when I press back in android why not exit the application?当我在android中按回为什么不退出应用程序? 【发布时间】:2016-08-21 03:05:31 【问题描述】:

我的主要活动是使用谷歌登录的 LoginActivity,当用户登录时将定向到 MapsActivity,当用户在 MapsActivity 中单击“返回”时,我希望用户退出应用程序,但现在为什么单击“返回”时应用程序刚刚再次打开MapsActvity 让用户无法退出?

LoginActivity.java

package com.emergency;


/**
 * Created by Eggy on 4/17/2016.
 */
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

/**
 * Activity to demonstrate basic retrieval of the Google user's ID, email address, and basic
 * profile.
 */
public class LoginActivity 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_login);


        // 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);
         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]

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

    @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) 
            Intent i = new Intent(LoginActivity.this, MapsActivity.class);
            startActivity(i);
         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;
    

MapsActivity.java

package com.emergency;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 

    private GoogleMap mMap;
    int PLACE_PICKER_REQUEST = 1;
    GoogleApiClient mGoogleApiClient;
    boolean search=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mGoogleApiClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    

    public void onSearch(View view)
    
        PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

        try 
            startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
         catch (GooglePlayServicesRepairableException e) 
            e.printStackTrace();
         catch (GooglePlayServicesNotAvailableException e) 
            e.printStackTrace();
        

    


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */


    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;
        mMap.setTrafficEnabled(true);
        mMap.setMyLocationEnabled(true);
        mMap.setOnMyLocationChangeListener(onMyLocationChangeListener);

    

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        if (requestCode == PLACE_PICKER_REQUEST) 
            if (resultCode == RESULT_OK) 
                Place place = PlacePicker.getPlace(data, this);
                LatLng latLng = new LatLng(place.getLatLng().latitude,place.getLatLng().longitude);
                mMap.addMarker(new MarkerOptions().position(latLng).title(place.getAddress().toString()));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            
        
    

    private GoogleMap.OnMyLocationChangeListener onMyLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() 
        @Override
        public void onMyLocationChange(Location location) 
            if(!search) 

                mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                search=true;

            
        
    ;

    @Override
    public void onConnected(Bundle bundle) 

    

    @Override
    public void onConnectionSuspended(int i) 

    

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 

    

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.emergency"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.emergency.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.emergency.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- To access accounts configured on device -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- To use account credentials -->
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />
    //OpenGL ES version 2
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/CustomActionBarTheme">
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".splashscreen"
            android:label="@string/app_name"
            android:noHistory="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Main activity -->
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
        </activity>
        <activity
            android:name=".LoginActivity"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"/>
    </application>

</manifest>

【问题讨论】:

【参考方案1】:

试试这个代码

public void onBackPressed() 
  moveTaskToBack(true);     

【讨论】:

嗯?我们甚至应该把它放在哪里?对于想知道为什么会发生这种情况的我们来说,OP 问题的根本问题/根源是什么?

以上是关于当我在android中按回为啥不退出应用程序?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我在退出我的 Activity 时会崩溃?

为啥当我在编辑器中按下播放时 Unity 会崩溃?

Android - 在通知上单击打开文件并按回不显示应用程序

关闭Android弹出窗口并按回键

Android Reorder Fragment Backstack

退出时如何保存 Activity 的状态?安卓