【问题标题】:Get current location during app launch在应用启动期间获取当前位置
【发布时间】:2012-08-30 10:49:43
【问题描述】:

美好的一天! 我正在开发一个监控用户位置的安卓应用程序。我正在使用 LocationManager 获取用户位置,使用以下方法

public void onLocationChanged(Location theLocation) {}

通过上述方法,每当有用户移动时,我都会收到位置坐标。

但是,现在我计划在用户登录应用后立即获取用户的位置。有什么方法可以通过 LocationManager 在我的应用启动后手动获取位置坐标?

【问题讨论】:

  • 应用启动时不一定知道当前位置。所以getLastKnownLocation 可以是null 或非常过时,无论位置提供商如何。
  • 见老post

标签: android geolocation location locationmanager


【解决方案1】:

使用这种技术:

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

boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location location;

if(network_enabled){

   location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if(location!=null){
   longitude = location.getLongitude();
   latitude = location.getLatitude();
    }                
}

在这种情况下,您甚至不需要使用 GPS,只需移动网络即可。

不要忘记在 Manifest 中授予以下权限:

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

【讨论】:

  • getLastKnownLocation() 可能返回 null,在这种情况下这段代码会崩溃
  • 它对我来说工作正常,只是集中精力我没有使用 GPS 提供商,我使用的是网络提供商。你测试了吗??
  • 您不能证明否定断言,例如“从不”。它可能会返回 null,您应该在调用 .getLongitude() 之前通过检查 location 是否为 null 来进行防御性编码
  • 我取消了反对票,但我并不是要给它+1。事实是,“我现在想要位置”的答案是“好吧,很难,你不能总是拥有它,你必须等到 onLocationChanged() 被触发”它是事件驱动的,如果没有 GPS 或网络信号当您打开手机运行应用程序时,您很不走运。无论如何,您添加了空检查,这很好
  • 感谢工作正常,你拯救了我的白天,黑夜等等:D
【解决方案2】:

试试这个代码。希望它会起作用

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class MainActivity extends Activity implements LocationListener {

private LocationManager locationManager;
private 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);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
      } else {
        System.out.println("Location not avilable");
      }

}

protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
  }

  /* Remove the locationlistener updates when Activity is paused */
  @Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates((LocationListener) this);
  }
public void onLocationChanged(Location location) {
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());
    Toast.makeText(getApplicationContext(), lat+"----"+lng,Toast.LENGTH_LONG).show();
    Log.i("Latitude------------", "Lattitude:" +lat);
    Log.i("Longitude-------------", "Longitude:" +lng);
  }

@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

}
    }

必须添加所需的权限

【讨论】:

    【解决方案3】:

    这就是我所做的... 1)mainactiviy.java

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    
    public class MainActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button gpsButton = (Button) findViewById(R.id.getloc);
    
    gpsButton.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v){
        LoadCoords();
    }});
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }
    
    public void LoadCoords(){
    EditText locn = (EditText)findViewById(R.id.text1);
    EditText locn1 = (EditText)findViewById(R.id.text2);
    GPSTracker gps = new GPSTracker(this);
    if(gps.canGetLocation){
    Double latPoint=gps.getLatitude(); 
    Double lngPoint =gps.getLongitude();   
    
    locn.setText(latPoint.toString());
    locn1.setText(lngPoint.toString());
    }
    }
    }
    

    另一个文件 2)GPSTracker.java

    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;
    
    public class GPSTracker extends Service implements LocationListener{
    private final Context mContext;
    
    // flag for GPS status
    boolean isGPSEnabled = false;
    
    // flag for network status
    boolean isNetworkEnabled = false;
    
    boolean canGetLocation = false;
    
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
    // Declaring a Location Manager
    protected LocationManager locationManager;
    
    public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
    }
    public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);
    
        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return location;
    }
    public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }
    
    // return latitude
    return latitude;
    }
    
    /**
    * Function to get longitude
    * */
    
    public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }
    
    // return longitude
    return longitude;
    }
    @Override
    public void onLocationChanged(Location location) {
    }
    
    @Override
    public void onProviderDisabled(String provider) {
    }
    
    
    
    @Override
    public void onProviderEnabled(String provider) {
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    
    @Override
    public IBinder onBind(Intent arg0) {
    return null;
    }
    

    如果有效请回复...

    【讨论】:

    • 别忘了添加权限
    • 权限>
    【解决方案4】:
        ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            /*
            tvLatitud.setText("No se tienen permisos");
            ...
             */
    
            return;
        }else
        {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            latitude = location.getLatitude();
            longitude =  location.getLongitude();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 2021-08-03
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      相关资源
      最近更新 更多