向 Android 应用程序推送数据

3
我正在开发一个安卓应用,通过PHP Web服务连接到MySQL数据库。目前,我可以从MySQL数据库中读取数据,并将它们添加到我的安卓SQLite数据库中。现在,我需要将数据库中的更新推送到应用程序中。经过多方考虑,最好的解决方案是GCM,但由于项目中的一些限制,我不能使用它。有人能提供其他替代方案吗?请注意,我对所有这些都比较新手。谢谢。

你尝试过使用异步调用Web服务吗? - Ravi Dhoriya ツ
@Ravi 不,我没有。不过这个速度很快,我不能有太长的延迟。 - Kopiko
@Ravi 你好,我刚意识到这是轮询方法,而我正在寻找推送方法。 - Kopiko
那是我通常使用的解决方案。 - Ravi Dhoriya ツ
1个回答

0
AsyncTask是Android提供的一个抽象类,它可以帮助我们正确地使用UI线程。这个类允许我们执行长时间/后台操作,并在UI线程上显示其结果,而无需操纵线程。
您可以使用AsyncTask来调用您的Web服务:
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方法传递参数到Web服务,以使其更加安全。 :)


非常感谢,我只有一个问题,为了使我的应用程序高效,我应该多久执行一次LongOperation? - Kopiko
这取决于您的应用程序要求何时更新MySQL中的数据。可以在某些事件或某些时间间隔内调用。 - Ravi Dhoriya ツ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接