我正在使用Android Studio 3.0.1并尝试使用API 19(KitKat)获取GPS位置,它是一个扩展FragmentActivity的活动(AppCompatActivity)。
我已经启动了GPS,我正在使用真正的设备" Alcatel One Touch"我确实更新了它的服务(谷歌服务,地图等),电池100%
我有我的权限设置:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
这是我的代码:
LocationManager locationManager;
LocationListener listener;
public void start()
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
String ss = String.valueOf(location.getLatitude()) + " || " + String.valueOf(location.getLongitude() + " : " + location.getProvider());
Log.i("Location", ss);
Toast.makeText(MainActivity.this, ss, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle)
{
Toast.makeText(MainActivity.this, "changed", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String s)
{
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String s)
{
Toast.makeText(MainActivity.this, "disabled", Toast.LENGTH_SHORT).show();
}
};
if(Build.VERSION.SDK_INT < 23 )
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); // my case
}
else
{
int Check_Permission = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION);
int Permission_Granted = PackageManager.PERMISSION_GRANTED;
if (Check_Permission != Permission_Granted)
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},10);
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Toast.makeText(this, "Granted", Toast.LENGTH_SHORT).show();
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
}
永远不会调用onLocationChanged,除非我改变
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
到
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
它立即起作用,但为什么它没有使用GPS_PROVIDER?在GPS_PROVIDER上我等了30分钟以防万一GPS需要太长时间来获取位置,但它没有。