简体   繁体   English

活动处于活动状态时的Android后台操作

[英]Android background operation while activity is active

So this is my theory - when creating a background thread on activity creation, with a callback that references by the activity, if activity closed, it stays in memory because of the hard reference of the callback, am I right? 所以这是我的理论 - 当在活动创建时创建一个后台线程时,有一个由活动引用的回调,如果活动关闭,它会因为回调的硬引用而留在内存中,我是对的吗? So how can I make sure the background operation stop's it's execution when activity closed? 那么,如何在活动结束时确保后台操作停止执行?

让你的Activity实现onStop()并在那时杀死你的后台任务。

Do you want onStop() or onDestroy() ? 你想要onStop()还是onDestroy()

Navigating away from the Activity, such as clicking a list item or starting a subactivity will trigger onPause() , then onStop() when the activity is fully invisible. 导航离开活动,例如单击列表项或启动子活动将触发onPause() ,然后在活动完全不可见时触发onStop() If memory is your concern, you should look into implementing it in onDestroy() and/or use a Weak/SoftReference in the background operation to prevent leakage. 如果你担心内存,你应该考虑在onDestroy()实现它和/或在后台操作中使用Weak / SoftReference以防止泄漏。

When an Activity is finished, android sets all its view references to null and then the Activity reference is set to null. 当Activity完成后,android将其所有视图引用设置为null,然后将Activity引用设置为null。 Also, Android assumes that the threads started by the Activity could be killed with no problems. 此外,Android假定活动启动的线程可以被杀死而没有任何问题。 So, the threads would get killed but the time is not defined. 因此,线程被杀死,但时间没有定义。 In you situation a callback wont matter as all the references would be set to null. 在您的情况下,回调不重要,因为所有引用都将设置为null。 Ther would be nobody to listen to callback. 没有人可以听回叫。

The easiest to kill your threads yourself is to keep the code execution of the thread in a loop.You can have a volatile boolean parameter that is checked on every loop of your thread: 最容易自己杀死线程的方法是将线程的代码执行保持在循环中。你可以在线程的每个循环上检查一个volatile布尔参数:

while (!threadStop) {
    // Do stuff
}

In onDestroy(), make this variable as true 在onDestroy()中,将此变量设为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM