GVKun编程网logo

如何在Android中获取当前位置的经纬度(如何在android中获取当前位置的经纬度坐标)

3

这篇文章主要围绕如何在Android中获取当前位置的经纬度和如何在android中获取当前位置的经纬度坐标展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何在Android中获取当前位置的经纬度

这篇文章主要围绕如何在Android中获取当前位置的经纬度如何在android中获取当前位置的经纬度坐标展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何在Android中获取当前位置的经纬度的优缺点,解答如何在android中获取当前位置的经纬度坐标的相关问题,同时也会为您带来Android 11:如何获取当前位置、Android GPS获取当前经纬度坐标、Android – 可靠地获取当前位置、android – 在应用启动期间获取当前位置的实用方法。

本文目录一览:

如何在Android中获取当前位置的经纬度(如何在android中获取当前位置的经纬度坐标)

如何在Android中获取当前位置的经纬度(如何在android中获取当前位置的经纬度坐标)

在我的应用程序中,我在打开应用程序时获得了当前位置的纬度和经度,但是在关闭应用程序时却没有得到。

我正在使用Service类在应用程序中获取当前位置的纬度和经度。

请告诉我即使关闭应用程序也如何获取当前位置的纬度和经度

答案1

小编典典

几个月前,我创建了GPSTracker库来帮助我获取GPS位置。如果您需要查看GPSTracker> getLocation

AndroidManifest.xml

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

活动

import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.TextView;public class MainActivity extends Activity {    TextView textview;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.geo_locations);        // check if GPS enabled        GPSTracker gpsTracker = new GPSTracker(this);        if (gpsTracker.getIsGPSTrackingEnabled())        {            String stringLatitude = String.valueOf(gpsTracker.latitude);            textview = (TextView)findViewById(R.id.fieldLatitude);            textview.setText(stringLatitude);            String stringLongitude = String.valueOf(gpsTracker.longitude);            textview = (TextView)findViewById(R.id.fieldLongitude);            textview.setText(stringLongitude);            String country = gpsTracker.getCountryName(this);            textview = (TextView)findViewById(R.id.fieldCountry);            textview.setText(country);            String city = gpsTracker.getLocality(this);            textview = (TextView)findViewById(R.id.fieldCity);            textview.setText(city);            String postalCode = gpsTracker.getPostalCode(this);            textview = (TextView)findViewById(R.id.fieldPostalCode);            textview.setText(postalCode);            String addressLine = gpsTracker.getAddressLine(this);            textview = (TextView)findViewById(R.id.fieldAddressLine);            textview.setText(addressLine);        }        else        {            // can''t get location            // GPS or Network is not enabled            // Ask user to enable GPS/network in settings            gpsTracker.showSettingsAlert();        }    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);        return true;    }}

GPS追踪器

