我有一个LocationManager,应该在单击按钮时从android设备获取gps经度和纬度。我的问题是它总是给我0.0,我无法弄清楚这是怎么回事。我在MyLocation.java和AndroidManifest.xml中为其授予了权限,我还检查了是否存在gps信号。
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" />
最佳答案
此问题与延迟的gps传感器和延迟有关。所以根据您的需要有两种解决方案
1-在onclicklistener之外启动并实例化myLocation类(例如,在oncreate中)。因此,当您单击按钮时,手机感应器会有一段时间与卫星同步。
2-在活动之前(在活动之前)并在onLocationChanged方法的myLocation中启动myLocation,将location参数发送到另一个类中的静态var(例如:sharedGps)。这样您就可以从每个活动和每个班级的sharedGps中获取位置信息