2016-04-28 130 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"); 
}