0
我正試圖製作一個簡單的應用程序來顯示我的位置座標。當我模擬代碼(nexus 6.0,它的工作原理)。但是,當我通過usb調試(我的htc 10)使用真實設備時,按按鈕顯示我的座標時不會顯示任何內容。任何想法爲什麼?這是我的代碼:無法使用GPS獲取位置
//Location
textView = (TextView) findViewById(R.id.textView);
button2 = (Button) findViewById(R.id.button2);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
System.out.println(location.getLongitude());
System.out.println(location.getLatitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
configure_button();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case 10:
configure_button();
break;
default:
break;
}
}
void configure_button() {
// first check for permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
// this code won't execute IF permissions are not allowed, because in the line above there is return statement.
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//noinspection MissingPermission
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
});
}
我有這個加在我的清單:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
我想你必須使用融合的位置API提供的谷歌https://developer.android.com/training/location/receive-location-updates.html –