我是android的新手,我正在尝试将gps坐标发送到Web服务器。我已经获得GPS坐标并每X秒请求更新一次。
我想要的是使用服务将这些coords发送到Web服务器并以不同的时间间隔运行服务(用户将决定他想要更新他的位置)。
我已经搜索过了,我希望能够更有效地进行搜索,这就是为什么我认为使用服务是最好的方法。
我无法知道在何处启动服务以及如何使其按时间间隔运行,如果我应该在服务中使用AsyncTask将coords发送到网络服务器。
任何暗示都会受到赞赏。
谢谢!
答案 0 :(得分:3)
使用 AlarmManager 每隔X秒启动一次服务。
服务应包含一个实现位置监听器的类。
参考本教程 link ,这将有助于您了解服务和时间 时间间隔
您只需从服务中获取活动中的坐标,然后使用异步任务将其发送到服务器强>
希望它会对你有所帮助。
答案 1 :(得分:1)
您可以在不使用AlarmManager的情况下执行此操作。 我使用了来自LocationManager的onLocationChanged()
<强> LocServ.java 强>
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by BrijD on 14-12-22.
*/
public class LocServ extends Service implements LocationListener {
private static String url_insert_location = "http://172.20.10.4/testing/insert.php";
public static String LOG = "Log";
JSONParser jsonParser = new JSONParser();
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 = 0; // 0 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 ; // 1 second
// Declaring a Location Manager
protected LocationManager locationManager;
public LocServ(Context context){
this.mContext = context;
}
public LocServ(){
super();
mContext = LocServ.this;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.i(LOG, "Service started");
Log.i("asd", "This is sparta");
new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()));
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(LOG, "Service created");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG, "Service destroyed");
}
class SendToServer extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... la ) {
try {
Log.i("string" , la[0]);
String longi = la[0];
String lati = la[1];
// Building Parameters
Log.d("value", lati);
Log.d("value", longi);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("longitude", longi));
params.add(new BasicNameValuePair("latitude", lati));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_insert_location, "POST", params);
Log.d("Create Response", json.toString());
} catch (Exception e) {
Log.i("error", e.toString());
}
return "call";
}
}
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) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
//updates will be send according to these arguments
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
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;
}
@Override
public void onLocationChanged(Location location) {
//this will be called every second
new SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
答案 2 :(得分:0)
使用以下服务相关代码来满足您的要求
在onTick()
方法中您可以编写代码以将数据(GPS坐标)从您的设备发送到Web服务器,即使您可以在此服务中编写GPS相关代码(获取gps坐标)
TimerService.java
package com.android.yourpackagename;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
public class TimerService extends Service {
// variables
MyCounter timer;
@Override
public void onCreate() {
timer = new MyCounter(30 * 60 * 1000, 1000);//counter of 30minutes and tick interval is //1 second(i.e.1000) you can increase its limit whatever you want as per your requirement
super.onCreate();
timer.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private class MyCounter extends CountDownTimer {
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@SuppressWarnings("static-access")
@Override
public void onFinish() {
//timer finished 30 minutes
stopSelf()//to stop service after counter stop
}
@Override
public void onTick(long millisUntilFinished) {
//timer clock tick event after each 1 second
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
timer.cancel();
super.onDestroy();
// call start servce here for lifetime running of service
// startService(new Intent(this, TimerService.class));
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
使用下面的代码
将TimerService.java注册到manifest中<service
android:name="com.android.yourpackagename.TimerService"
android:process=":TimerService" >
</service>
使用类似
的startService()方法从您的活动中启动服务 startService(new Intent(getApplicationContext(), TimerService.class));
使用像
这样的stopService()方法停止服务 stopService(new Intent(getApplicationContext(),
TimerService.class));
希望这会帮助你让它对我有同样的要求:)
答案 3 :(得分:0)
我认为你应该使用凌空库而不是异步任务
这link解释了差异 这是一种可以帮助您了解如何使用它的方法:
public static void postLatAndLongAndId(final Context context,String id,String imei,String latitude,String longitude) {
// Tag used to cancel the request
String tag_string_req = "req_login";
// progress bar showing
pDialog.setMessage("votre reservation est en cours de traitement ...");
showDialog();
//create jsonObject to post it
final JSONObject body = new JSONObject();
try {
body.put("id_client",id );
body.put("imei",imei);
body.put("lat",latitude);
body.put("long",longitude);
body.put("type","b2c");
// Log.e(TAG, "jsonObj body: " + body );
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_POSTING_USER_COORDINATES, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Log.e(TAG, "WebS Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
// Log.e(TAG, "affichage de jobj =: " + jObj );
String status = jObj.getString("status");
// Log.e(TAG, "status = ok ?? " + status.equals("OK") );
// Check for error node in json
if (status.equals("OK")){
//data send successfully
hideDialog();
} else {
// Error . Get the error message
String errorMsg = jObj.getString("message");
// Log.e(TAG, "webS Error: "+errorMsg);
Toast.makeText(context,
errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
alert.showAlertDialog(context, "Désolé", " Une erreur est survenue, veuillez essayer ultérieurement",true);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Log.e(TAG, "webS Error: " + error.getMessage());
Toast.makeText(context,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
alert.showAlertDialog(context, "Désolé", " Une erreur est survenue, veuillez essayer ultérieurement",true);
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
// Log.e(TAG, "j'ai executé la methode getBody!! ");
return body.toString().getBytes();
}
@Override
public String getBodyContentType()
{
return "application/json";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
希望它有所帮助:)
答案 4 :(得分:0)
Alaram服务或计时器是执行时间相关任务的好方法,但如果您使用报警管理器而不是请求操作系统执行任务,则最好使用您选择的后期处理程序来执行您想要的任何任务一段时间后,与计时器相同,但对于您在自己的代码中使用/管理的处理程序