Sending data from Android to a PHP server

北慕城南 提交于 2019-12-05 22:28:35

Building upon @DarkXphenomenon answer, make sure you have the right permissions.

// to retrieve location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// to retrieve location
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
// to send data
<uses-permission android:name="android.permission.INTERNET"/>

Then in your java class you can use this code to send the data to the php file. Make sure to catch any exceptions.

String and = "&";

                    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://my site.com/gpsdata.php?imei="+imei+and+"lat="+lat+and+"lng="+lng+and+"alt="+alt+and+"spd="+speed);

        try {

             httpclient.execute(httppost);
            Log.d(TAG, "Data sent!");
        } catch (ClientProtocolException e) {
            Toast.makeText(this,
                    "Client protokol exception ", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(this,
                    "IO exception " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }

You also need to make sure that your location variables such as latitude or longitude are strings otherwise you will get some unexpected errors. Normally the location variables would be a double or a float. To convert a double to a string, excecute

String Longitude = Double.toString(doubleToConvertToString);

And likewise a Float to a String

String Longitude = Float.toString(doubleToConvertToString);

The manifest needs to contain

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />`

Update: Network connections are no longer allowed in the UI thread. You need to then issue an HTTP get wrapped in an AsyncTask<> which will be parsed and interpreted by your PHP backend. An example is at http://developer.android.com/training/basics/network-ops/connecting.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!