没有错误,但是当我点击测试按钮(不是每5秒)时距离不断变化,所以我不知道我的代码是否真的有效。如果您能判断是否存在某些逻辑错误,将不胜感激。 这是我的代码。 这里的逻辑是,当我点击开始按钮时,它将获得位置,然后在每5秒,它将获得一个新位置并计算距离并将其存储在一个数组中。当我按下测试按钮时,将显示总距离
public class MapsActivity extends BaseActivity /*implements LocationListener*/{
double totalDis=0;
double l;
int oxy =0;
TimeAnimator anim = new TimeAnimator();
private int isReset = 1;
private TextView textTimer;
private Button startButton;
private Button pauseButton;
private Button resetButton;
private long startTime = 0L;
private Handler myHandler = new Handler();
long timeInMillies = 0L;
long timeSwap = 0L;
long finalTime = 0L;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private GoogleMap mMap;
private Button testbtn;
double x;
double y;
double j;
double k;
float [] dis = new float[6];
TextView txt;
Location locationA;
Location locationB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
textTimer = (TextView) findViewById(R.id.textTimer);
testbtn = (Button) findViewById(R.id.testbtn);
txt = (TextView) findViewById(R.id.textTest);
testbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for(int i=0;i<dis.length;i++){
totalDis+=dis[i];
}
txt.setText("dis = "+totalDis);
}
});
startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location locationA = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
x = locationA.getLatitude();
y = locationA.getLongitude();
anim.start();
anim.setTimeListener(new TimeAnimator.TimeListener() {
long time = 0;
@Override
public void onTimeUpdate(TimeAnimator timeAnimator, long t, long dt) {
time += dt;
if (time >= 5000) { // >= needed because this also might be not totally accurate...
time -= 5000; // keep the remainder (if there is) to correct the accuracy of next loop
// do stuff here (in every 5 seconds)
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location locationB = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
j = locationB.getLatitude();
k = locationB.getLongitude();
Location.distanceBetween(x,y,j,k,dis);
x=j;
y=k;
}
}
});
}
});
pauseButton = (Button) findViewById(R.id.btnPause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);
}
});
resetButton = (Button) findViewById(R.id.btnReset);
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
textTimer.setText("0:00:00");
timeSwap=0;
}
});
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
}
private Runnable updateTimerMethod = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliseconds));
myHandler.postDelayed(this, 0);
}
};
}
答案 0 :(得分:0)
你的代码非常错误。
请参阅Receiving Location updates页面。那个页面留下了一些东西供你实现,所以我会给你一些工作实例。您需要自己根据自己的需要进行调整。
@Override
public void onConnected(@Nullable final Bundle bundle) {
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(final int i) {
}
@Override
public void onLocationChanged(final Location location) {
EventBus.getDefault().post(new LocationChangedEvent(location));
}
@Override
public void onConnectionFailed(@NonNull final ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
Logger.e(this, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Utils.showPermissionRationaleDialog(MainActivity.this, R.string.permission_rationale_location,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
"request_location_updates");
}
buildGoogleApiClient();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
@Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
答案 1 :(得分:0)
按照指示将这些代码放入您的代码中。
声明这些变量
LocationManager manager;
Button start_calculating, show;
boolean startcount_now = false;
double total_dist = 0;
Location last_loc = null;
进口
import android.location.LocationListener;
并实施
LocationListener
然后实现这些方法
@Override
public void onLocationChanged(Location location) {
if (startcount_now == true) {
if (last_loc == null) {
last_loc = location;
} else {
total_dist += location.distanceTo(last_loc);
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
protected void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
if (manager != null) {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
}
}
@Override
protected void onPause() {
super.onPause();
super.onResume();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}
if (manager != null) {
manager.removeUpdates(MainActivity.this);
}
}
在oncreate()
中manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
按钮的监听器(将它们添加到用于此目的的按钮中)
start_calculating.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startcount_now = true;
}
});
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "total distancetravelled is " + total_dist, Toast.LENGTH_LONG).show();
}
});
在清单中添加权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
show按钮会显示吐司的总距离。你可以随心所欲地使用它。当您的应用处于后台时,将停止提取位置。有关位置获取机制,请阅读this。
如果这是你想要的,请告诉我。