在Timer Android上运行New Thread



我一直在使用JSON定期检查mysql数据库的android应用程序,一切都与我的代码工作良好。

我有麻烦运行这作为一个计时器,因为它只运行一次,然后停止。唯一的代码,我设法得到工作运行的http请求在UI线程冻结。任何帮助都将是非常感激的。提前感谢,

@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();   
}

正如@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需要它)中使它成为一个私有的内部类。你可能需要改变一些活动变量的作用域,以便内部类可以使用它们(例如,将局部变量移动到成员变量)。

相关内容

最新更新