不使用互联网获取Android设备位置

时间:2014-06-10 19:31:28

标签: android gps android-manifest android-permissions

虽然,我已经使用了

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

在我的AndroidManifest.xml中,但我的应用仍然没有显示设备的当前位置。

以下是我在java文件中的代码。

LocationManager locationManager ;
String provider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);        

    Criteria criteria = new Criteria();

    provider = locationManager.getBestProvider(criteria, false);


    if(provider!=null && !provider.equals("")){

        Location location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(provider, 20000, 1, this);


        if(location!=null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

    }else{
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
    }
}

public void onLocationChanged(Location location) {
    TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);

    TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);


    tvLatitude.setText("Latitude:" + location.getLatitude() );

    tvLongitude.setText("Longitude:" + location.getLongitude());


}

但是当我打开wifi时,它开始工作得很好。所以,有什么方法可以做到这一点吗?

3 个答案:

答案 0 :(得分:0)

我真的会研究FusedLocationProvider实现。这是一个例子:

public class LocationService extends Service implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener, 
        LocationListener{

private String TAG = getClass().getSimpleName();

private final IBinder binder = new LocalLocationBinder();

/* GPS VARIABLES */
private String provider;
    private int minPingInterval = 5000;
    private int maxPingInterval = 7000;

// Simple
private LocationManager locationManager;

// Fused Location Provider
private LocationClient locationClient;
private LocationRequest locationRequest;
private Location loc;

@Override
public void onCreate(){
    setupFusedLocationUpdates();
}

@Override
public void onDestroy(){        
    Log.d(TAG, "Disconnecting from GPS services.");
    super.onDestroy();
    if (locationClient.isConnected()) {
        locationClient.disconnect();
    }

    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
}

/** -- GPS FUNCTIONALITY -- **/
/* NETWORK CHANGE */
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.d(TAG, "Provider, " + provider + " status is changing to " + status);
    setupFusedLocationUpdates();
}

/* SIMPLE GPS (Network) */
@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this,
            "Provider " + provider + " is enabled. Starting Network GPS.",
            Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this,
            "Provider " + provider + " is disabled. Unable to track GPS.",
            Toast.LENGTH_SHORT).show();
}

// Setup a simple (coarse) location update
private void setupSimpleLocationUpdates() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setBearingRequired(true);
    provider = locationManager.getBestProvider(criteria, true);
    locationManager.requestLocationUpdates(provider, minPingInterval,
            0, this);
}


/* FUSED LOCATION PROVIDER */
// If we can't connect to Google Play, set up simple network GPS provider
@Override
public void onConnectionFailed(ConnectionResult result) {
    Toast.makeText(this,
            "Attemp to connect to Google Play failed. Using Network GPS.",
            Toast.LENGTH_SHORT).show();
    setupSimpleLocationUpdates();
}

// If we can connect to Google Play (preferred) then do it, and set up
// our Location updates
@Override
public void onConnected(Bundle connectionHint) {
    Toast.makeText(this,
            "Connected to Google Play. Starting Fused Location GPS.",
            Toast.LENGTH_SHORT).show();

    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    locationRequest.setInterval(maxPingInterval);
    locationRequest.setFastestInterval(minPingInterval);
    locationRequest.setSmallestDisplacement(0);
    locationClient.requestLocationUpdates(locationRequest, this);
}

@Override
public void onDisconnected() {
    Toast.makeText(this,
            "Stopping Fused Location GPS and Disconnecting from Google Play.",
            Toast.LENGTH_SHORT).show();
}

// This method determines the best means of GPS. If we are able to connect to Google Play
// we will be able to utilize it's  GPS system, if not we can use our
// simple GPS updates through our network provider. This gives us a "fused" location
// provider by fusing our possible location providers for best results.
private void setupFusedLocationUpdates() {
    int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // if we can connect to Google Play, use our fused location provider
    if (resp == ConnectionResult.SUCCESS) {
        locationClient = new LocationClient(this, this, this);
        locationClient.connect();
    }
    // if we can't connect to Google Play, set up our simple network
    // location listener
    else {
        Toast.makeText(this,
                     "Google Play Services currently unavailable. Using Network GPS.",Toast.LENGTH_SHORT).show();
        setupSimpleLocationUpdates();
    }
}

/* GPS LOCATION CHANGE - PRIMARY FUNCTIONALITY */
@Override
public void onLocationChanged(Location loc) {
    // Do what you want with your updated location
}

/** -- Service Binding -- **/
@Override
public IBinder onBind(Intent intent) {
    return binder;
}

public class LocalLocationBinder extends Binder{
    LocationService getService(){
        return LocationService.this;
    }
}

}

我从我的一个项目中删除了这个并做了一些快速编辑。我可能错过了一些东西或意外删除了一些东西。如果您有任何疑问,请告诉我。

答案 1 :(得分:0)

您必须注册LocationListener才能接收位置更新。我不确定是否是这种情况,因为没有看到您的活动实现了哪些接口。

答案 2 :(得分:0)

这将帮助您没有任何错误。 这样做是为了使用GPS访问地理位置:

Java文件:

package com.example.projgeolocation1;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.view.Menu;
import android.app.Activity;
import android.content.Context;
import android.location.Geocoder;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {

private TextView latituteField;

private TextView longitudeField, time, myLocationText;

private LocationManager locationManager;

private String provider, addressString;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);
    time = (TextView) findViewById(R.id.textView2);
    myLocationText = (TextView) findViewById(R.id.textView4);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);


    Toast.makeText(getApplicationContext(), "Provider " + provider + " has been selected.", Toast.LENGTH_LONG).show();
    Toast.makeText(getApplicationContext(), "Location is " + String.valueOf(location), Toast.LENGTH_LONG).show();

    if (location != null)
    {
        onLocationChanged(location);
    }

    else
    {
        latituteField.setText("Location not available");
        longitudeField.setText("Location not available");
    }
}


@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 0, 0, this);
}


@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());
    latituteField.setText(String.valueOf(location.getLatitude()));
    longitudeField.setText(String.valueOf(location.getLongitude()));
    time.setText(String.valueOf(location.getTime()));


    Geocoder gc = new Geocoder(this, Locale.getDefault());
    try {
    List<Address> addresses = gc.getFromLocation(lat, lng, 1);
    StringBuilder sb = new StringBuilder();
    if (addresses.size() > 0) {
    Address address = addresses.get(0);
    for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
    sb.append(address.getAddressLine(i)).append("\n");
    sb.append(address.getLocality()).append("\n");
    sb.append(address.getPostalCode()).append("\n");
    sb.append(address.getCountryName());
    }
    addressString = sb.toString();
    } 
    catch (IOException e) 
    {

    }
    myLocationText.setText(addressString);

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {
    Toast.makeText(this, "Enabled new provider " + provider,
            Toast.LENGTH_SHORT).show();

}

@Override
public void onProviderDisabled(String provider) {
    Toast.makeText(this, "Disabled provider " + provider,
            Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
}

AndroidManifest.xml

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