Android--使用手机GPS获取经纬度

有很多应用在打开应用的时候,就需要去获取当前手机的地址位置并且显示出地名等,现在介绍一种方法通过手机内置的GPS获取当前位置的经纬度.

思路: 首先判断手机当前是否打开GPS功能-->如果没有打开就通过代码帮助用户强制打开手机GPS功能-->根据手机GPS获取手机当前位置的经纬度.

注意:打开gps和访问网络的权限.

1.上代码:

1.1判断手机是否打开GPS-需要使用到Android系统的LocationManager对象.

/**
 * 判断手机GPS是否开启
 * @param mainActivity
 * @return
 */
public boolean isOpen(Context context) {
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //通过GPS卫星定位,定位级别到街
    boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    //通过WLAN或者移动网络确定位置
    boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (gps || network) {
        return true;
    }
    return false;
}

1.2用户未打开GPS,帮助用户打开该功能.

/**
 * 开启手机GPS
 */
public void openGPS(Context context) {
    Intent GPSIntent = new Intent();
    GPSIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvide");
    GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
    GPSIntent.setData(Uri.parse("custom:3"));

    try {
        //使用PendingIntent发送广播告诉手机去开启GPS功能
        PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
    } catch (PendingIntent.CanceledException e) {
        e.printStackTrace();
    }
}

1.3使用手机的GPS功能获取当前位置的经纬度

/**
 * GPS功能已经打开-->根据GPS去获取经纬度
 */
public void getGPSConfi() {
    Location location;
    if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }

    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        tv_content.setText("经纬度:" + latitude + "--" + longitude);
    } else {
        tv_content.setText("未获取到经纬度数据");
    }
}

2.需要的权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
3.界面很简单,就不贴代码了,一个按钮和一个文本框显示经纬度




  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值