2016-04-28 127 views
2

我正在做一個應用程序發送經緯度的座標,所以我擴展了一個服務並實現了LocationManager。 這是我的代碼部分:Android:實現LocationManager的最佳實踐

public class LocationServiceTracking extends Service implements LocationListener{ 
 
.... 
 
@Override 
 
    public void onCreate() { 
 
     super.onCreate(); 
 
     mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
 

 
      if (isGPSEnabled && provider.equals(LocationManager.GPS_PROVIDER)) { 
 
       try { 
 
        mLocationManager.requestLocationUpdates(3000, 0, criteria, this, null); 
 
        Log.d("GPS Enabled", "GPS Enabled"); 
 
       } catch (SecurityException se) { 
 
        se.printStackTrace(); 
 
        Crashlytics.logException(se); 
 
       } 
 
      } 
 
    } 
 

 

 
    @Override 
 
    public int onStartCommand(Intent intent, int flags, int startId) { 
 
     return START_STICKY; 
 
    } 
 

 
}

我的問題是¿會是什麼,如果你這樣做是爲了做到這一點在onCreate()象現在或將其更改爲onStartCommand()最好的做法是什麼?

回答

1

爲了簡潔使用熔融位置API。

關於你的問題 - 這是更好地做到這一點在onCreate()因爲當你觸發啓動服務,只有當實際創建的服務的onCreate onStartCommand()將被調用多次。

Calling start service

Service lifecycle

0

應該在onStartCommand()

原因:每當業務創建 但onStartCommand()將被調用時手動啓動onCreate()將被調用 服務致電obj.startService()

因此,如果您將該代碼放入onCreate(),您將在開始服務之前開始接收更新,這不是一種好的做法。在Service中編寫的代碼只有在啓動時才應啓用限制

例如,

MyService serviceObj = new MyService(); // this will call onCreate(). 

serviceObj.startService(); // this will call `onStartCommand()`. 

serviceObj.bindService(); // this will call onBind(). (Not your case). 

希望這會有所幫助。

0

在您的課程中創建一個名爲mGoogleApiClient的字段。

然後在onCreate做到這一點:

// Create an instance of GoogleAPIClient. 
if (mGoogleApiClient == null) { 
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

當類加載和停止,處理這個領域的生命週期:

public void onStart() { 
    mGoogleApiClient.connect(); 
    super.onStart(); 
} 

public void onStop() { 
    mGoogleApiClient.disconnect(); 
    super.onStop(); 
} 

現在實行folliwing接口:

GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener 

並添加其方法:

@Override 
public void onConnected(Bundle connectionHint) { 
    Log.d(TAG, "Google Maps API::onConnected"); 
    //For Marshmallow 6.0, make sure to check Permissions 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Log.d(TAG, "Google Maps API::onConnectionSuspended"); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
    Log.d(TAG, "Google Maps API::onConnectionFailed"); 
}