数据推送到Android应用 [英] Push data to android app

查看:116
本文介绍了数据推送到Android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个通过Web服务PHP连接到MySQL数据库的Andr​​oid应用程序。现在,我可以从MySQL数据库中读取数据并将其添加到我的Andr​​oid SQLite数据库就好了。

I am developing an android app that is connected to a Mysql database through a php webservice. Right now I can read the data from the Mysql database and add them to my android sqlite database just fine.

现在我需要从数据库到应用推到数据的任何更新。寻找到这个有很多之后,建议最好的解决方案是GCM但是由于该项目的一些限制,我不能使用它。任何人都可以提出任何替代方案牢记我在所有这一切都相当新。

Now I need to push any updates to the data from the database to the app. After looking into this a lot the best solution that is suggested is GCM however due to some restrictions in the project I am not allowed to use it. Can anyone suggest any alternatives keeping in mind that I am fairly new at all of this.

感谢。

推荐答案

AsyncTask的是由Android提供了一个抽象类,这有助于我们正确地使用UI线程。这个类允许我们执行长/后台操作并显示在UI线程上它的结果,而无需操纵线程。

AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

您可以使用AsyncTask的打电话给你的web服务:

You can use AsyncTask to call your webservices:

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 类的对象进行Web服务调用,

now, perform webservice call by creating object of LongOperation class,

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

在PHP中,你应该写如下:

in PHP you should wrote as follows:

<?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服务,使之更加安全。 :)

You can use POST method to pass parameters to webservice to make it more secure. :)

这篇关于数据推送到Android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