天天看點

Android GPS定位

前段時間在做有關定位的功能,在網上搜尋了好多個解決方案,然而并沒有完全想要的那種,于是自己靈機一動,終于想到了一個不用那麼費勁的解決方案了。

廢話不多說,需求:項目中多個頁面需要用到定位功能。

                        解決方案:1、自定義一個定位服務,在服務裡面将位置資訊放入廣播資訊中發送

                                            2、将該服務在清單檔案注冊

                                            3、在MyApplication中啟動該服務

                                            4、在需要用到定位功能的頁面注冊廣播接收器接收廣播(如果需要擷取實時位置,就在接收到位置資訊時就更新位置資訊;多久重新整理一次可以根據自己需要喽)

服務代碼如下:

package com.dw.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.Iterator;

/**
 * Created by Administrator on 2017/2/14.
 */

public class AirnGPSService extends Service implements LocationListener, GpsStatus.Listener {
    private LocationManager locationManager = null;

    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);    //高精度
            criteria.setAltitudeRequired(false);    //不要求海拔
            criteria.setBearingRequired(false);    //不要求方位
            criteria.setCostAllowed(false);    //不允許有話費
            criteria.setPowerRequirement(Criteria.POWER_LOW);    //低功耗
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    this);
            locationManager.addGpsStatusListener(this);
            sendGPSLocationMessage(location);
        } else {
            sendGPSErrMessage("0");
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        sendGPSLocationMessage(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 void onGpsStatusChanged(int event) {
        /**
         * GPS狀态監聽
         */
        switch (event) {
            // 第一次定位
            case GpsStatus.GPS_EVENT_FIRST_FIX:
                break;
            // 衛星狀态改變
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                // 擷取目前狀态
                if (locationManager != null) {
                    GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                    // 擷取衛星顆數的預設最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    // 建立一個疊代器儲存所有衛星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
                            .iterator();
                    int count = 0;
                    String str_count = "";
                    while (iters.hasNext() && count <= maxSatellites) {
                        GpsSatellite s = iters.next();
                        if (s.getSnr() != 0) {//隻有信躁比不為0的時候才算搜到了星
                            count++;
                        }
                    }
                    if (count > 0) {
                        str_count = String.valueOf(count);
                    } else {
                        str_count = "未搜到衛星";
                    }
                    sendGpsSatelliteMessage(str_count);
                }
                break;
            // 定位啟動
            case GpsStatus.GPS_EVENT_STARTED:
                break;
            // 定位結束
            case GpsStatus.GPS_EVENT_STOPPED:
                break;
        }
    }

    /**
     * 發送位置資訊
     *
     * @param location
     */
    private void sendGPSLocationMessage(Location location) {
        if (location != null) {
            Intent intent = new Intent("AirnGPSServiceLoc");
            intent.putExtra("lat", String.valueOf(location.getLatitude()));
            intent.putExtra("lng", String.valueOf(location.getLongitude()));
            sendBroadcast(intent);
        }

    }

    /**
     * 發送衛星數量資訊
     */
    private void sendGpsSatelliteMessage(String wx) {
        Intent intent = new Intent("AirnGPSServiceLocErr");
        intent.putExtra("GpsSatellite", wx);
        sendBroadcast(intent);
    }

    /**
     * 發送錯誤資訊
     */
    private void sendGPSErrMessage(String errMsg) {
        Intent intent = new Intent("AirnGPSServiceLocErr");
        intent.putExtra("Errmsg", errMsg);
        sendBroadcast(intent);
    }

}
      

頁面的廣播接收器注冊、服務清單檔案注冊、服務啟動在此都不再多說。