从服务器中提取Android应用中的实时数据

时间:2016-09-09 15:17:52

标签: android android-asynctask asynctaskloader

我开发了一个从服务器加载数据的Android应用程序。但是当用户按下加载按钮时,应用程序会从服务器加载数据。

但是我需要在不按下重新加载按钮的情况下显示实时数据。例如; Gmail应用会在不按任何UI的情况下显示新电子邮件。

如何在我的应用中执行此操作?

现在我正在使用AsyncTask来访问服务器,如下所示

public class HttpAsyncTaskAccountInfo extends AsyncTask<String, Void, String> {
    public static final String XXXXX = "XXXXX_XXXX";
    private final Activity context;
    SharedPreferences XXXX_XXXXX = null;
    private ProgressDialog dialog;
    private String finder_email = null, finder_name = null;

    public HttpAsyncTaskAccountInfo(Activity activity) {
        context = activity;
        dialog = new ProgressDialog(context);


    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Checking Account Info, please wait.");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... urls) {

        return Get.GET(urls[0]);
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        dialog.dismiss();
        try {
            JSONArray jArray = new JSONArray(result);
            JSONObject jObj = jArray.getJSONObject(0);

            Log.d("JSON_STRING", jObj.toString());

            String jsonTotalSpent = jObj.getString("total_spent_till_now");
            String jsonTotal_spent_with_validity = jObj.getString("total_spent_with_validity");
            String jsonHas_paid = jObj.getString("has_paid");

            if (jsonHas_paid.equals("true"))
                Globals.account_has_paid = "Paid";
            else Globals.account_has_paid = "Not Paid";

            Log.d("JSON_STRING", jsonTotalSpent);
            Log.d("JSON_STRING", jsonTotal_spent_with_validity);
            Log.d("JSON_STRING", jsonHas_paid);
            Log.d("JSON_STRING", Globals.account_has_paid);

            Globals.account_total_spent = jsonTotalSpent;
            Globals.account_total_spent_with_validity = jsonTotal_spent_with_validity;

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

FireBase Cloud Messenging旨在让服务器向客户端通知新数据,或者至少应该与服务器联系以获取新数据。

答案 1 :(得分:-1)

重新加载的极简主义版本可能会像每秒钟调用你的函数一样。这取决于你的最终目标是什么,这可能非常简单或困难。

// Init
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        yourfunction();
        handler.postDelayed(this, 1000);
    }
};

//Start
handler.postDelayed(runnable, 1000);