1

我正在使用以下代码访问 url:

final Handler handler = new Handler();
Runnable runnable = new Runnable() 
{
   public void run() 
   {
       img.setImageBitmap(returnBitmap("fromurl")); 
       handler.postDelayed(this, 50);  
   }
};

handler.postDelayed(runnable, 2000);

我观察到,如果服务器没有启动,如果我点击后退按钮,应用程序需要很长时间才能正确关闭。无论如何我可以加快退出程序。

4

2 回答 2

1

Runnables will exit automatically when finished with their run() method. If you are employing a loop to do some work, the solution that Jay Ho suggested will help exit from the loop cleanly. If you want to prevent the Handler from executing the runnable (before it posts) you can use handler.removeCallbacksAndMessages(null)1 to clear the queue. Placing it in onDestroy() is your best bet. Otherwise, you're on your own. Once you've spawned a thread, you're at the mercy of the Android operating system to terminate it once its done.

Side note: I've run into problems like this before, and it's usually a call to a system service or the implementation of a Broadcast Listener or Alarm that mucks up the exit process.

于 2012-07-25T04:43:08.447 回答
0
private Runnable runnable = new Runnable() {
    private boolean killMe=false;
    public void run() {
        //some work
        if(!killMe) {

            img.setImageBitmap(returnBitmap("fromurl"));
            handler.postDelayed(this, 50);
        }
    }
    public void kill(){
        killMe=true;
    }
};

ThreadPoolExecutor threadPoolExecutor = Executors.newSingleThreadExecutor();
Runnable longRunningTask = new Runnable();

// submit task to threadpool:
Future longRunningTaskFurure = threadPoolExecutor.submit(longRunningTask);

... ...
// At some point in the future, if you want to kill the task:
longRunningTaskFuture.cancel(true);
... ...
于 2012-07-25T03:36:29.717 回答