1

我一直在开发一个 android 应用程序,该应用程序定期使用 JSON 检查 mysql 数据库,并且我的代码一切正常。

我无法将其作为计时器运行,因为它只运行一次然后停止。我设法开始工作的唯一代码在冻结的 UI 线程上运行 http 请求。非常感激任何的帮助。预先感谢,

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    checkUpdate.start();
    ...
}

private Thread checkUpdate = new Thread() {
    public void run() {
        try {
            // my code here to get web request to return json string
        } 

        String response = httpclient.execute(httppost, responseHandler);
                    mHandler.post(showUpdate);
    }
    ...
}


private Runnable showUpdate = new Runnable(){
    public void run(){
        try{
            // my code here handles json string as i need it
            Toast.makeText(MainActivity.this,"New Job Received...", Toast.LENGTH_LONG).show();
            showja();
        }
    }
}


private void showja(){
    Intent i = new Intent(this, JobAward.class);  
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();   
}
4

1 回答 1

1

正如@Raghunandan 所建议的那样,在Android 后台执行工作并在完成工作后修改UI 的标准方法是使用AsyncTask

首先定义一个新的子类AsyncTask

private class JsonRequestTask extends AsyncTask<HttpUriRequest, Void, String> {
     protected String doInBackground(HttpUriRequest... requests) {
         // this code assumes you only make one request at a time, but
         //   you can easily extend the code to make multiple requests per
         //   doInBackground() invocation:
         HttpUriRequest request = requests[0];

         // my code here to get web request to return json string

         String response = httpclient.execute(request, responseHandler);
         return response;
     }

     protected void onPostExecute(String jsonResponse) {
        // my code here handles json string as i need it
        Toast.makeText(MainActivity.this, "New Job Received...", Toast.LENGTH_LONG).show();
        showja();  
     }
 }

然后你会使用这样的任务,而不是你的Thread

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    JsonRequestTask task = new JsonRequestTask();
    task.execute(httppost);
    ...
}

您可以通过简单地创建一个new JsonRequestTask()并调用其execute()方法来再次运行该任务。

像这样的简单异步任务的一种常见做法是使其成为使用它的类中的私有内部类Activity(如果只有一个Activity需要它)。您可能需要更改某些活动变量的范围,以便内部类可以使用它们(例如,将局部变量移动到成员变量)。

于 2013-05-26T21:03:06.963 回答