如何在Android中獲取當(dāng)前位置我在使用Android定位系統(tǒng)的網(wǎng)絡(luò)提供商獲取當(dāng)前的位置坐標(biāo)時(shí)遇到了麻煩。已經(jīng)閱讀了很多教程,并為我的項(xiàng)目實(shí)現(xiàn)了4或5個(gè)現(xiàn)有的類,它們都給了我最后的坐標(biāo),而不是當(dāng)前的坐標(biāo)。我很確定這個(gè)問題是我錯(cuò)過的基本問題,但我無法理解它到底是什么。我現(xiàn)在使用的密碼:這是我的主要活動(dòng)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;實(shí)際上,GPS定位工作得很好,但網(wǎng)絡(luò)定位卻不行。當(dāng)我移動(dòng)時(shí),當(dāng)我打開設(shè)備時(shí),坐標(biāo)上的GPS一直在變化,但當(dāng)我關(guān)閉它并在NetworkProvider上中繼時(shí),情況就不一樣了。
3 回答

繁星淼淼
TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
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"/>

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊

墨色風(fēng)雨
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
GPSTracker tracker = new GPSTracker(this); if (!tracker.canGetLocation()) { tracker.showSettingsAlert(); } else { latitude = tracker.getLatitude(); longitude = tracker.getLongitude(); }
添加回答
舉報(bào)
0/150
提交
取消