Android GPS, Location Manager教程

本文详细介绍如何在Android应用中集成GPS定位功能。从添加必要的权限开始,到创建GPSTracker类实现位置跟踪,再到获取经纬度及处理GPS状态,最后展示了如何在活动中使用这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你正在开发任何基于位置或者地图的应用,你能通过自动定位用户的位置来使你的应用更加的智能。对于这种需求你需要在你的应用中加入GPS模块。这个教程解释了怎么使用GPS/ Location API工作


在AndroidMainfest.xml中添加需要的权限(Permission)

在eclipse IDE中创建一个新项目

1. 在eclipse中创建一个新项目 File => New => Android Project 然后填入需要的项

要想在你的应用中使用GPS,你需要在AndroidMainfest.xml文件中添加相应的权限。 如果你通过GPS来获取位置信息,你需要添加ACCESS_FINE_LOCATION(它包含了ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION)。 如果你想获取基于网络的位置信息,你也需要添加INTERNET权限许可。

打开你的AndroidMainfest.xml文件然后像下面这样修改。

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gpstracking"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="8" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidGPSTrackingActivity"
            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>
     
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
    <uses-permission android:name="android.permission.INTERNET" />
 
</manifest>

写GPS Manager类

2. 创建一个新的类命名为GPSTracker.java

3. 打开你的GPSTracker.java做如下修改。我们需要使用系统服务,所以这里需要继承Service类

public class GPSTracker extends Service implements LocationListener{

4. 给这个类添加全局变量和构造函数

public class GPSTracker extends Service implements LocationListener {
 
    private final Context mContext;
 
    // 标记GPS状态
    boolean isGPSEnabled = false;
 
    // 标记网络状态
    boolean isNetworkEnabled = false;
 
    boolean canGetLocation = false;
 
    Location location; // 位置
    double latitude; // 纬度
    double longitude; // 经度
 
    // 更新的最短距离 以米为单位
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 米
 
    // 更新的最短时间 以毫秒为单位
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 分钟
 
    // 声明一个 Location Manager
    protected LocationManager locationManager;
 
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

5. 我们在构造函数中调用了getLocation()函数。 在你的GPSTracker类中添加新函数getLocation()

GPSTracker.java
public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
 
            // 获取GPS状态
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
 
            // 获取网络状态
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 
            if (!isGPSEnabled && !isNetworkEnabled) {
                // 网络和GPS都不能使用
            } else {
                this.canGetLocation = true;
                // 首先通过网络获取位置信息
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // 如果GPS打开 通过GPS服务获取纬度/经度信息
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return location;
    }
    @Override
    public void onLocationChanged(Location location) {
    }
 
    @Override
    public void onProviderDisabled(String provider) {
    }
 
    @Override
    public void onProviderEnabled(String provider) {
    }
 
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

获取用户当前的位置(纬度和经度)

6. 在GPSTracker.java中添加下面的函数。(如果没有成功获取纬度经度信息将返回0.00)
GPSTracker.java
	/**
     * 获取纬度
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
         
        // 返回纬度
        return latitude;
    }
     
    /**
     * 获取经度
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
         
        // 返回经度
        return longitude;
    }

询问用户是否打开GPS(打开系统设置)

7. 如果用户关闭了GPS,我们可以让用户打开GPS。下面的code将显示一个提醒对话框,用户确认后自动跳转到GPS设置界面来打开GPS
GPSTracker.java
/**
     * 检查是否可以获取位置信息
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
     
    /**
     * 显示设置提醒对话框
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
      
        // 设置对话框标题
        alertDialog.setTitle("GPS is settings");
  
        // 设置对话框信息
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
  
        // 设置对话框图标
        //alertDialog.setIcon(R.drawable.delete);
  
        // 按下设置按钮
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
  
        // 按下取消按钮
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // 显示提醒信息
        alertDialog.show();
    }

停止使用GPS

在你的应用中调用下面的函数来停用GPS
	/**
     * 关闭GPS监听器
     * 在你的应用中调用下面的函数来停用GPS
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

最终代码(GPSTracker.java)
GPSTracker.java
package com.example.gpstracking;
 
import android.app.AlertDialog;
import android.app.Service;
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.os.IBinder;
import android.provider.Settings;
import android.util.Log;
 
public class GPSTracker extends Service implements LocationListener {
 
    private final Context mContext;
 
    // 标记GPS状态
    boolean isGPSEnabled = false;
 
    // 标记网络状态
    boolean isNetworkEnabled = false;
 
    // 标记能否获取位置信息
    boolean canGetLocation = false;
 
    Location location; // 位置
    double latitude; // 纬度
    double longitude; // 经度
 
    // 更新最多距离 米为单位
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 米
 
    // 更新最多时间 毫秒为单位
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 分钟
 
    // 声明一个 Location Manager
    protected LocationManager locationManager;
 
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
 
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
 
            // 获取GPS状态
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
 
            // 获取网络状态
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 
            if (!isGPSEnabled && !isNetworkEnabled) {
                // GPS 网络都不好用
            } else {
                this.canGetLocation = true;
                // 首先通过网络获取位置信息
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // 如果GPS打开,通过GPS服务获取位置信息
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return location;
    }
     
    /**
     * 停用GPS
     * 在应用中调用这个方法来停用GPS
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }
     
    /**
     * 获取纬度
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
         
        // return latitude
        return latitude;
    }
     
    /**
     * 获取经度
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
         
        // return longitude
        return longitude;
    }
     
    /**
     * 检查GPS 网络是否可用
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
     
    /**
     * 显示设置对话框
     * 按下设置按钮将打开设置选项
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
      
        // 设置对话框标题
        alertDialog.setTitle("GPS is settings");
  
        // 设置对话框信息
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
  
        // 按下设置按钮
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
  
        // 按下取消按钮
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
  
        // 显示提醒信息
        alertDialog.show();
    }
 
    @Override
    public void onLocationChanged(Location location) {
    }
 
    @Override
    public void onProviderDisabled(String provider) {
    }
 
    @Override
    public void onProviderEnabled(String provider) {
    }
 
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
 
}

用法

8. 你能通过简单的调用GPSTracker类的函数来获取用户当前位置信息。 打开你的main activity试一下下面的代码吧

检查gps是否可以使用

GPSTracker gps = new GPSTracker(this);
if(gps.canGetLocation()){ // gps可以使用} // return boolean true/false

获取纬度和经度

gps.getLatitude(); // 返回 纬度
gps.getLongitude(); // 返回 经度

显示GPS设置提醒对话框

gps.showSettingsAlert();

停用GPS

gps.stopUsingGPS();
AndroidGPSTrackingActivity.java
package com.example.gpstracking;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class AndroidGPSTrackingActivity extends Activity {
     
    Button btnShowLocation;
     
    // GPSTracker 类
    GPSTracker gps;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
         
        // 按钮的click事件
        btnShowLocation.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {        
                // 创建类对象
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);
 
                // GPS是否可用   
                if(gps.canGetLocation()){
                     
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                     
                    // \n 换行
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                }else{
                    // 不能获取位置信息
                    // GPS或网络不可用
                    // 询问用户打开GPS或网络设置
                    gps.showSettingsAlert();
                }
                 
            }
        });
    }
     
}

使用虚拟器测试你的GPS App

你可以使用其它方法来测试你的app。如果你有一台android设备,你可以直接安装你的app来测试它。如果你没有,你可以用本地的虚拟器来测试你的app。




原文地址  http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/  点击打开链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值