在Android中立即从MySQL获取数据的有效方法?

时间:2014-09-14 11:33:43

标签: android mysql

我有一个简单的聊天应用程序,我想检查我的数据库并立即获取新消息, 我的代码有效,但我不知道这是否是正确的方法。

所以我在服务中使用了一个Thread,我调用了Thread.sleep并让它睡了一秒

class messagesThread extends Thread {
    @Override
    public void run() {
        while (true){
            try {
                   String response = null;
                   ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                   params.add(new BasicNameValuePair("id", id));
                   String url = "http://192.168.1.2/getMessages.php";
                   URL messagesURL = null;
                   HttpURLConnection connection = null;
                   InputStream inputStream = null;
                   try {
                          messagesURL = new URL(url);
                          connection = (HttpURLConnection) messagesURL.openConnection();
                          connection.setConnectTimeout(3000);
                          connection.setRequestMethod("POST");
                          connection.setDoInput(true);
                          connection.setDoOutput(true);

                          OutputStream outputStream = connection.getOutputStream();
                          BufferedWriter bufferedWriter  = new BufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));
                          bufferedWriter.write(getQuery(params));
                          bufferedWriter.flush();
                          bufferedWriter.close();


                          inputStream = connection.getInputStream();
                          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                          StringBuffer stringBuffer = new StringBuffer();
                          String line = null;
                          stringBuffer.append(line + "\n");
                          while ((line = reader.readLine()) != null) {
                                stringBuffer.append(line + "\n");
                          }

                          response = stringBuffer.toString();

                   }catch (MalformedURLException e) {
                          e.printStackTrace();
                   } catch (IOException e) {
                          e.printStackTrace();

                   }finally {
                     if(connection!=null){
                        connection.disconnect();
                     }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (response != null) {
            try {
                JSONObject jsonObj = new JSONObject(response);
                if (jsonObj != null) {
                    JSONArray messagesArray = jsonObj.getJSONArray("MessageArray");

                    for (int i = 0; i < messagesArray.length(); i++) {
                        JSONObject result = (JSONObject) messagesArray.get(i);
                        //I receive data here
                        thereIsNewData = true;
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                thereIsNewData = false;
               }
                sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}

getMessages.php:

<?php

    $host='localhost';
    $uname='root';
    $pwd='admin';
    $db="db";
    $con=mysql_connect($host,$uname,$pwd);
    if(!$con){
       die("connection failed");
    }

    mysql_select_db($db,$con);
    $response = array();
    $response["MessageArray"] = array();
    $id = $_REQUEST['id'];

    $getMSG = mysql_query("SELECT * FROM Messages WHERE Receiver = '$id' ",$con);
    while($row = mysql_fetch_array($getMSG)){
        $tmp = array();
        $tmp['sender'] = $row['Sender'];
        $tmp['msg'] = $row['Message'];
        array_push($response["MessageArray"], $tmp);

    }
    echo json_encode($response);
?>

服务器上的这个很重吗?因为当我运行我的应用程序并转到MySQL时,页面滞后并且它会永远加载

所以我想知道是否有比这更有效的方式

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Google Cloud Messaging之类的服务,而不是轮询服务器以获取新消息,这样更有效,更实用。