我最终完成了我在问题中提出的要求-我开始在
Thread中执行长期运行的操作
onDestroy()。
我必须考虑的一种情况是,即使在长时间运行之前,用户仍重新打开我的应用程序。在我的应用程序中,这意味着将创建一个新的JmDNS实例。因此,我分别在中清理每个实例
onDestroy。
您的用例可能有所不同-您可能只想在清理线程尚未运行时启动它(使用
Thread的
isAlive()方法或某种类似的技术)。
这是一些示例代码。要欣赏“分别清理每个实例”部分,请执行以下步骤序列:
- 启动应用
- 按下返回按钮。您将在LogCat中看到清理操作
- 重新启动应用程序。
- 再次退出应用程序。现在,您将看到两组清理日志-第一个代表第一个实例的清理;第二个代表第一个实例的清理。第二集合对应于第二实例。
public class DelayedExitActivity extends Activity {private static final String LOG_TAG = "DelayedExit";private final Runnable longOperation = new Runnable(){ @Override public void run() { for (int i=0 ; i < 50; i++){ Log.d(LOG_TAG, "Iteration "+i); try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }};private Thread longThread ;@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);}@Overrideprotected void onDestroy() { if(longThread == null){ longThread = new Thread(longOperation); } longThread.start(); super.onDestroy();}}



