0

我正在製作一個應用程序,用於從傳感器收集數據。每次傳感器發送數據時,都會在地圖上放置一個新的標記。當我按回來然後恢復地圖活動時,所有標記都消失了。在恢復活動時,是否有方法使用其獨特的MarkerOptions(title,snippet,LatLng)保存和恢復每個獨特標記?Google地圖:如何在恢復地圖活動時恢復標記

這裏是我的地圖活動

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

private GoogleMap mMap; 
GoogleApiClient mGoogleApiClient; 
Location mLastLocation; 
Marker mCurrLocationMarker; 
private int co_mV; 
private int no2_mV; 
LocationRequest mLocationRequest; 
private boolean initiateApp; 
String currentTime; 

TcpClient mTcpClient; 
ArrayList<Marker> markerArrayList; 

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

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 
    // 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); 
    initiateApp = true; 
    markerArrayList = new ArrayList<Marker>(); 

} 

/** 
* 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.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
    mMap.setMyLocationEnabled(true); 


    if(mGoogleApiClient == null) { 
    //Initialize Google Play Services 
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      buildGoogleApiClient(); 

     } 
    } 
    else { 
      buildGoogleApiClient(); 
     } 
    } 
} 

/* Here we create the infoWindow **/ 
protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    mGoogleApiClient.connect(); 

} 

@Override 
public void onConnected(Bundle bundle) { 

    getNewLocation(); 
    new ConnectTask().execute(""); 

} 


public void newData(JSONObject d) { 
    try { 
     co_mV = d.getInt("co_mV"); 
     no2_mV = d.getInt("no2_mV"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    getNewLocation(); 
} 

public void getTime() { 

    Calendar cal = Calendar.getInstance(); 
    currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime()); 

} 

public void getNewLocation() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 

    if (markerArrayList.size()>1) { 
     if(location.distanceTo(mLastLocation) < 30) { 
      markerArrayList.get(markerArrayList.size()-1).remove(); 
      markerArrayList.remove(markerArrayList.size()-1); 
      Toast.makeText(
        getApplicationContext(), 
        "Reading to close to last reading, replaces last reading", Toast.LENGTH_SHORT).show(); 
     } 
    } 


    if (markerArrayList.size() == 8) { 
     markerArrayList.get(0).remove(); 
     markerArrayList.remove(0); 
    } 

    //Place current location marker 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 

    if (!initiateApp) { 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Time of reading: " + currentTime); 
     markerOptions.snippet("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV"); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
     mCurrLocationMarker = mMap.addMarker(markerOptions); 
     markerArrayList.add(mCurrLocationMarker); 

    } 

    mLastLocation = location; 


    Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude())); 
    Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude())); 


    //move map camera 

    if(initiateApp){ 
     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15)); 
    } 

    boolean contains = mMap.getProjection() 
      .getVisibleRegion() 
      .latLngBounds 
      .contains(latLng); 

    if(!contains){ 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    } 

    initiateApp = false; 
} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 

} 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
public boolean checkLocationPermission(){ 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Asking user if explanation is needed 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       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[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 


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

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], 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, 
         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(); 
      } 
      return; 
     } 

     // other 'case' lines to check for other permissions this app might request. 
     // You can add here other case statements according to your requirement. 
    } 
} 

ublic JSONObject getNewJSON(JSONObject json) { 
    try { 

     int humidity = json.getInt("humidity_ppm"); 
     int pressure = json.getInt("pressure_Pa"); 
     int noise = json.getInt("noise_dB"); 
     double lat = mLastLocation.getLatitude(); 
     double lng = mLastLocation.getLongitude(); 
     long time = System.currentTimeMillis()/1000L; 

     JSONObject c = new JSONObject(); 
     c.put("time",time); 
     c.put("lat",lat); 
     c.put("long",lng); 
     c.put("humidity",humidity); 
     c.put("pressure",pressure); 
     c.put("noise_dB",noise); 
     return c; 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

return null; 
} 


public class ConnectTask extends AsyncTask<String, String, TcpClient> { 

    @Override 
    protected TcpClient doInBackground(String... message) { 

     //we create a TCPClient object 
     mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() { 
      @Override 
      //here the messageReceived method is implemented 
      public void messageReceived(String message) { 
       //this method calls the onProgressUpdate 
       publishProgress(message); 
      } 
     }); 
     mTcpClient.run(); 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     super.onProgressUpdate(values); 


     try { 
      JSONObject parser = new JSONObject(values[0]); 
      JSONObject d = parser.getJSONObject("d"); 
      JSONObject cloudData = getNewJSON(d); 

      if (mLastLocation != null) { 
       newData(d); 
       getTime(); 
      } 

      System.out.println(cloudData); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     //process server response here.... 
    } 

} 

回答

0

您可以與您的服務器的新數據填充功能。然後,只要服務器發送JSON數據,就可以調用該函數。要回答你的問題,你只需在onResume中調用相同的函數。有關活動狀態的更多信息,請參閱this

另一種方法是將其保存在savedInstanceState捆綁,做檢查的onSaveInstanceState就像this SO accepted answer如果包不爲空,如果是填充的列表(標記的最後一個已知位置的地圖,如果有工作你的項目)。否則,只需加載地圖。

+0

我真的不明白你的意思嗎?我已經有一個名爲newData()的方法,當服務器發送JSON數據時會調用它?我編寫了代碼。你的意思是我需要做什麼? – Kspr

+0

您需要重寫Activity類的onPause和onResume方法。然後你創建一個類的List或者其他的東西來保存onPause()方法中的標記,然後在你的情況下在onResume()方法中引用List,newData()。系統分別在活動停止和恢復時調用這兩種方法。 –

+0

謝謝你的回答。我有一個「markerArray」ArrayList,它在「OnLocationChanged」上填充了我的標記。我怎樣才能讓這個ArrayList保存在onPause()中? – Kspr

0

你說

當我按回,然後繼續在地圖

吧?不關閉你的應用程序。

最簡單的方法是重寫onBackPressed方法,像這樣:

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

這不會觸發onDestroy()onCreate()了,所以你會離開你的活動實例不變。夠簡單,嗯?