保持地图活动在后台更新

时间:2015-06-06 05:51:45

标签: java android google-maps google-maps-api-3

在我的Android应用中,我添加了地图活动,我希望能够在后台监控位置并不断更新位置数据。然后,该数据将用于执行特定于位置的功能。

我是Android新手,所以我们将非常感谢您的最大帮助 到目前为止,我已经有了启动map的基本代码。

package com.app.alviefinal.alviefinal;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


public class MapsActivity extends FragmentActivity {

    private GoogleMap newmap; // Might be null if Google Play services APK is  not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        Log.d("Map","MapCreated");
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
        if (newmap == null) {
            // Try to obtain the map from the SupportMapFragment.
            newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
            // Check if we were successful in obtaining the map.
            if (newmap != null) {
                setUpMap();
                Log.d("MAPS","Map working");
            }
            else Log.d("MAPS","not working");
        }
    }

    private void setUpMap() {

        newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

        // Enable MyLocation Layer of Google Map
        newmap.setMyLocationEnabled(true);

        // Get LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Get Current Location
        Location myLocation = locationManager.getLastKnownLocation(provider);

        // set map type
        newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        // Get latitude of the current location
        double latitude = myLocation.getLatitude();

        // Get longitude of the current location
        double longitude = myLocation.getLongitude();

        // Create a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Show the current location in Google Map
        newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
        newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));

        Log.d("LATITUDE",String.valueOf(latitude));
        Log.d("LONGITUDE",String.valueOf(longitude));
        GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(final Marker marker) {

                Intent intent=new Intent(getApplicationContext(),PrefActivity.class);
                startActivity(intent);
                return true;
            }

        };

        newmap.setOnMarkerClickListener(listener);
        newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng latLng) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Setting the title for the marker.
                // This will be displayed on taping the marker
                markerOptions.title(latLng.latitude + " : " + latLng.longitude);


                // Animating to the touched position
                newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                // Placing a marker on the touched position
                newmap.addMarker(markerOptions);
                Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
                Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Service在后台获取数据。为此,您必须创建一个扩展Service类的类,然后重写onStartCommand以编写您自己的代码。像这样:

public class MyService extends Service {

@Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

 @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
...
return START_STICKY;
    }
}

您可以在onStartCommand中使用计时器来更新您的数据。 您必须在Android Manifest中注册您的服务,如下所示:

<service
            android:name=".MyService"
            android:enabled="true" >
        </service>

您必须记住,如果重新启动手机,服务将无法自动启动。您必须使用Boot Broadcast Receiver来启动该服务。