2017-02-21 1 views
1

Wenn ich Android-Taste "recents" und wähle meine App erneut, um zurück zu de App gehen, den Lebenszyklus von MapsActivity onCreate wieder ausführen und erstellen neue Instanz von MapsActivity.Aktivitäten Lebenszyklus nach gedrückten Android-Taste "recents" erstellen neue Aktivität, aber nicht zerstören alte Aktivität

Das ist in Ordnung, aber die alte MapsActivity läuft immer noch im Hintergrund, und das ist ein Problem, da sowohl MapsActivity als auch unabhängige neue Variablen Zähler haben und immer noch mit verschiedenen Werten in denselben Variablen zählen.

Der Zähler befindet sich in onLocationChanged() und wird als "Uhr" bezeichnet. onLocationChanged() aktualisiert automatisch je 5 Sekunden.

Beispiel: Zähler laufen: 1, 2, 3, 4, 5, ... an diesem Punkt i android Taste "Recent" drücken (das System auszuführen onCreate) Zähler immer noch so ausgeführt wird: 6, 1, 7, 2, 8, 3, ... an diesem Punkt ein erneutes Andrücken Knopf "recent" (Ausführen onCreate) Zähler läuft noch so: 9, 4, 1, 10, 5, 2, 11, 6, 3, ...

Ich nehme an, der Lebenszyklus von MapsActivity zerstört keine alten Aktivitäten.

Ich brauche nur eine sequentiellen Zähler läuft, und ich denke, das alte MapsActivity :)

eine Idee zu lösen mein Problem sterben müssen? Danke vielmals!

unter dem manifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.sasse.myapplication"> 

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="@string/google_maps_key" /> 

     <activity 
      android:name=".MapsActivity" 
      android:label="@string/title_activity_maps"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

Layout activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/map" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.sasse.myapplication.MapsActivity" /> 

Maps_activity

package com.example.sasse.myapplication; 

import android.*; 
import android.Manifest; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.os.Build; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.app.FragmentActivity; 
import android.os.Bundle; 
import android.support.v4.content.ContextCompat; 
import android.util.Log; 
import android.widget.Toast; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
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 LocationListener, ConnectionCallbacks, OnConnectionFailedListener, OnMapReadyCallback { 

    private static final String TAG = "MapsActivity"; 
    private GoogleMap mMap; 
    protected GoogleApiClient mGoogleApiClient; 
    protected LocationRequest mLocationRequest; 
    public int clock = 0; 

    @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); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     // Add a marker in Sydney and move the camera 
     LatLng sydney = new LatLng(-34, 151); 
     mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
     //Initialize Google Play Services 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        android.Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } else { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 

    } 

    public void onLocationChanged(Location location) { 

     clock++; 
     if (clock>=10) { 

      Toast.makeText(this, "clock : "+clock, Toast.LENGTH_SHORT).show(); 
      clock=0; 
     } 
     Log.i(TAG, "= = = = = >>> clock : "+clock); 
    } 

    // --------------------------------------------------------------------------------------------- 
    // ---------------- VERIFICAÇÃO DA CONEXÃO COM O SERVIDOR DO GOOGLE MAPS----------------------- 
    // --------------------------------------------------------------------------------------------- 
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 

    public boolean checkLocationPermission() { 
     if (ContextCompat.checkSelfPermission(this, 
       android.Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Asking user if explanation is needed 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        android.Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 

       //Prompt the user once explanation has been shown 
       ActivityCompat.requestPermissions(this, 
         new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } else { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, 
         new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
      return false; 
     } else { 
      return true; 
     } 
    } 

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission was granted. Do the 
        // contacts-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, 
          android.Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 
         if (mGoogleApiClient == null) { 
          buildGoogleApiClient(); 
         } 
         mMap.setMyLocationEnabled(true); 
        } 
       } else { 
        // Permission denied, Disable the functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
      } 
      // other 'case' lines to check for other permissions this app might request. 
      // You can add here other case statements according to your requirement. 
     } 
    } 

    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    public void onConnected(Bundle bundle) { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(5000); 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    public void onConnectionSuspended(int i) { 
    } 

    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
    } 
} 
+0

Nicht sicher, ob Genau das ist y Sie suchen, aber ich würde vorschlagen, den Backstack als beantwortet in dieser Frage http://stackoverflow.com/questions/5794506/android-clear-the-back-stack. Weitere Informationen zum Backstack finden Sie hier https://developer.android.com/guide/components/activities/tasks-and-back-stack.html –

+0

Ich habe versucht, FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_NEW_TASK und FLAG_ACTIVITY_CLEAR_TASK, aber immer noch viele Aktivitäten ausgeführt . – Itapox

Antwort

0

Versuchen launchMode = "singleTop" für die Aktivität mit

+0

Ich habe versucht "singleTop", "singleTask" und "singleInstance". Leider hat nicht funktioniert. Immer noch viele Aktivitäten. – Itapox

Verwandte Themen