应用启动时获取当前位置

9

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

public void onLocationChanged(Location theLocation) {}

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

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


1
应用程序启动时当前位置不一定已知,因此getLastKnownLocation可能为null或非常过时,无论位置提供者如何。 - zapl
1
请查看早期的帖子:http://stackoverflow.com/a/5988838/1250370 - Deepak
3个回答

21

使用这种技术:

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"/>

3
getLastKnownLocation() 可能会返回 null,在这种情况下,此代码将崩溃。 - NickT
1
你无法证明一个否定性的断言,比如“从不”。它可能会返回空值,因此在调用.getLongitude()之前,你应该进行防御性编码并检查位置是否为空。 - NickT
1
我取消了反对投票,但我并不是想给它一个+1。事实上,“我想要现在的位置”的答案是“好吧,难受了,你不能总是得到它,你必须等到onLocationChanged()被触发”。这是事件驱动的,如果你打开手机并运行应用程序时没有GPS或网络信号,那么你就没戏了。无论如何,你添加了空值检查,所以很好。 - NickT
@NickT,我认为如果您使用移动SIM网络获取位置,则不会等待onLocationChanged被触发...这只会在使用WIFi或GPS获取位置时发生。 - Piyush Agarwal
1
谢谢,它正常工作了,你救了我的一天,晚上和更多的时间 :D - user3402040
显示剩余3条评论

3
尝试以下代码。希望它能起作用。
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

}
    }

必须添加所需的权限


0
    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();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接