在我的应用程序中(只要它是打开的)我想将我的数据与我的服务器同步。
我的策略如下:
//create the handler on which we will use postdelayed
Handler handler = new Handler();
//create the first runnable.
//Will this run on UI thread at this stage ? as it is being called from the handler ?
Runnable runnable1 = new Runnable()
{
public void run()
{
Thread t = new Thread(runnable2);
}
};
//create the second runnable.
//This is for sure being called from a thread, so it will not run on UI thread ? NO ?
Runnable runnable2 = new Runnable()
{
public void run()
{
//connect to internet
//make the check periodical
handler.postdelayed(runnable1, 1000);
}
};
//call the postdelayed.
handler.postdelayed(runnable1, 1000);
如果我希望处理程序在应用程序关闭后停止其可运行任务。我有什么办法,因为我有几项活动,当他/点击主页按钮时,我不知道用户在哪里。我应该在所有onDestroys()中包含一张支票吗?
答案 0 :(得分:0)
是的,你是第二个Runnable将在一个新的线程上运行而不是UI线程。
执行new Handler();
时会创建当前线程的句柄,如果此代码在onCreate
中,则该线程将成为UI线程。
因此,当您执行handler.post
时,它将发布到UI线程(runnable1),但是当您启动runnable2时,您将显式创建一个新线程来运行它。
这可能不是每1秒创建一个新线程的正确策略(postDelayed ..1000
),可能保持对另一个后台线程的引用,并每秒发送一条消息以执行新的操作。
要停止重复的游戏,您需要在任意活动的removeCallbacks(runnable1)
中致电onPause
(我假设在postDelayed
中称为onCreate
)