获取位置在广播接收机与谷歌播放服务



我想在启用GPS时在谷歌地图上设置标记。

我创建了一个广播接收器来检查GPS是否启用或禁用。它的工作原理。但是,我不知道如何使用Google Play服务获取位置并在地图上设置标记。

LocationClient上的connect()方法在onStart()方法上启动,startuupdates()方法在onResume()方法上启动。

如何在广播接收器上设置地图?

如果我使用getLocation()(见下文),它返回null,因为我没有连接到GooglePlay服务。

如果我使用LocationClient.connect(),我必须等待客户端连接到获取位置。

我该怎么做呢?

PS:我使用这个示例代码连接到Google play服务:http://developer.android.com/training/location/receive-location-updates.html

我的内部类GpsLocationReceiver:

public class GpsLocationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
            boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            onGpsStatusChanged(isEnabled);
        }
    }
    private void onGpsStatusChanged(boolean b) {
        if (!servicesConnected() && b) {
            mLocationClient.connect();
        }
        /*currentLocation = getLocation();
        //setUpMapIfNeeded();
        if (currentLocation == null) {
            Toast.makeText(this, "GPS enabled - " + b + " Loc : null", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "GPS enabled - " + b + " Loc : " + currentLocation.toString(), Toast.LENGTH_LONG).show();
        }*/
    }

方法getLocation

public Location getLocation() {
        // If Google Play Services is available
        if (servicesConnected()) {
            // Get the current location
            return mLocationClient.getLastLocation();
        }
        return null;
    }

my method onConnected():

 @Override
    public void onConnected(Bundle bundle) {
        //Set currentLocation
        currentLocation = getLocation();
        if (currentLocation == null) {
            Toast.makeText(HomeActivity.this, "location null", Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(HomeActivity.this, "Lat : "+ currentLocation.getLatitude() + " Long : "+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
            //Get map if needed
            setUpMapIfNeeded();
        }

        if (mUpdatesRequested) {
            startPeriodicUpdates();
        }
    }

Thx

编辑:

我修改了我的代码。对我来说似乎更清楚了。现在,我的函数getLocation()在连接成功完成后调用,返回null。这意味着google play服务不可用。

如果我理解得很好,问题是即使GPS启用了,你也必须等到GPS获得至少它的第一个修复才能获得用户的位置。我不明白为什么你要检查BroadcastReceiver中的GPS状态,但我认为如果你在连接LocationClient之前检查GPS是否启用(也许你可以在启动Actviity之前检查它,如果你的要求允许的话),然后你可以请求位置。

现在,还有另一个问题:如果您调用mLocationClient.getLastLocation(),则有可能检索缓存位置(称为系统注册的"最后一个位置"),或者如果系统没有缓存位置,则可以获得null位置,因此您的标记显然是不准确的。我通常做,检查后如果你可以启用GPS LocationRequest PRIORITY_HIGH_ACCURACY和实现LocationListener安卓培训,之后第一个收到locationChange可以removeLocationUpdates如果你只想要一个标记现在可以肯定的是,位置是用户的当前位置,但你必须不可避免地等待GPS连接,可能是几分钟或者它可能永远不会发生,这取决于天气和一些你无法控制的随机变量。

编辑:这是一个来自Google Play Services SDK样本的例子(SDK/extras/Google/google_play_services/samples/maps)::

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.mapdemo;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
 * This demo shows how GMS Location can be used to check for changes to the users location.  The
 * "My Location" button uses GMS Location to set the blue dot representing the users location. To
 * track changes to the users location on the map, we request updates from the
 * {@link LocationClient}.
 */
public class MyLocationDemoActivity extends FragmentActivity
        implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener,
        OnMyLocationButtonClickListener {
    private GoogleMap mMap;
    private LocationClient mLocationClient;
    private TextView mMessageView;
    // These settings are the same as the settings for the map. They will in fact give you updates
    // at the maximal rates currently possible.
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000)         // 5 seconds
            .setFastestInterval(16)    // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_demo);
        mMessageView = (TextView) findViewById(R.id.message_text);
    }
    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        setUpLocationClientIfNeeded();
        mLocationClient.connect();
    }
    @Override
    public void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                mMap.setMyLocationEnabled(true);
                mMap.setOnMyLocationButtonClickListener(this);
            }
        }
    }
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(
                    getApplicationContext(),
                    this,  // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }
    /**
     * Button to get current Location. This demonstrates how to get the current Location as required
     * without needing to register a LocationListener.
     */
    public void showMyLocation(View view) {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            String msg = "Location = " + mLocationClient.getLastLocation();
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * Implementation of {@link LocationListener}.
     */
    @Override
    public void onLocationChanged(Location location) {
        mMessageView.setText("Location = " + location);
    }
    /**
     * Callback called when connected to GCore. Implementation of {@link ConnectionCallbacks}.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        mLocationClient.requestLocationUpdates(
                REQUEST,
                this);  // LocationListener
    }
    /**
     * Callback called when disconnected from GCore. Implementation of {@link ConnectionCallbacks}.
     */
    @Override
    public void onDisconnected() {
        // Do nothing
    }
    /**
     * Implementation of {@link OnConnectionFailedListener}.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Do nothing
    }
    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }
}

这个答案怎么样?使用地理定位,并为清单提供精细位置访问

https://stackoverflow.com/a/8543819/2931489

Voggela教程http://www.vogella.com/tutorials/AndroidLocationAPI/article.html

相关内容

最新更新