包含在清单中:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
活动代码:
public class ActivityLogin extends AppCompatActivity {
public static LocationManager mLocationManager;
public static MyLocationListener locationListener = new MyLocationListener();
//...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
ActivityCompat.requestPermissions(ActivityLogin.this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
2);
// ...
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 2:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 0, locationListener);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, 0, locationListener);
mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 10 * 1000, 0, locationListener);
}
return;
}
}
}
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
MapsActivity.Mylocation = new LatLng(
location.getLatitude(), location.getLongitude());
}
public void onProviderDisabled(String provider) {
// ...
}
public void onProviderEnabled(String provider) {
// ...
Location location = ActivityLogin.mLocationManager
.getLastKnownLocation(provider);
if (location != null) {
MapsActivity.Mylocation = new LatLng(
location.getLatitude(), location.getLongitude());
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// ...
}
}
因此,事件onLocationChanged
不会发生。如果我关闭wifi然后再打开,则会发生onProviderEnabled
事件,ActivityLogin.mLocationManager.getLastKnownLocation(provider)
会返回null
。
最后,我无法得到我的坐标。
答案 0 :(得分:0)
我过去遇到过locationListener有问题,而我唯一能让它工作的方法是在mainActivity中实现LocationListener,本地或静默的locationlistener将无效。
例如
public class ActivityLogin extends AppCompatActivity implements LocationListener
也就是说,google正在弃用locationListener并将其替换为Google位置API。这使用fusionLocationAPI和GoogleApiClient。
在你的onCreate中你应该有类似
的东西GoogleApiClient api_client;
api_client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
在你的onConnected方法中你应该有类似
的东西location = LocationServices.FusedLocationApi.getLastLocation(api_client);
我不认为这是一个改进,但谷歌强迫我们这样做。