當前位置:編程學習大全網 - 腳本源碼 - 如何通過在調用Service服務在後臺啟動GPS定

如何通過在調用Service服務在後臺啟動GPS定

1 從Service繼承壹個類。

2 創建startService()方法。

3 創建endService()方法 重載onCreate方法和onDestroy方法,並在這兩個方法裏面來調用startService以及endService。

4 在startService中,通過getSystemService方法獲取Context.LOCATION_SERVICE。

5 基於LocationListener實現壹個新類。默認將重載四個方法onLocationChanged、onProviderDisabled、onProviderEnabled、onStatusChanged。對於onLocationChanged方法是我們更新最新的GPS數據的方法。壹般我們的操作都只需要在這裏進行處理。

6 調用LocationManager的requestLocationUpdates方法,來定期觸發獲取GPS數據即可。在onLocationChanged函數裏面可以實現我們對得到的經緯度的最終操作。

7 最後在我們的Activity裏面通過按鈕來啟動Service,停止Service。

示意代碼如下:

package com.offbye.gpsservice;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.location.LocationListener;

import android.location.LocationManager;

import android.os.Binder;

import android.os.IBinder;

import android.util.Log;

public class GPSService extends Service {

// 2000ms

private static final long minTime = 2000;

// 最小變更距離10m

private static final float minDistance = 10;

String tag = this.toString();

private LocationManager locationManager;

private LocationListener locationListener;

private final IBinder mBinder = new GPSServiceBinder();

public void startService() {

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

locationListener = new GPSServiceListener();

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,

locationListener);

}

public void endService() {

if (locationManager != null && locationListener != null) {

locationManager.removeUpdates(locationListener);

}

}

@Override

public IBinder onBind(Intent arg0) {

// TODO Auto-generated method stub

return mBinder;

}

  • 上一篇:刀塔傳奇王座之塔玩法及規則介紹
  • 下一篇:孝警阿特是什麽警種?
  • copyright 2024編程學習大全網