Android Location API不会在LocationChanged上显示模拟位置

时间:2014-06-17 19:08:21

标签: java android google-maps

我正在努力使用android location api来不断更新我设备的当前位置。我在这里做错了什么?

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class ViewMapActivity extends FragmentActivity implements LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {

    public static final Long LOCATION_MIN_TIME = 1000L;
    public static final float LOCATION_MIN_DISTANCE = 10f;

    private static GoogleMap googleMap;
    private LocationManager locationManager;
    private  Criteria criteria;
    private String provider;


    public ViewMapActivity() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("ViewMap"," Map created");
        setContentView(R.layout.map);
        GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
        GoogleMapOptions mapOptions = new GoogleMapOptions();
        mapOptions.mapType(GoogleMap.MAP_TYPE_NORMAL);
        mapOptions.zoomGesturesEnabled(true);
        mapOptions.zoomControlsEnabled(true);
        googleMap = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.mapfragment))
                .getMap();
        googleMap.setMyLocationEnabled(true);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria,  false);
        //Log.d("ViewMap", provider.toString());

        Location location = locationManager.getLastKnownLocation(provider);

        if(location != null) {
            onLocationChanged(location);
        } else {
            Log.d("ViewMap", "Location found onCreate."+location.toString());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("ViewMap", "Paused");
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("ViewMap", "Resume");
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i("ViewMap", "location changed");
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        //googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        //googleMap.animateCamera(CameraUpdateFactory.zoomBy(15)); //TODO: move this to static config
        String loc = "Lat:"+latLng.latitude+" long:"+latLng.longitude;
        Toast.makeText(getBaseContext(), loc, Toast.LENGTH_SHORT).show();
        Log.d("ViewMap", latLng.toString());
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        Log.d("ViewMap", "Status Changed: "+s);
    }

    @Override
    public void onProviderEnabled(String s) {
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Log.d("ViewMap", "GPS Provider");
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
        } else {
            Log.d("ViewMap", "Network Provider");
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
    }

    @Override
    public void onProviderDisabled(String s) {
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        } else {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        // TODO may be add some logs
        Log.i("ViewMap", "GPS can work now");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onDisconnected() {
        // TODO may be add some logs
        Log.i("ViewMap", "GPS is disconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
       // TODO may be add some logs
        Log.e("ViewMap", "Google play connection failed. GPS might not work");
    }
}

这是AndroidManifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.sample.activity"
           android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="18"/>

    <permission
            android:name="com.sample.activity.permissions.MAP_RECEIVE"
            android:protectionLevel="signature" />

    <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />

    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission 
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />


    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="SplashScreenStartActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity android:name=".ViewMapActivity"/>



        <meta-data android:name="com.google.android.maps.v2.API_KEY" 
android:value="@string/google_map_api_key" />
         <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
     </application> </manifest>

作为后续问题,如何通过传递模拟位置来测试此活动。我正在使用来自http://developer.android.com/training/location/location-testing.html的模拟位置示例。标记确实显示模拟位置,但onLocation始终显示当前位置

2 个答案:

答案 0 :(得分:3)

模拟位置仅适用于GPS,它不会伪造任何其他提供商。具体来说,它不会伪造NETWORK位置提供者。不要使用标准来选择最佳提供商,指定GPS提供商。

一般来说,我不认为Criteria是有用的。你写了你的应用程序,你知道你是否需要GPS的准确性或想要通过网络节省电池。指定您想要的内容,而不是让操作系统为您选择一个。

答案 1 :(得分:0)

您是否可以使用您的活动的导入集更新问题,如果不正确则会编辑/删除我的答案 为什么您总是看到当前位置可能是因为onCreate()

中的googleMap.setMyLocationEnabled(true);

坦率地说,有问题的代码似乎是来自多个来源的复制粘贴,但没有太多了解或细节被忽略,而不是那么温和。

代码包含两种获取用户位置的方法 1。 使用LocationClientRetrieving the Current Location
这实现了GooglePlayServicesClient的接口 该套餐为com.google.android.gms.location.LocationClient,因此LocationListener.Testing Using Mock Locations的链接上,已使用此链接。

2。 使用LocationManager
使用方法requestLocationUpdates()。这个包是android.location所以它的LocationListener.

这对您的代码意味着什么:
1.1 您已为第一种方法实现了侦听器,但您从未设置,调用或使用locationClient.connect(),因此永远不会调用以下部分代码。

@Override
    public void onConnected(Bundle bundle) {
        // TODO may be add some logs
        Log.i("ViewMap", "GPS can work now");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onDisconnected() {
        // TODO may be add some logs
        Log.i("ViewMap", "GPS is disconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
       // TODO may be add some logs
        Log.e("ViewMap", "Google play connection failed. GPS might not work");
    }  

您应该使用此方法,因为您仍在使用Google Play服务。

2.1 locationManager.requestLocationUpdates(provider, 400, 1, this);
如果您导入了正确的LocationListener,这就是获取位置的原因。您可以签入导入,如果它不是android.location包,我不认为代码到达那里。