Android服务连接到服务器

时间:2016-04-23 04:25:50

标签: php android mysql android-service

我目前正在使用一个Android应用程序,它通过PHP从MySQL数据库中检索数据,为此我使用了服务,但我无法连接到MySQL。 有没有人对此有所了解或是服务支持吗?非常感谢。

public class MyAlarmService extends Service{

private NotificationManager mManager;
public int response = 0;
@Override
public IBinder onBind(Intent arg0)
{
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onCreate()
{
    // TODO Auto-generated method stub
    super.onCreate();
}

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    makePostRequest();
}

private void makePostRequest() {


    HttpClient httpClient = new DefaultHttpClient();
    // replace with your url
    HttpPost httpPost = new HttpPost("http://10.0.3.2/folder/detect_h_area.php");


    //Post Data
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
    nameValuePair.add(new BasicNameValuePair("latitued", "34.52234315"));
    nameValuePair.add(new BasicNameValuePair("longitued", "69.18254074"));
    nameValuePair.add(new BasicNameValuePair("token", "token123585775"));

    //Encoding POST data
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    //making POST request.
    try {
        HttpResponse response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

}

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

}

PHP文件

$con = mysql_connect("localhost","root","root");
mysql_select_db("test_db");

$lat = $_POST['latitued'];
$lon = $_POST['longitued'];

if($lat != "" || $lat != "0"){
    $lat = substr($lat, 0,5);
}
if($lon != "" || $lon != "0"){
    $lon = substr($lon, 0,5);
}

$result = mysql_query('SELECT count( * ) AS total
                        FROM table1
                        WHERE geolat LIKE "%'.$lat.'%"
                        AND geolng LIKE "%'.$lon.'%"
                        GROUP BY '.$lat.' , '.$lon.''
                    );

$row = mysql_fetch_assoc($result);

if($row['total'] > 0)
{
    echo $row['total'];exit;
}
else
{
    echo "null";exit;
}

1 个答案:

答案 0 :(得分:0)

您是否为MySQL连接编写PHP配置?

编辑:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
 // Check connection
 if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
 } 
 echo "Connected successfully";
 ?>