J'ai un LocationManager qui devrait me procurer la longitude et la latitude gps de l'appareil Android sur le bouton. Mon problème est que ça me donne toujours 0.0 Je ne peux pas comprendre ce qui ne va pas avec ça. Je lui ai donné les permissions dans MyLocation.java et AndroidManifest.xml J'ai aussi vérifié s'il y a un signal gps.Android LocationManager donne 0,0 pour la latitude et la longitude
MyLocation.java
public class MyLocation extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public MyLocation(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
}
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(MyLocation.this);
}
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
tablelayout.java
public class tablelayout extends Activity implements View.OnClickListener {
Button btn, btn2;
MyLocation myLocation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bundle2);
/* create button */
btn=(Button)findViewById(R.id.Button01);
btn.setOnClickListener(this);
/* delete button */
btn2=(Button)findViewById(R.id.Button02);
btn2.setOnClickListener(this);
}
public void onClick(View view){
if (view == btn) {
TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
TableRow tr = new TableRow(this);
/* get date */
SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date mydate = new Date();
String dateString = dtformat.format(mydate);
TextView dt = new TextView(this);
dt.setText(dateString);
dt.setGravity(Gravity.CENTER_HORIZONTAL);
/* get time */
SimpleDateFormat tmformat = new SimpleDateFormat("HH:mm", Locale.getDefault());
Date mytime = new Date();
String timeString = tmformat.format(mytime);
TextView tm = new TextView(this);
tm.setText(timeString);
tm.setGravity(Gravity.CENTER_HORIZONTAL);
/* drop-down list */
String[] species = getResources().getStringArray(R.array.speciesList);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,species);
AutoCompleteTextView autoComplete = new AutoCompleteTextView(this);
autoComplete.setAdapter(adapter);
autoComplete.setThreshold(1);
autoComplete.setDropDownWidth(ViewGroup.LayoutParams.MATCH_PARENT);
autoComplete.setTextSize(10);
int options = autoComplete.getImeOptions();
autoComplete.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE|EditorInfo.IME_FLAG_NO_FULLSCREEN);
/* GPS location */
TextView latitudeTv = new TextView(this);
TextView longitudeTv = new TextView(this);
// create class object
myLocation = new MyLocation(tablelayout.this);
// check if GPS enabled
if (myLocation.canGetLocation()) {
Double latitude =myLocation.getLatitude();
Double longitude =myLocation.getLongitude();
latitudeTv.setText(latitude.toString());
longitudeTv.setText(longitude.toString());
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
myLocation.showSettingsAlert();
}
/* user input */
EditText et3 = new EditText(this);
et3.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE);
et3.setInputType(InputType.TYPE_CLASS_NUMBER);
EditText et4 = new EditText(this);
et4.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE);
tr.addView(dt);
tr.addView(tm);
tr.addView(autoComplete);
tr.addView(latitudeTv);
tr.addView(longitudeTv);
tr.addView(et3);
tr.addView(et4);
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
if (view == btn2) {
TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
int rowNumber = tl.getChildCount();
tl.removeViews(rowNumber-1,1);
}
}
}
AndroidManifest.java
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Référez-vous à http://stackoverflow.com/a/23823363/6616489. Semble avoir utilisé 'location = locationManager.getLastKnownLocation (LocationManager.NETWORK_PROVIDER);' avant d'utiliser location.getLatitude()/.getLongitude(); –
'getLastKnownLocation()' retourne régulièrement 'null'. Utilisez-le avec optimisme, mais soyez prêt à prendre des mesures supplémentaires (par exemple, appelez requestLocationUpdates() ') pour obtenir des données de localisation. Ceci est couvert dans tout livre Android ou cours de formation décent qui couvre 'LocationManager'. – CommonsWare