0

在我的应用程序中(只要它是打开的),我想将我的数据与我的服务器同步。

我的策略如下:

//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() 吗?

4

1 回答 1

1

是的,你是第二个 Runnable 将在一个新线程而不是 UI 线程上运行。

当您这样做时,new Handler();会为当前线程创建一个句柄,如果此代码在onCreate该线程中,则该代码将是 UI 线程。

因此,当您这样做时,handler.post它会发布到 UI 线程 (runnable1) 上,但是当您启动 runnable2 时,您会明确创建一个新线程来运行它。

每 1 秒创建一个新线程postDelayed ..1000


要停止重复运行,您需要调用任何 Activity (我假设调用removeCallbacks(runnable1)in )onPausepostDelayedonCreate

于 2013-09-19T12:42:21.813 回答