将GPS数据发送到localhost进行测试

时间:2013-10-06 08:38:57

标签: php android gps demo

我是一个开发Android应用程序的新手,但这里是。 我正在尝试设计一个应用程序来获取用户的GPS位置,然后将此GPS数据发送到远程服务器(但将使用xampp服务器进行测试,但如果我使用在线服务器则需要进行哪些更改)我有获取gps位置的代码,以及发布数据的php页面,但我面临的问题是,idont知道我需要在程序中将这些数据发送到php文件需要做什么样的更改。 所以,如果任何人可以给我一个解决方案或指向一个演示代码o教程将是有帮助的。

package com.example.gpstracking;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AndroidGPSTrackingActivity extends Activity {

Button btnShowLocation;

// GPSTracker class
GPSTracker gps;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

    // show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {        
            // create class object
            gps = new GPSTracker(AndroidGPSTrackingActivity.this);

            // check if GPS enabled     
            if(gps.canGetLocation()){

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

                // \n is for new line
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
            }else{
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }

        }
    });
}

}

package com.example.gpstracking;

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;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

/*
 * COMMENTS LocationListner is used for receiving notifications from the
 * LocationManager when the location has changed.
 * refrence:http://developer.android.
 * .com/reference/android/location/LocationListener.html to access system
 * services global variable declaration to use anywhere
 */

private final Context mContext;

// GPS status flag to check if GPS is switched on or not
boolean isGPSEnabled = false;

// network status flag to check if network provider connection is switched
// on or not
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 = 1000 * 60 * 1; // 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) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                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 latitude/longitude 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;
}

// 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, to display settings pages
    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, to cancel
    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;
}

}

<?php

//A class file to connect to database

class DB_CONNECT {

// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/**
  * Function to connect with database
 */
function connect() {
    // import database connection variables
    require_once '/db_config.php';

    // Connecting to mysql database
    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

    // Selecing database
    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

    // returing connection cursor
    return $con;
}

/**
 * Function to close db connection
 */
function close() {
    // closing db connection
    mysql_close();
}

}

&GT;

<?php

/*
 * All database connection variables
 */

define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "coordinate"); // database name
define('DB_SERVER', "localhost"); // db server
?>

2 个答案:

答案 0 :(得分:0)

在Android中,您可以在服务器中执行HTTP邮件.. 并在您的服务器上(PHP文件)尝试存储位置..

<?php If(isset($_POST['lng']) && isset($_POST['lat'])){ StoreinDp($_POST['lng'],$_POST['lat']);}

代码就像提示..但你必须按照自己的方式去做..

尝试使用HTTPPOST:http post request for android

答案 1 :(得分:0)

您使用冗长的方式连接到服务器,使用Volley库将您的应用程序连接到php。不要忘记将volley库添加到你的Android应用程序依赖项中。

//这里REGISTER_URL是你的php文件的网址e-g localhost:port / phpFilename.php

Android端代码:

private void registerUser(){
        final String username = editTextUsername.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();


        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //do stuffs with response of post
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //do stuffs with response erroe
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();

                params.put(KEY_PASSWORD,password);
                params.put(KEY_EMAIL, email);
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }