android - 在定时器 Android 上运行新线程

标签 android multithreading timer

我一直在开发一个 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/

相关文章:

Android 屏幕方向行为

java - android:layout_below 与 ImageView 不工作

arrays - 如何在 “pool”线程之间划分值范围?

ios - Swift 中的无效定时器

javascript - 基于计时器 jQuery 循环悬停状态

android - 在 flutter 中,底部重载了 248 像素

android - 这是导入预制数据库并打开和关闭的正确方法吗?

multithreading - 强制跨 IORef : rnf, deepSeq 或其他东西进行评估?

java - yield() 和 sleep() 有什么区别?

java - 计时器未定义