【问题标题】:Making a Service out of Basic Location Sample code使用基本位置示例代码制作服务
【发布时间】:2015-12-20 12:42:20
【问题描述】:

我想在 Android 中创建一项服务(后台操作)以不时跟踪设备的位置,并将其存储在 SharedPreference 上或在位置更改时将其发送到我的服务器。我是从Get current location name of user without using gps or internet but by using Network_Provider in androidAndroid Developers - Getting the Last Known Location 看到这段代码的。

这是代码:

public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {

    protected static final String TAG = "MainActivity";

    /**
    * Provides the entry point to Google Play services.
    */
    protected GoogleApiClient mGoogleApiClient;

    /**
    * Represents a geographical location.
    */
    protected Location mLastLocation;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mLatitudeLabel = getResources().getString(R.string.latitude_label);
        mLongitudeLabel = getResources().getString(R.string.longitude_label);
        mLatitudeText = (TextView) findViewById((R.id.latitude_text));
        mLongitudeText = (TextView) findViewById((R.id.longitude_text));

        buildGoogleApiClient();
    }

    /**
    * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
    */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
    * Runs when a GoogleApiClient object successfully connects.
    */
    @Override
    public void onConnected(Bundle connectionHint) {
        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            Log.e("Location", "not null");
            makeUseOfNewLocation(mLastLocation);
            } else {
            Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
            // should request new one
            // location should be enabled
            Log.i(TAG,
            "No location data previously acquired.. should request!");

            Toast.makeText(this,
            "Requesting location data ..",
            Toast.LENGTH_SHORT).show();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(5000);

            PendingResult<Status> result = LocationServices.FusedLocationApi
            .requestLocationUpdates(mGoogleApiClient,
            locationRequest,
            new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    Log.e("Location", "not null");
                    makeUseOfNewLocation(location);
                }
            });
            // TODO: use result to retrieve more info
            Toast.makeText(this, result.toString(),Toast.LENGTH_LONG);
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    private void makeUseOfNewLocation(Location location) {
        // do your stuff here
        mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
        location.getLatitude()));
        mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
        location.getLongitude()));
    }
}

我的问题是,仅通过在此类上扩展服务,此代码是否可以成为服务。这是否可行并且能够不时地在后台跟踪设备的位置

【问题讨论】:

    标签: android service gps location


    【解决方案1】:

    根据 Google 的文档,您将需要在 onConnected 中使用 PendingIntent 以确保即使在应用关闭时也有后台服务在运行。

    https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

    public abstract PendingResult requestLocationUpdates(GoogleApiClient 客户端,LocationRequest 请求,PendingIntent callbackIntent)

    在指定的 PendingIntent 上使用回调请求位置更新。

    此方法适用于后台用例,尤其适用于接收位置更新,即使应用已被系统终止。为此,请将 PendingIntent 用于已启动的服务。对于前台用例,建议使用 LocationListener 版本的方法,参见 requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener)。

    我之前的方法是创建一个包含在您的 pendingIntent 中的 Intent,然后在 Intent 中指明从您当前的活动传递给一个 Handler 类。在扩展 IntentService 的处理程序类中,您将能够在 onHandle 方法中获取任何位置信息。

    您可以查看我之前的一个问题以供参考: FusedLocationProvider using intentservice for background location update: location update does not work when pendingintent has a bundle added

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多