android利用GPS和高德地圖獲取定位案例

 

1、main.xmljava

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/text_location"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:editable="false" />

</LinearLayout>
View Code

 

2、activityandroid

package com.mytest.huilife;

import java.util.Date;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class LocationActivity extends Activity {

    private static final String LOG_TAG = "LocationActivity";

    private LocationManager locationManager;
    private ProgressDialog progressDialog;
    private EditText textLoaction;
    private String loactionSoureFrom; // 定位數據來自哪,GPS,仍是網絡
    // private TimerTask timerTask;
    // private Timer timer;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if(progressDialog!=null){
                progressDialog.dismiss();
            }
            
            //更新界面位置信息
            updateTextLoaction();

        };
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (locationManager != null && locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }

        // if (timer != null) {
        // timer.cancel();
        // }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
        textLoaction = (EditText) this.findViewById(R.id.text_location);

        if (NetWorkUtil.isNetAvailable(this) == false) {
            Toast.makeText(this, "請打開網絡鏈接", Toast.LENGTH_SHORT).show();
            return;
        }

        if (NetWorkUtil.isGPSAvailable(this)) {
            // 從GPS獲取位置信息
            getLocationFromGPS();
        } else {

            // 若是GPS不可用
            new AlertDialog.Builder(this).setTitle("你是否要打開GPS?")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            // 讓用戶打開GPS
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, 0);
                        }

                    }).setNegativeButton("否", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 從網絡獲取位置信息
                            getLocationFromNetWork();
                        }
                    }).show();

        }

    }

    private double latitude; // 緯度
    private double longitude; // 經度
    private double altitude; // 海拔
    private String getLocationLastTime;

    private void updateTextLoaction() {
        // Log.v(LOG_TAG,"updateTextLoaction:"+"經度:"+longitude+",緯度:"+latitude+",海拔:"+altitude);
        textLoaction.setText("定位數據來自:" + loactionSoureFrom + ",\n經度:" + longitude + "\n緯度:" + latitude + ",\n海拔:"
                + altitude + ",獲取時間:" + getLocationLastTime);

    }

    /**
     * 採用高德地圖,執行網絡定位,並在定位中顯示等待
     */
    private void getLocationFromNetWork() {
        progressDialog = new ProgressDialog(LocationActivity.this);
        progressDialog.setMessage("正在定位中...");
        progressDialog.setCanceledOnTouchOutside(false);// 點擊外部,進度提示框不會消失
        progressDialog.show();

        // 初始化高德地圖定位
        initAmapLocation();

    }

    /**
     * 初始化高德定位
     */
    private void initAmapLocation() {
        LocationManagerProxy locationManagerProxy = LocationManagerProxy.getInstance(this);
        locationManagerProxy.setGpsEnable(false);
        locationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, 3 * 1000, 10,
                new AMapLocationListener() {

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {

                    }

                    @Override
                    public void onLocationChanged(Location location) {

                    }

                    @Override
                    public void onLocationChanged(AMapLocation amapLocation) {
                        if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
                            // 定位成功回調信息,設置相關消息
                            latitude = amapLocation.getLatitude();
                            longitude = amapLocation.getLongitude();
                            altitude = amapLocation.getAltitude();
                            Date date = new Date(amapLocation.getTime());
                            String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(),
                                    date.getSeconds());
                            getLocationLastTime = dateStr;
//                            Log.v(LOG_TAG, "(amap)位置發生改變," + "時間:" + dateStr + "經度:" + amapLocation.getLongitude()
//                                    + "緯度:" + amapLocation.getLatitude() + "海拔:" + amapLocation.getAltitude());
                            if (progressDialog != null) {
                                progressDialog.dismiss();
                            }

                            loactionSoureFrom = "amap";

                            // 發送消息,更新界面位置信息
                            handler.sendEmptyMessage(0);

                        }

                    }
                });
    }

    /**
     * 從GPS獲取位置信息
     */
    private void getLocationFromGPS() {
        
        progressDialog = new ProgressDialog(LocationActivity.this);
        progressDialog.setMessage("正在定位中...");
        progressDialog.setCanceledOnTouchOutside(false);// 點擊外部,進度提示框不會消失
        progressDialog.show();
        
        
        // 獲取manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        String bestProvider = locationManager.getBestProvider(getCriteria(), true);
        Location location = locationManager.getLastKnownLocation(bestProvider);

        if (location != null) {

            Date date = new Date(location.getTime());
            String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(), date.getSeconds());
            getLocationLastTime = dateStr;
            longitude = location.getLongitude(); // 緯度
            latitude = location.getLatitude(); // 經度
            altitude = location.getAltitude(); // 海拔

            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            loactionSoureFrom = "GPS";

            // 更新界面位置信息
            updateTextLoaction();

        } else {

//            Log.i(LOG_TAG, "從GPS獲取數據爲空");

            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            loactionSoureFrom = "GPS";

            // Toast.makeText(this, "從GPS獲取位置信息,獲得數據爲空",
            // Toast.LENGTH_SHORT).show();
            new AlertDialog.Builder(this).setTitle("GPS數據爲空,改從網絡?")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            getLocationFromNetWork();

                        }

                    }).setNegativeButton("否", null).show();

        }

        locationManager.addGpsStatusListener(gpsListener);

        // 綁定監聽,有4個參數
        // 參數1,設備:有GPS_PROVIDER和NETWORK_PROVIDER兩種
        // 參數2,位置信息更新週期,單位毫秒
        // 參數3,位置變化最小距離:當位置距離變化超過此值時,將更新位置信息
        // 參數4,監聽
        // 備註:參數2和3,若是參數3不爲0,則以參數3爲準;參數3爲0,則經過時間來定時更新;二者爲0,則隨時刷新
        // 3秒更新一次,或最小位移變化超過1米更新一次;
        // 注意:此處更新準確度很是低,推薦在service裏面啓動一個Thread,在run中sleep(10000);而後執行handler.sendMessage(),更新位置
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);

    }

    /**
     * 設置查詢條件
     * 
     * @return
     */
    private Criteria getCriteria() {
        // 建立查詢條件
        Criteria criteria = new Criteria();
        // 設置定位精確度 Criteria.ACCURACY_COARSE比較粗略,Criteria.ACCURACY_FINE則比較精細
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 設置是否要求速度
        criteria.setSpeedRequired(false);
        // 設置是否容許運營商收費
        criteria.setCostAllowed(false);
        // 設置是否須要方位信息
        criteria.setBearingRequired(false);
        // 設置是否須要海拔信息
        criteria.setAltitudeRequired(false);
        // 設置對電源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        return criteria;
    }

    /**
     * 位置監聽
     */
    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
            // GPS狀態爲可見時
            case LocationProvider.AVAILABLE:
                // Log.i(LOG_TAG, "當前GPS狀態爲可見狀態");
                break;
            // GPS狀態爲服務區外時
            case LocationProvider.OUT_OF_SERVICE:
                // Log.i(LOG_TAG, "當前GPS狀態爲服務區外狀態");
                break;
            // GPS狀態爲暫停服務時
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                // Log.i(LOG_TAG, "當前GPS狀態爲暫停服務狀態");
                break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            Date date = new Date(location.getTime());
            String dateStr = String.format("%d:%d %d", date.getHours(), date.getMinutes(), date.getSeconds());
            getLocationLastTime = dateStr;
            longitude = location.getLongitude(); // 緯度
            latitude = location.getLatitude(); // 經度
            altitude = location.getAltitude(); // 海拔
            // Log.v(LOG_TAG, "GPS位置發生改變," + "時間:" + dateStr + "經度:" +
            // location.getLongitude() + "緯度:"
            // + location.getLatitude() + "海拔:" + location.getAltitude());

            if (progressDialog != null) {
                progressDialog.dismiss();
            }

            loactionSoureFrom = "GPS";

            // 發送消息,更新界面位置信息
            handler.sendEmptyMessage(0);

        }
    };

    /**
     * GPS狀態監聽
     */
    GpsStatus.Listener gpsListener = new GpsStatus.Listener() {

        @Override
        public void onGpsStatusChanged(int event) {
            switch (event) {
            case GpsStatus.GPS_EVENT_FIRST_FIX:
//                Log.v(LOG_TAG, "第一次定位");
                break;
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
//                Log.v(LOG_TAG, "衛星狀態發生改變");
                break;
            case GpsStatus.GPS_EVENT_STARTED:
//                Log.v(LOG_TAG, "啓動定位");
                break;
            case GpsStatus.GPS_EVENT_STOPPED:
//                Log.v(LOG_TAG, "結束定位");
                break;
            }

        }
    };

}
View Code

 

