Sending data from Android to a PHP server

北城余情 提交于 2019-12-22 10:37:21

问题


I am having an application in android and I want to send the latitude and longitude of the android mobile to the web PHP server through a url (like=..mydata.php?lat=76867&long=87979). I am having the php code that saves the data in database if this url is hit.

All I am not getting is that how to send the latitude and longitude through my android mobile phone to the PHP server.


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/11575591/sending-data-from-android-to-a-php-server

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