2013-05-26 29 views
1

我一直在研究一個android應用程序,它定期檢查使用JSON的mysql數據庫,並且一切工作正常,我的代碼。在定時器上運行新線程Android

即時運行這個作爲一個計時器,因爲它只運行一次,然後停止。 我設法讓工作的唯一代碼在凍結的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(); 
} 
+1

您的代碼沒有正確縮進......讓我們真的很難閱讀。 –

+0

你的文章缺少很多信息(例如,什麼是'mHandler'變量,什麼類是'onCreate'方法,哪裏是具有計時器的代碼等) –

+1

爲什麼不使用asynctask for這個目的 – Raghunandan

回答

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()並調用​​方法。

對於這樣一個簡單的異步任務,通常的做法是讓使用它(如果只有一個Activity需要吧)Activity類中的私人內部類。您可能需要更改某些活動變量的範圍,以便內部類可以使用它們(例如,將局部變量移動到成員變量中)。