当前纬度; android片段类中的经度

时间:2014-02-04 07:09:28

标签: android location locationlistener

我如何获得当前location.i已尝试下面的代码但是为位置获取null -

public class LocationsMapView extends Fragment implements LocationListener, android.location.LocationListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

  locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationsMapView.this);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } else {
      System.out.println("Location not available");

    }
}

@Override
    public void onLocationChanged(Location loc) {
        current=new LatLng(loc.getLatitude(),loc.getLongitude());
        lat=loc.getLatitude();longi=loc.getLongitude();
        Toast.makeText(getActivity(), "location-"+loc.getLatitude(), Toast.LENGTH_SHORT).show();
        System.out.println("location.."+lat+"..."+longi+" current .."+current);
    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    }
@Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        location = locationManager.getLastKnownLocation(provider);

            // Initialize the location fields
            if (location != null) {
              System.out.println("Provider " + provider + " has been selected.");
              onLocationChanged(location);
            } else {
              System.out.println("Location not available"); 
            }       
}
}

我还在清单中给予了许可 -

<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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

public static class XYZ extends Fragment
        implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener,
            LocationListener {
    GoogleMap map;
    LatLng latlng;
    private LocationRequest lr;
    private LocationClient lc;
    MapFragment mapFragment;
    ImageView iv;
    private static View view;

    public XYZ() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null)
                parent.removeView(view);
        }

        try {
            view = inflater.inflate(R.layout.XYZ, container,
                    false);

            mapFragment = ((MapFragment) this.getActivity()
                    .getFragmentManager().findFragmentById(R.id.map));
            iv = (ImageView) view.findViewById(R.id.iv);

            map = mapFragment.getMap();
            map.getUiSettings().setAllGesturesEnabled(false);
            map.getUiSettings().setMyLocationButtonEnabled(false);
            map.setMyLocationEnabled(true);
            map.getUiSettings().setZoomControlsEnabled(false);

            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            Toast.makeText(getActivity(), "Google Play Services missing !",
                    Toast.LENGTH_LONG).show();
        } catch (InflateException e) {
            Toast.makeText(getActivity(), "Problems inflating the view !",
                    Toast.LENGTH_LONG).show();
        } catch (NullPointerException e) {
            Toast.makeText(getActivity(), "Google Play Services missing !",
                    Toast.LENGTH_LONG).show();
        }

        return view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lr = LocationRequest.create();
        lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        lc = new LocationClient(this.getActivity().getApplicationContext(),
                this, this);
        lc.connect();
    }

    @Override
    public void onLocationChanged(Location l2) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
        map.animateCamera(cameraUpdate);
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        lc.requestLocationUpdates(lr, this);

    }

    @Override
    public void onDisconnected() {

    }
}

这在我的案例中非常完美。

答案 1 :(得分:0)

 public class LocationFinderFragment extends Fragment implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener {

        public interface OnNewLocationFoundListener {
            public void OnNewLocationFound(Location location);
        }

        private static final String TAG = "LocationFinderFragment";
        private static final long DEFAULT_UPDATE_LOCATION_INTERVAL = 30 * 1000; // update every 30 seconds
        private static final long DEFAULT_TERMINATE_SAT_FINDING = 1 * 60 * 60 * 1000; // for 1 hour

        private OnNewLocationFoundListener listener;  // Listener of fragments
        private OnNewLocationFoundListener listener2; // Listener of MainFragmentHolder
        private Context context;
        private LocationClient mLocationClient;
        private static double lat = 0;
        private static double lng = 0;
        private static long lastTime = 0;

        private LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if(location == null)
                    return;

                if(lat == location.getLatitude()  &&  lng == location.getLongitude()) {
                    Log.e(TAG, "location not changed.");
                    return;
                }

                lat = location.getLatitude();
                lng = location.getLongitude();
                Log.i(TAG, "Location changed to (" + lat + ", " + lng + ")");


            }
        };