如何重新启动在android系统线程? [英] how to restart a thread in android?

查看:190
本文介绍了如何重新启动在android系统线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用我有一个UI更新线程,保持我的所有视图先进的日期。

in my android app i have an ui-update-thread that keeps all my views up-to-date.

protected Thread UIUpdateThread = new Thread()
{
 @Override
 public void run()
 {
  while(true)
  {
    query_some_data_from_service(); // gets some "fresh" data from a service
    UIUpdateHandler.sendEmptyMessage(0); // will update all ui elements with the new values
    sleep(1234);
  }
 }
};

我开始这个线程中的onCreate()以

i start this thread in onCreate() with

UIUpdateThread.start();

,当我离开活动(例如,因为我切换到另一个活动)我叫一切工作就好了:)

and everything works just fine :) when i leave the activity (e.g. because i switch to another activity) i call

UIUpdateThread.interrupt();

中的onStop(),以prevent运行所有的时间线程。如果我不这样做,它会继续运行,即使我关闭应用程序!?!?!

within onStop() to prevent the thread from running all the time. if i dont do this, it would keep running even if i close the app !?!?!!

问题是:我如何从一些其他活动回到这个时候把这个线程起死回生?运行()不工作,要求初始启动()像onResume(其它方法)崩溃的应用程序。

problem is: how do i bring this thread back to life when returning from some other activity to this one? run() doesnt work, calling the initial start() in some other method like onResume() crashes the app.

我已经尝试了很多东西,但似乎没有任何工作:(

i already tried a lot of things, but nothing seems to work :(

推荐答案

Atmocreation的答案是正确的......假设你的实现是摆在首位是个好主意。

Atmocreation's answer is the correct one...assuming that your implementation is a good idea in the first place.

首先,你在这里展示的线程中运行简单,并立即终止其自身,这样你就不会需要调用中断()停止它。在这种情况下,你可能是更好的服务切换到的AsyncTask 而不是你自己的线程和处理程序,因为你需要更少的code,可以采取<$优势C $ C>的AsyncTask 的线程池。

First, the thread that you show here runs briefly and immediately terminates on its own, so you would not need to call interrupt() to stop it. In that case, you are probably better served switching to an AsyncTask rather than your own thread and handler, as you will need less code and can take advantage of AsyncTask's thread pool.

如果你真正的线程是不是你在这里展示,而是某种无限循环,这是一般一个坏主意。从不创建忙循环,尤其是在Android系统。最有可能的,对于你的问题更好的解决方案,或许是一个会避免中断()以及

If your real thread is not what you show here, but some sort of infinite loop, that is a bad idea in general. Never create busy loops, particularly in Android. Most likely, there is a better solution for your problem, perhaps one that would avoid the need for interrupt() as well.

这篇关于如何重新启动在android系统线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