我一直在开发一个 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();
}
最佳答案
正如@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
类中的私有(private)内部类(如果只有一个 Activity
需要它)。您可能需要更改某些 Activity 变量的范围,以便内部类可以使用它们(例如,将局部变量移至成员变量)。
关于android - 在定时器 Android 上运行新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755098/