【发布时间】:2020-03-24 21:15:21
【问题描述】:
我试图在我的活动中访问gps 位置,但在调用getLastKnownLocation 的LocationManager 类时总是得到null。我还添加了以下权限。我的 GPS 已启用,但设备上没有互联网。请指导我做错了什么
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
并且还签入代码。下面是我的代码。
public class MainActivity extends AppCompatActivity 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);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
} catch (Exception e) {
e.printStackTrace();
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latituteField.setText(location.getLatitude()+"");
longitudeField.setText(location.getLongitude()+"");
}else{
latituteField.setText("not found");
longitudeField.setText("not found");
}
}
@Override
public void onLocationChanged(Location location) {
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();
}
}
【问题讨论】:
-
快速检查方法是在同一部手机中打开谷歌地图并检查它是否显示当前位置
-
地图给了我正确的位置
-
行前" locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); " 。您需要检查您的设备上是否有gps/位置设置。如果没有打开意味着您需要将其设为开启。如果位置设置为关闭,则位置值可能为空。
-
位置设置已开启,我可以在我的活动开启时看到位置图标。
-
Map is giving me my correct location通过使用 wifi。如果 gps 没有打开,它也会。
标签: android geolocation android-location