我正在創建一個使用設備當前位置的Android應用程序。爲了做到這一點,我使用以下代碼開發了一個應用程序,每5秒獲取一次當前位置。Android位置應用程序
import android.*;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CurrentLocation extends AppCompatActivity {
private Button button;
private TextView textView;
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_location);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
textView.append("\n " + location.getLongitude() + " " + location.getLatitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
return;
}
}
else{
configureButton();
}
;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 10:
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
configureButton();
}
}
private void configureButton() {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});
}
}
第一次在我的設備中安裝此應用程序時,它工作得非常好。但之後它根本不工作。它甚至不要求打開位置服務。 有人可以幫助我這個。謝謝。
點擊按鈕後,檢查您的logcat和發佈的結果。你有什麼錯誤嗎?你有沒有啓用你的GPS? – AndroidRuntimeException