3、NetWorkUtilgit

package com.mytest.huilife;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetWorkUtil {

    /**
     * 判斷網絡是否可用
     * @param context
     * @return
     */
    public static boolean isNetAvailable(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netWorkInfo = connManager.getActiveNetworkInfo();
        if(netWorkInfo==null || !netWorkInfo.isAvailable()){
            return false;
        }
    
        return true;
    }
    
    
    /**
     * 判斷GPS是否可用
     */
    public static boolean isGPSAvailable(Context context) {
        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean net = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(gps || net){
            return true;
        }
        return false; 
    }    
        
}
View Code

 

 

4、AndroidMainfest.xmlapi

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.huilife"
    android:versionCode="2"
    android:versionName="2" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="??????在此輸入高德地圖的key" />

        <activity
            android:name=".LocationActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".GPSActivity" >
        </activity>
        <activity android:name=".LocationActivity" >
        </activity>
    </application>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />

</manifest>
View Code

 

5、小結網絡

一、導入高德地圖的jar包(Android_Location_V1.2.0)。app

二、用了一個手機卡的舊手機測試,GPS雖然打開,但獲取數據爲空,改用從網絡獲取。ide

三、上述引用,注意在androidmainfest.xml中配置高德地圖的相關meta、權限等。測試

(具體配置參考官網:http://lbs.amap.com/api/android-location-sdk/guide/project/)ui

相關文章
相關標籤/搜索