【问题标题】:Push data to android app将数据推送到安卓应用
【发布时间】:2013-12-18 23:32:52
【问题描述】:

我正在开发一个通过 php webservice 连接到 Mysql 数据库的 android 应用程序。现在我可以从 Mysql 数据库中读取数据并将它们添加到我的 android sqlite 数据库中就好了。

现在我需要将数据的任何更新从数据库推送到应用程序。在研究了很多之后,建议的最佳解决方案是 GCM,但是由于项目中的一些限制,我不允许使用它。任何人都可以提出任何替代方案,请记住我在所有这些方面都很新。

谢谢。

【问题讨论】:

  • 你试过异步调用webservice吗?
  • @Ravi 不,我没有,但是这么快我不能有长时间的延迟
  • @Ravi 嗨,我刚刚意识到这是轮询方法,我正在寻找一种推送方法
  • 嗯,这就是我通常使用的解决方案..

标签: php android mysql sqlite push


【解决方案1】:

AsyncTask 是 Android 提供的一个抽象类,可以帮助我们正确使用 UI 线程。此类允许我们执行长/后台操作并在 UI 线程上显示其结果,而无需操作线程。

您可以使用 AsyncTask 调用您的网络服务:

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
            try {
                //call your webservice to perform MySQL database opration
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
                StrictMode.setThreadPolicy(policy);
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new Http Get("http://yourserver.com/webservices/service.php?id="
                    + URLEncoder.encode("record_id") +"&param1="
                    + URLEncoder.encode("param1 value") + "&param2="+ URLEncoder.encode("param2 value"));

                HttpResponse response = httpclient.execute(httpget);
                final String str=EntityUtils.toString(response.getEntity());

                myjson = new JSONObject(str);
                //perform JSON parsing to get webservice result.
                if (myjson.has("success") == true) {
                    //Updation is succesful

                } else {
                    //failed to perform updation

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        // This will be executed after completion of webservice call. and `String result` will have returned value from doInBackground()
        // might want to change "executed" for the returned string passed
        // into onPostExecute() but that is upto you

    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

现在,通过创建LongOperation类的对象来执行webservice调用,

LongOperation webCall = new LongOperation();
webCall.execute();

在 PHP 中你应该这样写:

<?php

//DB Connection code:
$dbhost = "server";
$dbuser = "user_name";
$dbpassword = "pass";
$database = "your_db";

// connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: ".mysql_error());
mysql_select_db($database, $db) or die("Error conecting to db.");

header("Content-type: text/json");

if (!isset($_GET['id']) || $_GET['id'] == "" ||!isset($_GET['param1']) || $_GET['param1'] == "" || !isset($_GET['param2']) || $_GET['param2'] == "" ){
    echo json_encode(array('error' => 'Required arguments missing.'));
    exit;
}
$id = mysql_real_escape_string($_GET['id']); //escape string to prevent SQL injection attack.
$param1 = mysql_real_escape_string($_GET['param1']);
$param2 = mysql_real_escape_string($_GET['param2']);

$sql = "update your_table set param1='$param1',param2='$param2' where id=$id";

mysql_query($sql);

if (mysql_affected_rows()==1) {
    echo json_encode(array('success' => "updated"));
}else{
    echo json_encode(array('error' => "not updated"));
}
?>

您可以使用 POST 方法将参数传递给 webservice 以使其更安全。 :)

【讨论】:

  • 非常感谢你,我只有一个问题,我应该多久执行一次 LongOperation 才能让我的应用程序高效
  • 这取决于您的应用程序要求更新 MySQL 中的数据。可能在您可以致电的某个事件或某个时间间隔。
猜你喜欢
  • 1970-01-01
  • 2021-11-09
  • 2017-12-01
  • 2013-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多