我曾经使用AlarmManager + WakefulBroadcastReceiver + Service来做一些背景代码并获取位置更新。

自奥利奥(Oreo)以来,此方法已被弃用,因此现在我使用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(),然后在onDestroy()之后。

几秒钟后,我开始在onLocationChanged中获取位置更新,但由于出事onDestroy(),我担心出现了问题。这是正确的方法吗?

这是我从BroadcastReceiver创建JobIntentService的方式:

Intent i = new Intent(contexto, MyJobIntentService.class);
MyJobIntentService.enqueueWork(MyContext, i);

最佳答案

JobIntentService不是您想要的,它代替了IntentService。这意味着,当onHandleIntent方法结束时,该服务将被终止。在您的情况下,您需要使用前台服务或使用其他服务。

关于android - 使用JobIntentService在后台更新Android Oreo位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49496030/

10-11 22:27