实现定位服务的两种方法

xiaoxiao2021-02-28  170

第一种,使用Google提供的LocationManager类。不过只能获取坐标,需要自己多坐标进行处理。 我同样是以服务的形式调用。

//添加定位权限 <!-- 这个权限用于访问GPS定位--> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> package com.greysun.he.service; import com.greysun.he.bin.AppSystem; import android.app.Service; 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.telephony.SmsManager; import android.util.Log; public class ListenSeat extends Service{ private LocationManager manager; private LocationListener locationListener; @Override public int onStartCommand(Intent intent,int flags,int startId){ System.out.println("开启位置监听"+AppSystem.getListenerNumber()); manager = (LocationManager)getSystemService(LOCATION_SERVICE); Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //第一次获得设备的位置 updateLocation(location); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateLocation(location); } @Override public void onProviderDisabled(String str) { System.out.println(str); } @Override public void onProviderEnabled(String str) { System.out.println(str); } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { System.out.println(arg0+" int: " +arg1+ " Bundle " +arg2); } }; //重要函数,监听数据测试 manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, locationListener); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; } private void updateLocation(Location location) { String latLng; if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); latLng = "Latitude:" + lat + " Longitude:" + lng; } else { latLng = "Can't access your location"; } latLng = "The location has changed to :" +latLng; System.out.println("Listen-Seat " + latLng); } @Override public void onDestroy() { manager.removeUpdates(locationListener); stopSelf(); System.out.println("关闭位置监听"); } }

第二种方法是利用百度的定位接口,涉及到的权限也很多 这里是官方教程贴:http://lbsyun.baidu.com/index.php?title=android-locsdk 官方给的已经够详细了,这里就不再赘述了,主要是自己没测试=。=

转载请注明原文地址: https://www.6miu.com/read-21536.html

最新回复(0)