2

我曾经有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);
4

1 回答 1

1

JobIntentService 不是您想要的,它取代了 IntentService。这意味着当 onHandleIntent 方法结束时,服务被杀死。在您的情况下,您需要使用前台服务或使用不同的东西。

于 2018-03-26T17:13:42.573 回答