-2
我有一個活動,其中我有一個文本視圖,我想要顯示用戶的當前位置和特定地址之間的距離。我有地址的緯度和經度,但我的問題是獲取用戶的位置。我的目標是當活動創建時,我想要得到他的位置'沒有按任何按鈕。我已經嘗試了多種方式:getLastKnownLocation,onLocation已更改等,但返回的值始終爲空。如何使用GPS獲取用戶的位置
請務必注意,我正在模擬器上運行應用程序。
示例代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_list);
Bundle bundleUser = getIntent().getExtras();
final String owneruser = bundleUser.getString("username");
Bundle bundleType = getIntent().getExtras();
String type = bundleType.getString("type");
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final TextView t = (TextView) findViewById(R.id.textView2);
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
t.append("\n " + location.getLongitude() + " " + 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);
}
};
final Location userLocation = new Location("");
userLocation.setLatitude(latitude);
userLocation.setLongitude(longitude);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 10:
update();
break;
default:
break;
}
}
void update(){
// 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);
}
}
else {
locationManager.requestLocationUpdates("gps", 5000, 0, listener);
}
}
通過這個沒有按任何按鈕,任何時候,位置變化,你可以得到的位置 – Meikiem
說我必須實現抽象方法onProviderEnabled,我有 – Jokerah
也你在哪裏得到的位置在這裏?你可能會添加到你的代碼嗎? – Jokerah