2013-07-22 3 views
0

Вот сценарий, который привел к получению нулевого расположения:.Null места при попытке Google Maps демки

  1. Перейти к меню Настройки -> Расположение доступа> Выключить WiFi & mobile network location.
  2. Открыть демонстрационное приложение.
  3. Выберите MyLocationDemoActivity.
  4. Нажмите на кнопку My Location. Вы получите Location: null в тосте.

Однако, если вы включите WiFi & mobile network location, место вернется. Итак, вот некоторые вопросы:

  1. В моем приложении, я должен предположить, что WiFi & mobile network location включен по умолчанию (то же самое демо сделал)?
  2. Если нет, как определить это и показать соответствующее сообщение?
  3. И хорошо ли хранить последнее место в (например, SharedPreference) для использования, когда сетевое местоположение отключено?

Это MyLocationDemoActivity для справки:

/* 
* 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.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationClient; 
import com.google.android.gms.maps.GoogleMap; 
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 { 

    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); 
     } 
    } 
    } 

    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 
    } 
} 

ответ

1

Вот как обнаружить GPS и доступность сети для размещения

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

boolean GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
boolean NetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

Нет, не храним последнее место. Вместо этого используйте getLastKnownLocation.

+1

Я думаю, что мы должны использовать [LocationClient] (http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html) вместо [ LocationManager] (http://developer.android.com/reference/android/location/LocationManager.html) с версии 2, не так ли? – iTurki

+0

Не обязательно, кроме: 'LocationClient' полагается на' Службы Google Play ', которые могут быть недоступны на каждом устройстве. – Androiderson

+0

Я полагаюсь на это. В моем приложении используются карты Google. – iTurki

0

Недавно я столкнулся с той же проблемой. я сделал что-то вроде этого:

private boolean posChecked = false; 

//import OnMyLocationChangeListener 
//from import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener; 

@Override 
public void OnMyLocationChanged(Location location){ 

    if(!checked){ 
     //now your getMyLocation() wont be null 
    } 

} 

Вы не можете быть уверены, что вы получите непустой объект из getMyLocation() на OnCreate() потому что нагрузка Google MapFragment является асинхронным.

Надеется, что это помогает;)

Смежные вопросы