沃梦达 / 编程问答 / php问题 / 正文

将 Gps 作为后台服务运行并将坐标发送到 Web 服务器 (PHP)

Run Gps as background service and send coordinates to web server (PHP)(将 Gps 作为后台服务运行并将坐标发送到 Web 服务器 (PHP))

本文介绍了将 Gps 作为后台服务运行并将坐标发送到 Web 服务器 (PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于这个问题的问题,我已经经历了几天的所有问题,但找不到合理的答案.我是 android 和 php 的新手,所以我不知道事情是如何完成的.

所以基本上首先我想知道如何在后台运行 gps 作为服务,例如在安装应用程序时它会启动并定期将坐标发送到 Web 服务器?

解决方案

只需创建一个一直在后台运行的服务.

例如:-

AndroidLocationServices

公共类 AndroidLocationServices 扩展服务 {唤醒锁唤醒锁;私人位置管理器位置管理器;公共 AndroidLocationServices() {//TODO 自动生成的构造函数存根}@覆盖公共 IBinder onBind(Intent arg0) {//TODO 自动生成的方法存根返回空值;}@覆盖公共无效 onCreate() {//TODO 自动生成的方法存根超级.onCreate();PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");//Toast.makeText(getApplicationContext(), "服务创建",//Toast.LENGTH_SHORT).show();Log.e("Google", "服务创建");}@覆盖@已弃用公共无效onStart(意图意图,int startId){//TODO 自动生成的方法存根super.onStart(intent, startId);Log.e("谷歌", "服务启动");locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000, 5, 监听器);}私有 LocationListener 监听器 = new LocationListener() {@覆盖公共无效onLocationChanged(位置位置){//TODO 自动生成的方法存根Log.e("谷歌", "位置改变");如果(位置 == 空)返回;if (isConnectingToInternet(getApplicationContext())) {JSONArray jsonArray = new JSONArray();JSONObject jsonObject = 新 JSONObject();尝试 {Log.e("纬度", location.getLatitude() + "");Log.e("经度", location.getLongitude() + "");jsonObject.put("纬度", location.getLatitude());jsonObject.put("经度", location.getLongitude());jsonArray.put(jsonObject);Log.e("请求", jsonArray.toString());新 LocationWebService().execute(新字符串 [] {常量.TRACK_URL, jsonArray.toString() });} 捕捉(异常 e){//TODO 自动生成的 catch 块e.printStackTrace();}}}@覆盖公共无效onProviderDisabled(字符串提供者){//TODO 自动生成的方法存根}@覆盖公共无效onProviderEnabled(字符串提供者){//TODO 自动生成的方法存根}@覆盖public void onStatusChanged(String provider, int status, Bundle extras) {//TODO 自动生成的方法存根}};@覆盖公共无效 onDestroy() {//TODO 自动生成的方法存根super.onDestroy();wakeLock.release();}公共静态布尔isConnectingToInternet(上下文_context){ConnectivityManager 连接性 = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);如果(连接!= null){NetworkInfo[] info = 连接性.getAllNetworkInfo();如果(信息!= null)for (int i = 0; i < info.length; i++)if (info[i].getState() == NetworkInfo.State.CONNECTED) {返回真;}}返回假;}}

LocationWebService

public class LocationWebService extends AsyncTask{公共位置网络服务(){//TODO 自动生成的构造函数存根}@覆盖受保护的布尔doInBackground(字符串... arg0){ArrayList<NameValuePair>nameValuePairs = new ArrayList();nameValuePairs.add(new BasicNameValuePair("位置", arg0[1]));HttpClient httpclient = new DefaultHttpClient();HttpPost httppost = 新 HttpPost(arg0[0]);HttpParams httpParameters = new BasicHttpParams();httpclient = new DefaultHttpClient(httpParameters);尝试 {httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));HttpResponse 响应;响应 = httpclient.execute(httppost);StatusLine statusLine = response.getStatusLine();if (statusLine.getStatusCode() == HttpStatus.SC_OK) {Log.e("Google", "服务器响应正常");} 别的 {response.getEntity().getContent().close();抛出新的 IOException(statusLine.getReasonPhrase());}} 捕捉(异常 e){e.printStackTrace();}返回空值;}}

您可以在这个 github 项目 androidbackgroundgps 中找到一个带有 Android 应用程序和相应 WebFiles 的示例项目p>

I know there are many questions that have been asked regarding this and i have been going through all that from couple of days but could'nt find a reasonable answer. i am newbie to android and php so i have no idea how things get done.

so basically first i want to know how to run gps as a service in background like when the application is installed it starts and periodically send the coordinates to web server?

解决方案

Just create a service that runs in the background all the time.

For Example:-

AndroidLocationServices

public class AndroidLocationServices extends Service {

WakeLock wakeLock;

private LocationManager locationManager;

public AndroidLocationServices() {
    // TODO Auto-generated constructor stub
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);

    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");

    // Toast.makeText(getApplicationContext(), "Service Created",
    // Toast.LENGTH_SHORT).show();

    Log.e("Google", "Service Created");

}

@Override
@Deprecated
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);

    Log.e("Google", "Service Started");

    locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            5000, 5, listener);

}

private LocationListener listener = new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Log.e("Google", "Location Changed");

        if (location == null)
            return;

        if (isConnectingToInternet(getApplicationContext())) {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();

            try {
                Log.e("latitude", location.getLatitude() + "");
                Log.e("longitude", location.getLongitude() + "");

                jsonObject.put("latitude", location.getLatitude());
                jsonObject.put("longitude", location.getLongitude());

                jsonArray.put(jsonObject);

                Log.e("request", jsonArray.toString());

                new LocationWebService().execute(new String[] {
                        Constants.TRACK_URL, jsonArray.toString() });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
};

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    wakeLock.release();

}

public static boolean isConnectingToInternet(Context _context) {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}

}

LocationWebService

public class LocationWebService extends AsyncTask<String, String, Boolean> {

public LocationWebService() {
    // TODO Auto-generated constructor stub
}

@Override
protected Boolean doInBackground(String... arg0) {

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("location", arg0[1]));

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(arg0[0]);
    HttpParams httpParameters = new BasicHttpParams();

    httpclient = new DefaultHttpClient(httpParameters);

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response;
        response = httpclient.execute(httppost);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {

            Log.e("Google", "Server Responded OK");

        } else {

            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
}

You can find a sample project with Android App and corresponding WebFiles within this github project androidbackgroundgps

这篇关于将 Gps 作为后台服务运行并将坐标发送到 Web 服务器 (PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将 Gps 作为后台服务运行并将坐标发送到 Web 服务器 (PHP)

基础教程推荐