如何在Android中获取当前位置我在使用Android定位系统的网络提供商获取当前的位置坐标时遇到了麻烦。已经阅读了很多教程,并为我的项目实现了4或5个现有的类,它们都给了我最后的坐标,而不是当前的坐标。我很确定这个问题是我错过的基本问题,但我无法理解它到底是什么。我现在使用的密码:这是我的主要活动package com.example.locationtests;import android.os.Bundle;import android.app.Activity;import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GPSTracker mGPS = new GPSTracker(this);
TextView text = (TextView) findViewById(R.id.texts);
if(mGPS.canGetLocation ){
mGPS.getLocation();
text.setText("Lat"+mGPS.getLatitude()+"Lon"+mGPS.getLongitude());
}else{
text.setText("Unabletofind");
System.out.println("Unable");
}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;}}这是我用来跟踪的类:package com.example.locationtests;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;
import android.content.Intent;import android.location.Location;import android.location.LocationListener;
import android.location.LocationManager;import android.os.Bundle;import android.provider.Settings;
import android.util.Log;public final class GPSTracker implements LocationListener {
private final Context mContext;
// flag for GPS status
public boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;实际上,GPS定位工作得很好,但网络定位却不行。当我移动时,当我打开设备时,坐标上的GPS一直在变化,但当我关闭它并在NetworkProvider上中继时,情况就不一样了。
3 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
LocationListener
private final LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(final Location location) { //your code here }};
LocationManager
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mLocationListener);}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
桃花长相依
TA贡献1860条经验 获得超8个赞
添加回答
举报
0/150
提交
取消