如何使用Google位置服务API即使在后台也能获得位置更新?

时间:2016-09-05 09:36:29

标签: java android service geolocation

首先,这不是网站上任何其他问题的重复。我已经使用Service和Google API查看了位置更新。

我已经尝试了两种方法,但是在服务的情况下,它无效。但第一个链接的代码工作得很好,并正确地提供位置更新。但我认为当应用程序处于后台时,它无法获得更新。

我想在服务中使用该代码,即使我的应用程序处于后台,也可以不断获取位置更新。

但无法弄清楚如何合并这两个代码。如果你问的是我尝试了什么?我只是复制服务类中的常用方法。但它给了我太多错误:(

如果有替代品,请建议我。我是android的新手。

提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试:

Service.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
 import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationServices;


import java.io.IOException;
import java.io.OutputStreamWriter;

public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {



private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onCreate() {
    super.onCreate();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mGoogleApiClient.connect();

    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {


    mGoogleApiClient.disconnect();
    super.onDestroy();



}


@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000); // Update location every second

    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this,"GoogleApiClient connection has been suspend",Toast.LENGTH_LONG).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(this,"GoogleApiClient connection has failed",Toast.LENGTH_LONG).show();
}

和MainActivity.java

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent i = new Intent(this,GPSService.class);
    startService(i);


}