【发布时间】:2020-02-13 11:10:40
【问题描述】:
我正在尝试获取用户的位置,但似乎从未触发过 onLocationUpdate,我尝试在多个设备上运行此应用,结果相同。
我在此处发布之前尝试了 Google,但找不到任何解决方案。并且,在 manifest 文件中添加了 Android Internet、GPS COARSE 和 GPS FINE 权限。
这是我的整个活动代码
public class AnotherActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Checking if we got permission
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_restaurants);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Toast.makeText(NearbyRestaurants.this, location.getLatitude()+String.valueOf(location.getLongitude()), Toast.LENGTH_SHORT).show();
Log.i("Location Update!", location.toString())
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION},1);
}else{
Log.i("Checking Location","Checking Location Wait");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
【问题讨论】:
标签: java android android-studio android-gps