已启用GPS提供程序,但getLastKnownLocation(提供程序)返回null

时间:2012-07-30 13:17:29

标签: android gps provider

我正在尝试为我的应用程序使用GPS提供程序。

应用程序使用GPS位置提供程序查找设备的当前位置。

该应用程序工作得很好。但是,虽然我的GPS_Provider已启用,但geLastKnownLocation()将返回null。

MainActivity.java


public class MainActivity extends Activity {

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

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

        String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);

        Log.v("BEFORE", "Location is: " + location);
        updateWithNewLocation(location);
        Log.v("AFTER", "LOCATION FOUND");
    }

    private void updateWithNewLocation(Location location){
        String latLongString;
        TextView myLocationText;
        myLocationText = (TextView)findViewById(R.id.myLocationText);

        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        } 
        else {
            latLongString = "No location found";
        }

        myLocationText.setText("Your Current Position is:\n" + latLongString);
    }

}

的Manifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.paad.whereami"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="4"
    android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-permission
        android:name="android.permission.ACCESS_FINE_LOCATION"
    />

</manifest>

2 个答案:

答案 0 :(得分:12)

如果设备不知道最后的已知位置,则返回documentation,它返回null。可能GPS无法找到你。无论如何,大约需要一分钟。因此,在晴朗的天空下,远离高层建筑,尝试外出,等到GPS可以找到你。这可能有帮助。并且不要忘记权限。如果您尝试使用GPS_PROVIDER,则不需要访问互联网,也不需要网络状态。

编辑:

要在仿真器上运行GPS,请参阅此link

答案 1 :(得分:0)

谁还在试图理解愚蠢的功能&#34; getLastKnownLocation&#34;。

此功能仅在其他应用程序使用GPS时返回某些内容。 因此,除非您经常将GPS用于其他应用,否则它将在90%的时间内返回null。 我一直在模拟器和我自己的Android手机上测试它。我开始使用模拟位置应用程序来获得结果每5秒更改一次坐标但是一旦我停止模拟位置应用程序,我就开始得到空结果。

相关问题