import java.io.IOException;import java.util.List;import java.util.Locale;import android.app.AlertDialog;import android.app.Service;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.location.Address;import android.location.Geocoder;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.os.IBinder;import android.provider.Settings;import android.util.Log;/** * Create this Class from tutorial :  * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial *  * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation *  */public class GPSTracker extends Service implements LocationListener {    // Get Class Name    private static String TAG = GPSTracker.class.getName();    private final Context mContext;    // flag for GPS Status    boolean isGPSEnabled = false;    // flag for network status    boolean isNetworkEnabled = false;    // flag for GPS Tracking is enabled     boolean isGPSTrackingEnabled = false;    Location location;    double latitude;    double longitude;    // How many Geocoder should return our GPSTracker    int geocoderMaxResults = 1;    // 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;    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information    private String provider_info;    public GPSTracker(Context context) {        this.mContext = context;        getLocation();    }    /**     * Try to get my current location by GPS or Network Provider     */    public void 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);            // Try to get location if you GPS Service is enabled            if (isGPSEnabled) {                this.isGPSTrackingEnabled = true;                Log.d(TAG, "Application use GPS Service");                /*                 * This provider determines location using                 * satellites. Depending on conditions, this provider may take a while to return                 * a location fix.                 */                provider_info = LocationManager.GPS_PROVIDER;            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled                this.isGPSTrackingEnabled = true;                Log.d(TAG, "Application use Network State to get GPS coordinates");                /*                 * This provider determines location based on                 * availability of cell tower and WiFi access points. Results are retrieved                 * by means of a network lookup.                 */                provider_info = LocationManager.NETWORK_PROVIDER;            }             // Application can use GPS or Network Provider            if (!provider_info.isEmpty()) {                locationManager.requestLocationUpdates(                    provider_info,                    MIN_TIME_BW_UPDATES,                    MIN_DISTANCE_CHANGE_FOR_UPDATES,                     this                );                if (locationManager != null) {                    location = locationManager.getLastKnownLocation(provider_info);                    updateGPSCoordinates();                }            }        }        catch (Exception e)        {            //e.printStackTrace();            Log.e(TAG, "Impossible to connect to LocationManager", e);        }    }    /**     * Update GPSTracker latitude and longitude     */    public void updateGPSCoordinates() {        if (location != null) {            latitude = location.getLatitude();            longitude = location.getLongitude();        }    }    /**     * GPSTracker latitude getter and setter     * @return latitude     */    public double getLatitude() {        if (location != null) {            latitude = location.getLatitude();        }        return latitude;    }    /**     * GPSTracker longitude getter and setter     * @return     */    public double getLongitude() {        if (location != null) {            longitude = location.getLongitude();        }        return longitude;    }    /**     * GPSTracker isGPSTrackingEnabled getter.     * Check GPS/wifi is enabled     */    public boolean getIsGPSTrackingEnabled() {        return this.isGPSTrackingEnabled;    }    /**     * Stop using GPS listener     * Calling this method will stop using GPS in your app     */    public void stopUsingGPS() {        if (locationManager != null) {            locationManager.removeUpdates(GPSTracker.this);        }    }    /**     * Function to show settings alert dialog     */    public void showSettingsAlert() {        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);        //Setting Dialog Title        alertDialog.setTitle(R.string.GPSAlertDialogTitle);        //Setting Dialog Message        alertDialog.setMessage(R.string.GPSAlertDialogMessage);        //On Pressing Setting button        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which)             {                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);                mContext.startActivity(intent);            }        });        //On pressing cancel button        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which)             {                dialog.cancel();            }        });        alertDialog.show();    }    /**     * Get list of address by latitude and longitude     * @return null or List<Address>     */    public List<Address> getGeocoderAddress(Context context) {        if (location != null) {            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);            try {                /**                 * Geocoder.getFromLocation - Returns an array of Addresses                  * that are known to describe the area immediately surrounding the given latitude and longitude.                 */                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);                return addresses;            } catch (IOException e) {                //e.printStackTrace();                Log.e(TAG, "Impossible to connect to Geocoder", e);            }        }        return null;    }    /**     * Try to get AddressLine     * @return null or addressLine     */    public String getAddressLine(Context context) {        List<Address> addresses = getGeocoderAddress(context);        if (addresses != null && addresses.size() > 0) {            Address address = addresses.get(0);            String addressLine = address.getAddressLine(0);            return addressLine;        } else {            return null;        }    }    /**     * Try to get Locality     * @return null or locality     */    public String getLocality(Context context) {        List<Address> addresses = getGeocoderAddress(context);        if (addresses != null && addresses.size() > 0) {            Address address = addresses.get(0);            String locality = address.getLocality();            return locality;        }        else {            return null;        }    }    /**     * Try to get Postal Code     * @return null or postalCode     */    public String getPostalCode(Context context) {        List<Address> addresses = getGeocoderAddress(context);        if (addresses != null && addresses.size() > 0) {            Address address = addresses.get(0);            String postalCode = address.getPostalCode();            return postalCode;        } else {            return null;        }    }    /**     * Try to get CountryName     * @return null or postalCode     */    public String getCountryName(Context context) {        List<Address> addresses = getGeocoderAddress(context);        if (addresses != null && addresses.size() > 0) {            Address address = addresses.get(0);            String countryName = address.getCountryName();            return countryName;        } else {            return null;        }    }    @Override    public void onLocationChanged(Location location) {    }    @Override    public void onStatusChanged(String provider, int status, Bundle extras) {    }    @Override    public void onProviderEnabled(String provider) {    }    @Override    public void onProviderDisabled(String provider) {    }    @Override    public IBinder onBind(Intent intent) {        return null;    }}

注意
如果方法/答案不起作用。您需要使用官方的Google Provider: FusedLocationProviderApi 。

Android 11:如何获取当前位置

Android 11:如何获取当前位置

我错了。 FusedLocationProviderClient.getCurrentLocation()FusedLocationProviderClient.requestLocationUpdates()都可以在Android 11上运行。除非用户启用了“ Wi-Fi扫描”,“蓝牙扫描”以及最重要的是“ Google位置准确性”,否则它们的运行速度非常慢。用户仅激活“使用位置”是不够的。

Android GPS获取当前经纬度坐标

Android GPS获取当前经纬度坐标

APP中可能会遇到一种需求,就是将当前所在位置的坐标传到服务器上,今天我提供三种途径去获取经纬度坐标信息,第一种是通过Android API来实现,第二种通过百度地图API来实现,第三种通过天地图API来实现。

第一种方法(Android API实现),废话不多说,上代码。

MainActivity代码如下:

public class MainActivity extends Activity {
 private static final String TAG = MainActivity.class.getSimpleName();
 private double latitude = 0.0;
 private double longitude = 0.0;
 private TextView info;
 private LocationManager locationManager;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 info = (TextView) findViewById(R.id.tv);
 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
 getLocation();
 //gps已打开
 } else {
 toggleGPS();
 new Handler() {
 }.postDelayed(new Runnable() {
 @Override
 public void run() {
  getLocation();
 }
 }, 2000);
 
 }
 }
 
 private void toggleGPS() {
 Intent gpsIntent = new Intent();
 gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
 gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
 gpsIntent.setData(Uri.parse("custom:3"));
 try {
 PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
 } catch (CanceledException e) {
 e.printStackTrace();
 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
 Location location1 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
 if (location1 != null) {
 latitude = location1.getLatitude(); // 经度
 longitude = location1.getLongitude(); // 纬度
 }
 }
 }
 
 private void getLocation() {
 Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
 if (location != null) {
 latitude = location.getLatitude();
 longitude = location.getLongitude();
 } else {
 
 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
 }
 info.setText("纬度:" + latitude + "\n" + "经度:" + longitude);
 }
 
 LocationListener locationListener = new LocationListener() {
 // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {
 }
 
 // Provider被enable时触发此函数,比如GPS被打开
 @Override
 public void onProviderEnabled(String provider) {
 Log.e(TAG, provider);
 }
 
 // Provider被disable时触发此函数,比如GPS被关闭
 @Override
 public void onProviderDisabled(String provider) {
 Log.e(TAG, provider);
 }
 
 // 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
 @Override
 public void onLocationChanged(Location location) {
 if (location != null) {
 Log.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
 latitude = location.getLatitude(); // 经度
 longitude = location.getLongitude(); // 纬度
 }
 }
 };
 
 /*
 * 
 * 打开和关闭gps第二种方法
 * private void openGPSSettings() {
 //获取GPS现在的状态(打开或是关闭状态)
 boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER);
 if (gpsEnabled) {
 //关闭GPS
 Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, false);
 } else {
 //打开GPS 
 Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
 }
 }*/
}

