我以前有
AlarmManager+WakefulBroadcastReceiver+服务
执行一些背景代码并获取位置更新。
因为奥利奥,这是不推荐的,所以现在我使用
AlarmManager+BroadcastReceiver+JobIntentService
。
这是清单中JobIntentService的代码:
<service android:name="MyJobIntentService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
以及MyJobIntentService类,我需要在其中更新位置:
public class MyJobIntentService extends JobIntentService implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
public void onCreate() {
super.onCreate();
}
//Convenience method for enqueuing work in to this service.
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, clsJobIntentServiceDePosicionamientoPlayServices.class, 123456, work);
}
@Override
protected void onHandleWork(Intent intent) {
// We have received work to do. The system or framework is already holding a wake lock for us at this point, so we can just go.
StartLocating();
}
@Override
public void onDestroy() {
super.onDestroy();
}
void StartLocating(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
And the rest of the location functions like onLocationChanged...
这个应用程序可以运行(至少在模拟器上是这样),但恐怕我做错了什么,因为在onCreate()之后,它就被称为onHandleWork(),之后就是onHandleWork()
onDestroy()
。
几秒钟后,我开始在中获取位置更新
onLocationChanged(位置已更改)
但我担心出了问题,因为以前调用过onDestroy()。这样做对吗?
这是我从BroadcastReceiver创建JobIntentService的方法:
Intent i = new Intent(contexto, MyJobIntentService.class);
MyJobIntentService.enqueueWork(MyContext, i);