Service功能有:实时定位(后台进行)
Service不会,去百度谷歌
功能有
实时定位(30秒间隔)
判断是否在规定的时间段内
判断距离是否大于规定的距离
判断服务是否在开启的状态

服务代码:LocationService(Android Studio 2.3环境下)
实时定位(30秒间隔)
判断是否在规定的时间段内
判断距离是否大于规定的距离
这三个功能我都写在了一个里面,具体可以分类,看自己选择了

package zph.zhjx.com.chat.service;import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;import java.util.Timer;
import java.util.TimerTask;import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import zph.zhjx.com.chat.bean.Message_01;
import zph.zhjx.com.chat.contact.Contact;
import zph.zhjx.com.chat.imp.BeanImp;
import zph.zhjx.com.chat.util.DBUtil;public class LocationService extends Service {public final String TAG="LocationService";private AMapLocationClient locationClient = null;private AMapLocationClientOption locationOption = new AMapLocationClientOption();private Timer mTimer;private LatLng last_latlng;@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {Notification  noti = new Notification();noti.flags = Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;startForeground(1, noti);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {mTimer = new Timer();TimerTask  task = new TimerTask(){@Overridepublic void run() {initLocation();locationClient.startLocation();}};mTimer.scheduleAtFixedRate(task, 0, 30*1000);
//        flags = START_STICKY;return START_STICKY;}@Overridepublic void onDestroy() {
//        Toast.makeText(getApplicationContext(), "onDestroy", 0).show();if(locationClient!=null){locationClient.stopLocation();destroyLocation();}if(null!=mTimer){mTimer.cancel();}super.onDestroy();}private void initLocation(){if(locationClient==null){//初始化clientlocationClient = new AMapLocationClient(this.getApplicationContext());}//初始化定位参数initLocationOption();//设置定位参数locationClient.setLocationOption(locationOption);// 设置定位监听locationClient.setLocationListener(locationListener);}private void initLocationOption() {if (null == locationOption) {locationOption = new AMapLocationClientOption();}//定位精度:高精度模式locationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);//设置定位缓存策略locationOption.setLocationCacheEnable(false);//gps定位优先locationOption.setGpsFirst(false);//设置定位间隔
//        locationOption.setInterval(3000);locationOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是turelocationOption.setOnceLocation(true);//可选,设置是否单次定位。默认是falselocationOption.setOnceLocationLatest(true);//true表示获取最近3s内精度最高的一次定位结果;false表示使用默认的连续定位策略。locationOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用//AMapLocationClientOption.setLocationProtocol(AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP}/*** 定位监听*/AMapLocationListener locationListener = new AMapLocationListener() {@Overridepublic void onLocationChanged(AMapLocation loc) {if (null != loc) {//定位成功//              Toast.makeText(getApplicationContext(), loc.getLatitude()+"---"+loc.getLongitude(),0).show();Log.i(TAG,"定位成功");Log.i(TAG,"定位的经度位置是:"+loc.getLatitude());Log.i(TAG,"定位的维度位置是:"+loc.getLongitude());Log.i(TAG,"用户是:"+ DBUtil.getUserMessage().getPhone());if(isCurrentInTimeScope()) {UpDate(loc);}} else {//定位失败Log.i(TAG,"定位失败");}locationClient.stopLocation();destroyLocation();}};/**上传更新*/private void UpDate(AMapLocation loc) {final LatLng newlatlng=new LatLng(loc.getLatitude(),loc.getLongitude());BeanImp repo1;Retrofit retrofit1 = new Retrofit.Builder().baseUrl(Contact.Track_Interface).addConverterFactory(GsonConverterFactory.create()).build();repo1=retrofit1.create(BeanImp.class);String user_phone= DBUtil.getUserMessage().getPhone();if(user_phone!=null ||last_latlng==null) {if(IsDistanceMoreOneMile(last_latlng,newlatlng)) {Call<Message_01> call = repo1.AddMapTrackInToFuWuQi(user_phone, String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()));call.enqueue(new Callback<Message_01>() {@Overridepublic void onResponse(Call<Message_01> call, Response<Message_01> response) {Message_01 message = response.body();if (message != null)Log.i(TAG, message.toString());last_latlng = newlatlng;}@Overridepublic void onFailure(Call<Message_01> call, Throwable t) {}});}}}private void destroyLocation(){if (null != locationClient) {/*** 如果AMapLocationClient是在当前Activity实例化的,* 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy*/locationClient.onDestroy();locationClient = null;locationOption = null;}}/*** 判断两个点之间的距离大于规定的距离* */private boolean IsDistanceMoreOneMile(LatLng last,LatLng news){if(last==null){Log.i(TAG,"第一次为空");return true;}float mi=AMapUtils.calculateLineDistance(last, news);Log.i(TAG,"两次的间隔为:"+mi);if(mi>2.0f){return true;}elsereturn false;}/**** 判断当前时间是否在规定的时间段范围内* */public static boolean isCurrentInTimeScope() {int beginHour=5;int beginMin=0;int endHour=23;int endMin=0;boolean result = false;final long aDayInMillis = 1000 * 60 * 60 * 24;final long currentTimeMillis = System.currentTimeMillis();Time now = new Time();now.set(currentTimeMillis);Time startTime = new Time();startTime.set(currentTimeMillis);startTime.hour = beginHour;startTime.minute = beginMin;Time endTime = new Time();endTime.set(currentTimeMillis);endTime.hour = endHour;endTime.minute = endMin;if (!startTime.before(endTime)) {// 跨天的特殊情况(比如22:00-8:00)startTime.set(startTime.toMillis(true) - aDayInMillis);result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTimeTime startTimeInThisDay = new Time();startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis);if (!now.before(startTimeInThisDay)) {result = true;}} else {// 普通情况(比如 8:00 - 14:00)result = !now.before(startTime) && !now.after(endTime); // startTime <= now <= endTime}Log.i("LocationService","是否在时间间隔中"+result);return result;}
}

判断服务是否在开启状态
判断服务状态
GPS状态
打开GPS

public class ServiceUtil {/*** 用来判断某个服务是否开启* */public static boolean isServiceRunning(Context mContext, String className) {boolean isRunning = false;ActivityManager activityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);List<ActivityManager.RunningServiceInfo> serviceList= activityManager.getRunningServices(30);if (!(serviceList.size()>0)) {return false;}for (int i=0; i<serviceList.size(); i++) {if (serviceList.get(i).service.getClassName().equals(className) == true) {isRunning = true;break;}}return isRunning;}/*** 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的* @param context* @return true 表示开启*/public static final boolean isOPen(final Context context) {LocationManager locationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);// 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);// 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);if (gps || network) {return true;}return false;}/*** 强制帮用户打开GPS* @param context*/public static final void openGPS(Context context) {Intent GPSIntent = new Intent();GPSIntent.setClassName("com.android.settings","com.android.settings.widget.SettingsAppWidgetProvider");GPSIntent.addCategory("android.intent.category.ALTERNATIVE");GPSIntent.setData(Uri.parse("custom:3"));try {PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();} catch (PendingIntent.CanceledException e) {e.printStackTrace();}}}

使用:

boolean Flag= ServiceUtil.isServiceRunning(this,"zph.zhjx.com.chat.service.LocationService");

服务的开启和关闭

Intent intet1 = new Intent(SettingActivity.this, LocationService.class);
//开启
startService(intet1);
//关闭
stopService(intet1);

Android基于高德地图实时定位服务相关推荐

  1. android 基于高德地图的轨迹回放

    android 基于高德地图的轨迹回放 前段时间公司项目有一个需求,就是需要看到设备上传之后的轨迹路线,并且可以实现回放的整个过程,功能包括路线回放.地图位置插点.回放之后的轨迹标记颜色.回放加速等功 ...

  2. Android基于高德地图实现多人实时共享位置

    自开发上一款智慧旅游产品后,发现一个很有意义而且很实用的功能,就是模仿微信的位置共享,可以看到对方的位置,一直想模仿做出这样的效果.最近闲下来之后终于实现了.下面就把我的实现过程和心得分享给大家. 步 ...

  3. Android 集成高德地图——当前定位,添加图标,画路线,设置显示中心位置,比例,地图刷新位置监听,判断GPS开启,去打开GPS

    /*** 判断定位服务是否开启** @param* @return true 表示开启*/ public static boolean isLocationEnabled(Context contex ...

  4. Android 基于高德地图的锁屏后定位和轨迹自动纠偏(离线版)

    目录 一.后台如何持续获取定位 1.后台以及锁屏后持续定位异常的原因以及应对方案探索 2.后台持续获取定位失败的应对方案 二.对坐标点进行加工处理 (1).为什么要加工处理 (2).如何加工处理 本文 ...

  5. Android开发丶基于高德地图实现定位、搜索定位、绘制圆圈自定义图标及改变圆圈半径等功能

    前一段时间接了个需求,进入一个地图界面,可以获取当前位置信息,通过输入位置信息获取位置,绘制圆圈并可以实时改变圆圈半径等功能,地图SDK我们使用的是高德地图,仔细阅读了开发文档,发现这些需求都可以通过 ...

  6. 基于Android的高德地图的定位和运动轨迹记录的功能

           废话不多说,首先去高德地图的API上获取key(这一步很重要),因为没有KEY是无法获取高德地图的. 首先这是高德地图API的网址https://lbs.amap.com/,可以点击进去 ...

  7. 高德地图实时定位显示图标和名字

    前言:最近公司项目有个需要展示人员的实时定位和轨迹回放的需求,查阅了一些资料,最后决定用高德地图去实现. 注:人员的实时位置用的uniapp做的打包的app实时上传登录者的位置信息上传到后台,pc端获 ...

  8. 安卓高德地图实时定位方法的封装

    安卓地图的开发对于一个没有地图开发经验的人来说还是有点摸不着头脑的,我刚开始的时候就走了很多弯路,现在将自己实现的方法分享出来,供大家参考: 首先要去到高德地图的开方平台申请key值:点击打开链接 然 ...

  9. web网站开发基于高德地图浏览器定位

    准备工作: 首先,注册开发者账号,成为高德开放平台开发者 登陆之后,在进入「应用管理」 页面「创建新应用」 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI ) 」 拿到key ...

最新文章

  1. 汇总pandas中的dataframe的索引操作
  2. util.Date与sql.Date的相互转换以及区别
  3. apache用户名和密码验证
  4. 我失败的阿里程序员生涯
  5. Nacos 快速开始、版本选择、预备环境准备、下载源码或者安装包、从 Github 上下载源码方式、下载编译后压缩包方式、配置nacos、配置集群、启动服务器、服务注册发现和配置管理、关闭服务器
  6. WebApi管理和性能测试工具WebApiBenchmarks
  7. CBOW模型的学习、Trainer类的实现
  8. Java学习笔记2.3.4 运算符与表达式 - 逻辑运算符
  9. 李航博士:《统计学习方法》第二版上线啦!增加无监督学习!
  10. labview创建case结构_操作者框架(AF)系列视频学习笔记之视频三:创建简易操作者...
  11. 基于java jsp的铁路售票系统(火车票预订)ssh框架
  12. C++面向对象课程设计实例-图书馆借阅系统
  13. 西门子PLC S7-1200程序实例,博图版本V15,仅供电气编程者学习借鉴
  14. android sdk模拟器中文版,安卓sdk自带模拟器的使用
  15. table表格实现第一列固定
  16. 杭州卧兔:全球品牌出海峰会大咖集聚讲述品牌出海关键要素
  17. 分享一个很棒的免费壁纸网站
  18. Git 进阶 —— 时光穿梭机
  19. STM32单片机使用ADC功能驱动手指检测心跳模块
  20. 休闲卤味的商业江湖里,周黑鸭的巨变与出路

热门文章

  1. Java Essentials: Preventing ConcurrentModificationException
  2. 论文笔记 | Improving neural networks by preventing co-adaptation of feature detectors
  3. 白领商务出差开会高清音质蓝牙耳机,佩戴舒适高颜值蓝牙耳机
  4. CSS 3 基础知识(二)
  5. 《实现领域驱动设计》 (美)弗农著 10章 聚合
  6. 服务器的CPU跟家用电脑的一样吗,服务器该怎么选择CPU配置
  7. datax从gbase8a同步上亿大表到mysql5.7中
  8. 好用的手机Web网站开发工具:Mobirise for Mac
  9. 本地缓存天花板-Caffeine
  10. 互融云供应链代采金融系统:优化企业运作、有效控制成本