main.xml布局如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/layout"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@android:color/white"
 android:orientation="vertical" >
 
 <TextView
  android:id="@+id/tv"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="经纬度信息:"
  android:textColor="#660000"
  android:textSize="20sp" />
 
</LinearLayout>

清单文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.tqmapdemo"
 android:versionCode="1"
 android:versionName="1.0" >
 <uses-sdk
  android:minSdkVersion="8"
  android:targetSdkVersion="18" />
 
 <!-- 连接互联网Internet权限 -->
 <uses-permission android:name="android.permission.INTERNET" />
 <!-- GPS定位权限 -->
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 
 <application
  android:allowBackup="true"
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name"
  android:theme="@android:style/Theme.Black" >
  <activity
   android:name="com.example.tqmapdemo.MainActivity"
   android:label="@string/app_name" >
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
 
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
 </application>
</manifest>

运行结果如下

下载Demo请猛戳

第二种方法(百度地图API实现,注:需要自己申请apikey

下载Demo请猛戳


第三种方法(天地图API实现)

下载Demo请猛戳


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • Android通过原生APi获取所在位置的经纬度
  • android通过gps获取定位的位置数据和gps经纬度
  • Android 通过当前经纬度获得城市的实例代码
  • Android获取当前位置的经纬度数据
  • Android获取经纬度计算距离介绍
  • android手机获取gps和基站的经纬度地址实现代码
  • Android简单获取经纬度的方法
  • Android编程实现根据经纬度查询地址并对获取的json数据进行解析的方法
  • android如何获取经纬度
  • Android通过原生方式获取经纬度与城市信息的方法

Android – 可靠地获取当前位置

Android – 可靠地获取当前位置

我的应用程序在特定时间检查用户是否在指定位置.我使用警报管理器启动进行此调用的服务:
locationManager.requestLocationUpdates(bestProvider,listener);

并检查:

locationManager.getLastKNownLocation(bestProvider);

但是我在真实设备上运行时遇到了问题.首先,getLastKNownLocation很可能是GPS所在的最后一个位置,可能是任何地方(即,它可能距离用户的当前位置数英里).所以我只是等待requestLocationUpdates回调,如果它们在两分钟内不存在,则删除监听器并放弃,对吧?

错了,因为如果用户的位置已经稳定(即,他们最近使用过GPS并且没有移动过),那么我的听众永远不会被调用,因为位置没有改变.但GPS将一直运行,直到我的听众被移除,耗尽电池……

获取当前位置的正确方法是什么,而不会误认为当前位置的旧位置?我不介意等几分钟.

编辑:有可能我错误的是没有被叫的听众,它可能只需要比我想象的要长一点……很难说.我仍然很欣赏一个确定的答案.

解决方法

代码可能是这样的:
public class MyLocation {
    Timer timer1;
    LocationManager lm;

    public boolean getLocation(Context context)
    {
        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,locationListenerGps);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(),20000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            lm.removeUpdates(this);
            //use location as it is the latest value
        }
        public void onProviderdisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider,int status,Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             Location location=lm.getLastKNownLocation(LocationManager.NETWORK_PROVIDER);
             //use location as we have not received the new value from listener
        }
    }
}

我们启动监听器并等待更新一段时间(在我的示例中为20秒).如果我们在此期间收到更新,我们会使用它.如果我们在此期间没有收到更新,我们使用getLastKNownLocation值并停止监听器.

你可以在这里看到我的完整代码What is the simplest and most robust way to get the user’s current location on Android?

编辑(由提问者):这是答案的大部分,但我的最终解决方案使用Handler而不是计时器.

android – 在应用启动期间获取当前位置

android – 在应用启动期间获取当前位置

美好的一天!
我正在开发一个监控用户位置的 Android应用程序.我正在使用LocationManager来获取用户位置,使用以下方法
public void onLocationChanged(Location theLocation) {}

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

但是,现在我计划在他们的应用登录后立即获取用户的位置.有没有办法通过LocationManager我可以在我的应用程序启动后手动获取位置坐标?

解决方法

使用这种技术:
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"/>

今天关于如何在Android中获取当前位置的经纬度如何在android中获取当前位置的经纬度坐标的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android 11:如何获取当前位置、Android GPS获取当前经纬度坐标、Android – 可靠地获取当前位置、android – 在应用启动期间获取当前位置的相关知识,请在本站搜索。

本文标签: