Android post json 到 API 在后台

Android post json to API in background

我有两个应用程序,我有 android 应用程序和 Rails API 上的 Ruby。在 android 中,我有一个 SQLite 数据库,几乎所有时间我都需要将 android 数据库与 API 数据库同步,但这种同步可能需要 "long time",大约 10 seconds if 是第一次同步,因此用户需要继续等待并寻找加载屏幕,直到过程完成。

所以,我想在 Rails 应用程序上向 Ruby 发送一个 post,但在加载屏幕中没有 "stop" 应用程序,我想这样做在后台同步,因此用户不会意识到应用程序正在与 API.

同步

现在,我正在尝试使用线程,但仍然失败。

谢谢。

您尝试过 ASyncTask 吗?在 doInBackground 中提取数据,然后在 onPost 方法中将其应用到您的视图。无需处理线程。完成后它将自行终止。

在你正在工作的 activity 中制作一个内部 class,像这样

class ExecuteTask extends AsyncTask<String, Integer, String>{
    @Override
    protected String doInBackground(String... params) {
        JSONObject jsonObject=new JSONObject();
        url = "http://localhost:8080/abc/xyz";//your url
        try {
            jsonObject.put("id",params[0]);
            jsonObject.put("password",params[1]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            StringEntity se = new StringEntity(jsonObject.toString());

            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            HttpResponse response = httpclient.execute(post);
            inputStream = response.getEntity().getContent();//final response
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String res = CommomUtilites.post(url,jsonObject);
        return res;
    }
 }

现在在你想执行后台任务的地方调用write

new ExecuteTask.execute(String...params)

这将隐式调用

protected String doInBackground(String... params) 

params 将是您在 execute 方法中传递的参数。

这将有效,如果您遇到任何问题,请发表评论。

Happy coding!!!