这是我的班级
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;
}
}
这是我的asyncTask:
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中,3秒睡眠)不再了。
如何更新纬度和经度?
答案 0 :(得分:0)
要定期向服务器发送更新,我建议您使用Android AsyncHttp客户端,它是一个不错的库,可以节省一些时间。
关于你的问题:
您的API调用应该在您的第一个类的OnLocationChanged中。例如:
@Override
public void onLocationChanged(Location location) {
sendLocationToServer(location, new MyAsyncHttpResponseHandler());
}
您可以将您的位置作为Json tring发送,但是您需要对其进行Jsonize。 您还可以将Latitude和Longitude作为字符串放在参数中。
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
}
}
从我读到的,我只能看到冰山一角。但这应该指向正确的方向。 祝你好运。