我有这个代码(主要来自教程)以十进制形式显示GPS坐标。我想使用按钮来保存当前位置int某些数据结构或什么不....那部分不是问题。我想知道如何最好地从大量更新中捕获GPS数据。
我想捕获onClickListener中的坐标。
我应该使用getLasKnown()吗?
package com.example.geolocation;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
TextView textLat, textLong;
Button locateBTN;
double mLat, mLong;
ArrayList<Double> mLats = new ArrayList<Double>();
ArrayList<Double> mLongs = new ArrayList<Double>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView) findViewById(R.id.lat_output);
textLong = (TextView) findViewById(R.id.long_output);
locateBTN = (Button) findViewById(R.id.locate_button);
LocationManager locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener =
new myLocationlistener();
locationManager
.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locationListener);
locateBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//STUB
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class myLocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if ( location != null ){
double pLong = location.getLongitude();
double pLat = location.getLatitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
}
答案 0 :(得分:1)
单击按钮,可以使用LocationManager对象getLastKnownLocation方法 - http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
答案 1 :(得分:1)
获取GPS坐标的最佳方法是使用Fused Location API
Google
否则你必须投入大量代码才能获得正确的坐标。与仅使用GPS坐标相比,这种Api消耗的电池要少得多。