gpt4 book ai didi

java - 无法更新纬度和经度

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:35 25 4
gpt4 key购买 nike

这是我的类(class)

package com.example.seadog.gps;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSTracker 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 = 5000; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(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) {

} else {
this.canGetLocation = true;

if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}

if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

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){
locationManager.removeUpdates(GPSTracker.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;
}

}

这是我的异步任务:

class MyAsyncTask extends AsyncTask<JSONObject, Void, JSONObject> {

@Override
protected void onPreExecute() {

}

protected JSONObject doInBackground(JSONObject... params) {

int ID=0;
int random=0;
int Code=0;

String string = null;

double latitude;
double longitude;

try {
JSONObject json = params[0];
ID = Integer.parseInt(json.getString("ID"));
random = Integer.parseInt(json.getString("random"));
Code = Integer.parseInt(json.getString("Code"));
} catch (Exception e){
e.printStackTrace();
}

int i=0;

while(i<1){

latitude = gps.getLatitude();
longitude = gps.getLongitude();

try {
JSONObject json = new JSONObject();
json.put("ID", ID);
json.put("random", random);
json.put("latitude", latitude);
json.put("longitude", longitude);
json.put("Code", Code);

string = "json="+json;

} catch (Exception e){
e.printStackTrace();
}

try {

URL url = new URL("http://10.0.2.2/gps.php");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setConnectTimeout(15000);
httpCon.setRequestProperty("Content-Length", Integer.toString(string.length()));
httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpCon.setRequestMethod("POST");

DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(string);
wr.flush();
wr.close();

int responseCode = httpCon.getResponseCode();

if(Code==0){

if (responseCode==-1) { httpCon.connect(); }

InputStream is = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();

String result = response.toString();

JSONObject json = new JSONObject(result);

try {

OutputStream file = openFileOutput("configND", Context.MODE_PRIVATE);
DataOutputStream wrf = new DataOutputStream(file);
wrf.writeBytes(result);
wrf.close();

random = Integer.parseInt(json.getString("random"));
Code=1;

} catch (Exception e){
e.printStackTrace();
}
}

if (responseCode == 200) {
Thread.sleep(3000);
}else{
httpCon.disconnect();
}

} catch (Exception e1) {
e1.printStackTrace();
}

}

return null;

}

protected void onPostExecute(Boolean result) {

}

}

在 asyncTask 中,我通过 gps.getLatitude 和 gps.getLongitude 调用纬度和经度到两个 Double 变量。第一次运行的应用程序返回 GPS 位置,但下一次迭代(我的意思是在 asyncTask 中 sleep 3 秒时)不再返回。

如何在while中更新经纬度?

最佳答案

要定期向您的服务器发送更新,我建议您使用 Android AsyncHttp 客户端,它是一个很好的库,可以帮助您节省一些时间。

至于你的问题:

您的 API 调用应位于第一个类的 OnLocationChanged 中。例如:

@Override
public void onLocationChanged(Location location) {
sendLocationToServer(location, new MyAsyncHttpResponseHandler());
}

您可以将您的位置作为 Json 字符串发送,但随后您需要对其进行 Jsonize。您还可以将纬度和经度作为字符串放入参数中。

 private void sendLocationToServer(Location location, AsyncHttpResponseHandler handler){
RequestParams params = new RequestParams();
params.put(MY_LOCATION_PARAMETER_KEY,locationAsJson);
getClient().post("mydomain.com/update/device/location",params, handler);
}

然后管理您的处理程序:

private class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler{

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//Check the server response
} else{
//Notify user of error type
}

}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//Notify user of connection error
}
}

从我读到的内容来看,我只能看到冰山一角。但这应该为您指明正确的方向。祝你好运。

关于java - 无法更新纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com