码迷,mamicode.com
首页 > 移动开发 > 详细

关于Android自带的定位处理

时间:2015-12-31 12:07:47      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

工作需要这里对Android自带定位做个小小的记录,GPS测试过可用,网络的,需要再次测试,但是方式都差不多,简单总结如下。

1、首先需要添加权限

  <!-- 这个权限用于访问GPS定位-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <!-- 这个权限用于进行网络定位-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET" />

2、然后推荐在服务里做定位处理MyService可以继承Location网上很多,这里不再继承 LocationListener 了,继承的方法有很多上面有链接。

主要代码实现如下

要使用的参数

    private LocationManager mLocationManager;
    private Location mLocation;
    private double lat = 0;
    private double lng = 0;
    private double alt = 0;
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 刷新距离10m
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 5; // 5 秒

onCreate方法里

 @Override
    public void onCreate() {
        super.onCreate();
        PDALogger.d("onCreate");
        ctx = PdaApplication.getInstance();
        getLocation();//读取手机端GPS
        mHandler.postDelayed(uploadGPSRunnable, 3000);
    }

下面是这个方法getLocation(),划线部分可要可不要

public Location getLocation() {
        mLocationManager = (LocationManager) ctx.getSystemService(LOCATION_SERVICE);
        // getting GPS status
        boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            }
            //get the location by gps
            if (isGPSEnabled) {
                if (mLocation == null) {
                    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mGPSLocationListener);
                    PDALogger.d("GPS Enabled");
                    if(mLocationManager!=null){
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            } else if (isNetworkEnabled) {// First get location from Network Provider
                if(mLocation==null){
                    mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mNetWorkLocationListener);
                    PDALogger.d("Network");
                    if(mLocationManager!=null){
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                }
            }

        }
        return mLocation;
    }

这里是两个监听器GPS和网络的

/**
     * GPS定位监听器
     */
    public final LocationListener mGPSLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    /**
     * 网络定位监听器
     */
    public final LocationListener mNetWorkLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

定位数据保存,划线处可不要

 /**
     * 定位数据随时保存
     * @param location
     * @return
     */
    private Location updateToNewLocation(Location location) {
        String latLongString;
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            alt = location.getAltitude();
             latLongString = "\n纬度:" + lat + "\n经度:" + lng + "\n海拔:" + alt;
             PDALogger.d(latLongString);
            mLocation = mLocation;
        } else {
            PDALogger.d("无法获取地理信息,请稍后...");
        }
        return location;
    }

上面就是整个代码使用的方式了,下面是整个Service代码

技术分享
package com.xvli.comm;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;

import com.xvli.application.PdaApplication;
import com.xvli.utils.PDALogger;

public class MyService extends Service {
    private Context ctx;
    private LocationManager mLocationManager;
    private Location mLocation;
    private double lat = 0;
    private double lng = 0;
    private double alt = 0;
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 刷新距离10m
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 5; // 5 秒


    public MyService() {
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    PDALogger.d("onCreate");
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        PDALogger.d("onCreate");
        ctx = PdaApplication.getInstance();
        getLocation();//读取手机端GPS
        mHandler.postDelayed(uploadGPSRunnable, 3000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        PDALogger.d("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PDALogger.d("onDestroy");
        if (uploadGPSRunnable != null) {
            mHandler.removeCallbacks(uploadGPSRunnable);
        }

        //=================================
        //关闭定位监听器
        if (mLocationManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mLocationManager.removeUpdates(mGPSLocationListener);
            mLocationManager.removeUpdates(mNetWorkLocationListener);
            mLocationManager = null;
        }

    }

    @Override
    public boolean onUnbind(Intent intent) {
        PDALogger.d("onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        PDALogger.d("onRebind");
        super.onRebind(intent);
    }
//============================================================================
    Runnable uploadGPSRunnable = new Runnable() {
        @Override
        public void run() {
            PDALogger.d("这里上传GPS:经度:"+lat+",维度:"+lng+",海拔:"+alt);
            mHandler.postDelayed(this, Config.GPSTIME * 1000);
        }
    };

    /**
     * GPS定位监听器
     */
    public final LocationListener mGPSLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    /**
     * 网络定位监听器
     */
    public final LocationListener mNetWorkLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

    /**
     * 定位数据随时保存
     * @param location
     * @return
     */
    private Location updateToNewLocation(Location location) {
        String latLongString;
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
            alt = location.getAltitude();
             latLongString = "\n纬度:" + lat + "\n经度:" + lng + "\n海拔:" + alt;
             PDALogger.d(latLongString);
            mLocation = mLocation;
        } else {
            PDALogger.d("无法获取地理信息,请稍后...");
        }
        return location;
    }


    public Location getLocation() {
        mLocationManager = (LocationManager) ctx.getSystemService(LOCATION_SERVICE);
        // getting GPS status
        boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            }
            //get the location by gps
            if (isGPSEnabled) {
                if (mLocation == null) {
                    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mGPSLocationListener);
                    PDALogger.d("GPS Enabled");
                    if(mLocationManager!=null){
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            } else if (isNetworkEnabled) {// First get location from Network Provider
                if(mLocation==null){
                    mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mNetWorkLocationListener);
                    PDALogger.d("Network");
                    if(mLocationManager!=null){
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                }
            }

        }
        return mLocation;
    }

}
View Code

 

关于Android自带的定位处理

标签:

原文地址:http://www.cnblogs.com/bxfx111/p/5091061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!