测试我的gps位置并计算我在android中行驶的总距离时强制关闭
最近,我正在学习如何使用gps和标记来确定我当前的位置。现在我尝试修改代码,以便代码能够跟踪我的当前位置,并在位置更新时计算我的总行驶距离。一开始,它是有效的。但2-3分钟后,我的应用程序开始挂起并提示我强制关闭,因为我的应用程序没有响应 下面是我的代码:测试我的gps位置并计算我在android中行驶的总距离时强制关闭,android,gps,locationmanager,locationlistener,Android,Gps,Locationmanager,Locationlistener,最近,我正在学习如何使用gps和标记来确定我当前的位置。现在我尝试修改代码,以便代码能够跟踪我的当前位置,并在位置更新时计算我的总行驶距离。一开始,它是有效的。但2-3分钟后,我的应用程序开始挂起并提示我强制关闭,因为我的应用程序没有响应 下面是我的代码: public class WhereAmINowActivity extends Activity { //declaration of variables public void getPrevActivityValue(){ I
public class WhereAmINowActivity extends Activity {
//declaration of variables
public void getPrevActivityValue(){
Intent intent = getIntent();
// get the value from prev activity
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_distance);
getPrevActivityValue();
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
distance = (TextView)findViewById(R.id.distance);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, TWO_MIN, HUNDRED_METERS ,locationListener);
addListenerOnBtnStart();
addListenerOnBtnStop();
}
public void addListenerOnBtnStart(){
btnStart.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView){
if(!startPressed){
// Initialize the variables of current and old location coordinates
}
catch (Exception e){
e.printStackTrace();
}
}
else{
// Do nothing
}
}
});
}
public void addListenerOnBtnStop(){
btnStop.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView){
try{
if(connected to internet is true)
// Do something here
}
else{
// prompt message to notify user connectivity is not available
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
// Update the current location, old coordinates and get the address
}
}
某些值是通过使用getIntent()从上一个活动传递的
有人能帮我找出哪一部分我做错了吗
补充:
我移除了覆盖层,仅在位置侦听器上进行了测试。
我发现当它运行大约2-3分钟时,我的应用程序界面不会对我按下的按钮做出响应(因为我声明有两个按钮-启动和停止)。当我按下停止按钮时,没有发生任何事情,然后一条强制关闭消息会提示我。这是我做错的部分吗?当我使用GPS行走时,我应该如何纠正它,使其能够像正常距离计算一样工作?我已经在我的开源GPS跟踪器中解决了这个确切的问题。完整的android项目如下: 下面是进行跟踪的类。您想看看名为totalDistanceInMeters的变量
package com.websmithing.gpstracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class LocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "LocationService";
// use the websmithing defaultUploadWebsite for testing and then check your
// location with your browser here: https://www.websmithing.com/gpstracker/displaymap.php
private String defaultUploadWebsite;
private boolean currentlyProcessingLocation = false;
private LocationRequest locationRequest;
private LocationClient locationClient;
@Override
public void onCreate() {
super.onCreate();
defaultUploadWebsite = getString(R.string.default_upload_website);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// if we are currently trying to get a location and the alarm manager has called this again,
// no need to start processing a new location.
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_NOT_STICKY;
}
private void startTracking() {
Log.d(TAG, "startTracking");
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
locationClient = new LocationClient(this,this,this);
if (!locationClient.isConnected() || !locationClient.isConnecting()) {
locationClient.connect();
}
} else {
Log.e(TAG, "unable to connect to google play services.");
}
}
protected void sendLocationDataToWebsite(Location location) {
// formatted for mysql datetime format
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = new Date(location.getTime());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.websmithing.gpstracker.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
float totalDistanceInMeters = sharedPreferences.getFloat("totalDistanceInMeters", 0f);
boolean firstTimeGettingPosition = sharedPreferences.getBoolean("firstTimeGettingPosition", true);
if (firstTimeGettingPosition) {
editor.putBoolean("firstTimeGettingPosition", false);
} else {
Location previousLocation = new Location("");
previousLocation.setLatitude(sharedPreferences.getFloat("previousLatitude", 0f));
previousLocation.setLongitude(sharedPreferences.getFloat("previousLongitude", 0f));
float distance = location.distanceTo(previousLocation);
totalDistanceInMeters += distance;
editor.putFloat("totalDistanceInMeters", totalDistanceInMeters);
}
editor.putFloat("previousLatitude", (float)location.getLatitude());
editor.putFloat("previousLongitude", (float)location.getLongitude());
editor.apply();
final RequestParams requestParams = new RequestParams();
requestParams.put("latitude", Double.toString(location.getLatitude()));
requestParams.put("longitude", Double.toString(location.getLongitude()));
Double speedInMilesPerHour = location.getSpeed()* 2.2369;
requestParams.put("speed", Integer.toString(speedInMilesPerHour.intValue()));
try {
requestParams.put("date", URLEncoder.encode(dateFormat.format(date), "UTF-8"));
} catch (UnsupportedEncodingException e) {}
requestParams.put("locationmethod", location.getProvider());
if (totalDistanceInMeters > 0) {
requestParams.put("distance", String.format("%.1f", totalDistanceInMeters / 1609)); // in miles,
} else {
requestParams.put("distance", "0.0"); // in miles
}
requestParams.put("username", sharedPreferences.getString("userName", ""));
requestParams.put("phonenumber", sharedPreferences.getString("appID", "")); // uuid
requestParams.put("sessionid", sharedPreferences.getString("sessionID", "")); // uuid
Double accuracyInFeet = location.getAccuracy()* 3.28;
requestParams.put("accuracy", Integer.toString(accuracyInFeet.intValue()));
Double altitudeInFeet = location.getAltitude() * 3.28;
requestParams.put("extrainfo", Integer.toString(altitudeInFeet.intValue()));
requestParams.put("eventtype", "android");
Float direction = location.getBearing();
requestParams.put("direction", Integer.toString(direction.intValue()));
final String uploadWebsite = sharedPreferences.getString("defaultUploadWebsite", defaultUploadWebsite);
LoopjHttpClient.get(uploadWebsite, requestParams, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, byte[] responseBody) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - success", uploadWebsite, requestParams, responseBody, headers, statusCode, null);
stopSelf();
}
@Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] errorResponse, Throwable e) {
LoopjHttpClient.debugLoopJ(TAG, "sendLocationDataToWebsite - failure", uploadWebsite, requestParams, errorResponse, headers, statusCode, e);
stopSelf();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(TAG, "position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
// we have our desired accuracy of 500 meters so lets quit this service,
// onDestroy will be called and stop our location uodates
if (location.getAccuracy() < 500.0f) {
stopLocationUpdates();
sendLocationDataToWebsite(location);
}
}
}
private void stopLocationUpdates() {
if (locationClient != null && locationClient.isConnected()) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
}
/**
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(1000); // milliseconds
locationRequest.setFastestInterval(1000); // the fastest rate in milliseconds at which your app can handle location updates
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationClient.requestLocationUpdates(locationRequest, this);
}
/**
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onDisconnected() {
Log.e(TAG, "onDisconnected");
stopLocationUpdates();
stopSelf();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
stopLocationUpdates();
stopSelf();
}
}
package com.webmithing.gpstracker;
导入android.app.Service;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.location.location;
导入android.os.Bundle;
导入android.os.IBinder;
导入android.util.Log;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesClient;
导入com.google.android.gms.common.GooglePlayServicesUtil;
导入com.google.android.gms.location.LocationClient;
导入com.google.android.gms.location.LocationListener;
导入com.google.android.gms.location.LocationRequest;
导入com.loopj.android.http.AsyncHttpResponseHandler;
导入com.loopj.android.http.RequestParams;
导入java.io.UnsupportedEncodingException;
导入java.net.urlcoder;
导入java.text.DateFormat;
导入java.text.simpleDataFormat;
导入java.util.Date;
导入java.util.TimeZone;
公共类LocationService扩展了服务实现
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
位置侦听器{
私有静态最终字符串TAG=“LocationService”;
//使用WebMithing DefaultUploadWeb进行测试,然后检查您的
//您的浏览器在此处的位置:https://www.websmithing.com/gpstracker/displaymap.php
私有字符串默认上载网站;
私有布尔值currentlyProcessingLocation=false;
私人位置请求位置请求;
私人场所客户场所客户;
@凌驾
public void onCreate(){
super.onCreate();
defaultUploadWebsite=getString(R.string.default\u upload\u website);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
//如果我们目前正试图获取一个位置,而报警管理器又再次调用了该位置,
//无需开始处理新位置。
如果(!currentlyProcessingLocation){
currentlyProcessingLocation=true;
开始跟踪();
}
返回开始时间不粘;
}
私有void startTracking(){
日志d(标签“开始跟踪”);
if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)=ConnectionResult.SUCCESS){
locationClient=新locationClient(这个,这个,这个);
如果(!locationClient.isConnected()| |!locationClient.isConnecting()){
locationClient.connect();
}
}否则{
Log.e(标签“无法连接到google play服务”);
}
}
受保护的无效sendLocationDataToWebsite(位置){
//已格式化为mysql日期时间格式
DateFormat DateFormat=新的简化格式(“yyyy-MM-dd HH:MM:ss”);
dateFormat.setTimeZone(TimeZone.getDefault());
日期=新日期(location.getTime());
SharedReferences SharedReferences=this.getSharedReferences(“com.webmithing.gpstracker.prefs”,Context.MODE\u PRIVATE);
SharedReferences.Editor=SharedReferences.edit();
float totalDistanceInMeters=sharedPreferences.getFloat(“totalDistanceInMeters”,0f);
boolean firstTimeGettingPosition=SharedReferences.getBoolean(“firstTimeGettingPosition”,true);
if(第一次获取位置){
putBoolean(“firstTimeGettingPosition”,false);
}否则{
位置previousLocation=新位置(“”);
setLatitude(SharedReferences.getFloat(“previousLatitude”,0f));
setLength(SharedReferences.getFloat(“PreviousLength”,0f));
浮动距离=位置。距离到(以前的位置);
总距离(米+=距离);
putFloat(“totalDistanceInMeters”,totalDistanceInMeters);
}
putFloat(“previousLatitude”,(float)location.getLatitude());
putFloat(“previousLongitude”,(float)location.getLongitude());
editor.apply();
final RequestParams RequestParams=新RequestParams();
requestParams.put(“纬度”,Double.toString(location.getLatitude());
requestParams.put(“longitude”,Double.toString(location.getLongitude());
Double speedInMilesPerHour=location.getSpeed()*2.2369;
requestParams.put(“速度”,Integer.toString(speedInMilesPerHour.intValue());
试一试{
requestParams.put(“日期”,URLEncoder.encode(dateFormat.format(日期),“UTF-8”);
}捕获(不支持的编码异常e){}
requestParams.put(“locationmethod”,location.getPr