locationManager.getLastKnownLocation() 返回 null
Posted
技术标签:
【中文标题】locationManager.getLastKnownLocation() 返回 null【英文标题】:locationManager.getLastKnownLocation() returns null 【发布时间】:2017-07-31 18:59:45 【问题描述】:我正在制作一个程序,我想获取我设备的 gps 坐标。问题是当 locationManager.getLastKnownLocation() 被调用时它返回 null。我的设备运行 android 4.4 API 19。
这是我的代码:
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = LocationManager.GPS_PROVIDER;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
else
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
/* Request updates at startup */
@Override
protected void onResume()
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
locationManager.requestLocationUpdates(provider, 400, 0, this);
/* Remove the locationlistener updates when Activity is paused */
@Override
protected void onPause()
super.onPause();
locationManager.removeUpdates(this);
@Override
public void onLocationChanged(Location location)
Log.d("location change:", " change1 " );
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
// TODO Auto-generated method stub
@Override
public void onProviderEnabled(String provider)
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
@Override
public void onProviderDisabled(String provider)
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
这是我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vaggelis.location">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
我做错了什么?
【问题讨论】:
也许它只是在你请求它的那一刻不知道你的位置? 这是我的代码..如果我要它,你是什么意思? 好的,您只使用 GSP 提供商。您确定 GPS 已开启? 是的。除了 GPS 之外,我必须打开其他设备吗? 【参考方案1】:按照下面的链接并使用代码,它正在工作并经过测试。
https://medium.com/@ssaurel/getting-gps-location-on-android-with-fused-location-provider-api-1001eb549089
【讨论】:
【参考方案2】:locationManager.getLastKnownLocation() 返回 null。
因为每次从手机获取最后一个位置都需要时间。它非常陈旧而且不是好方法。
Google 为 Android 推出 fused api。它总是返回正确的值。
我已经回答了相同的question here。看看这个。如果你有任何问题,请告诉我。
谢谢
【讨论】:
它说 GoogleApiClient 和 LocationRequest 无法解析符号。你知道这是为什么吗?(我的设备运行的是 android 4.4 API 19) 您是否在 gradle 中添加了 com.google.android.gms:play-services-location ? 现在可以了,谢谢。我有两个问题:1)在我的清单文件“.service.location.LocationService”中说:未解决的 calss 'Locatioservice ,验证 Android XML 文件中的资源引用 2)在 onCreate 方法的主要活动中,我调用 startService(new Intent(context, LocationService.class));就像你说的那样。但是上下文需要初始化什么?抱歉给您添麻烦 我使用了 LocationService 类,因为我也需要在后台定位。您也可以使用 GoogleLocationService 方法来做到这一点。请阅读我的其他答案,我已经提到了所有内容。以上是关于locationManager.getLastKnownLocation() 返回 null的主要内容,如果未能解决你的问题,请参考以下文章