
1 从Service继承一个类。
2 创建startService()方法。
3 创建endService()方法 重载onCreate方法和onDestroy方法,并在这两个方法里面来调用startService以及endService。
4 在startService中,通过getSystemService方法获取ContextLOCATION_SERVICE。
5 基于LocationListener实现一个新类。默认将重载四个方法onLocationChanged、onProviderDisabled、onProviderEnabled、onStatusChanged。对于onLocationChanged方法是我们更新最新的GPS数据的方法。一般我们的 *** 作都只需要在这里进行处理。
6 调用LocationManager的requestLocationUpdates方法,来定期触发获取GPS数据即可。在onLocationChanged函数里面可以实现我们对得到的经纬度的最终 *** 作。
7 最后在我们的Activity里面通过按钮来启动Service,停止Service。
示意代码如下:
package comoffbyegpsservice;
import androidappService;
import androidcontentContext;
import androidcontentIntent;
import androidlocationLocationListener;
import androidlocationLocationManager;
import androidosBinder;
import androidosIBinder;
import androidutilLog;
public class GPSService extends Service {
// 2000ms
private static final long minTime = 2000;
// 最小变更距离10m
private static final float minDistance = 10;
String tag = thistoString();
private LocationManager locationManager;
private LocationListener locationListener;
private final IBinder mBinder = new GPSServiceBinder();
public void startService() {
locationManager = (LocationManager) getSystemService(ContextLOCATION_SERVICE);
locationListener = new GPSServiceListener();
locationManagerrequestLocationUpdates(LocationManagerGPS_PROVIDER, minTime, minDistance,
locationListener);
}
public void endService() {
if (locationManager != null && locationListener != null) {
locationManagerremoveUpdates(locationListener);
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
1第一种方法
private void toggleGPS() {
Intent gpsIntent = new Intent();
gpsIntentsetClassName("comandroidsettings", "comandroidsettingswidgetSettingsAppWidgetProvider");
gpsIntentaddCategory("androidintentcategoryALTERNATIVE");
gpsIntentsetData(Uriparse("custom:3"));
try {
PendingIntentgetBroadcast(StartActivitythis, 0, gpsIntent, 0)send();
} catch (CanceledException e) {
eprintStackTrace();
}
}
2第二种方法
private void openGPSSettings() {
//获取GPS现在的状态(打开或是关闭状态)
boolean gpsEnabled = SettingsSecureisLocationProviderEnabled( getContentResolver(), LocationManagerGPS_PROVIDER );
if(gpsEnabled)
{
//关闭GPS
SettingsSecuresetLocationProviderEnabled( getContentResolver(), LocationManagerGPS_PROVIDER, false );
}
else
{
//打开GPS >
以上就是关于mqtt 怎么实现android以后台service的方式获取gps数据,并定时发送到服务器全部的内容,包括:mqtt 怎么实现android以后台service的方式获取gps数据,并定时发送到服务器、android怎样自动打开gps、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)