gpt4 book ai didi

android - onReceive 异步操作和垃圾回收

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:59 27 4
gpt4 key购买 nike

onReceive 方法中的线程在完成之前是否符合垃圾回收条件?

@Override
public void onReceive(final Context context, Intent intent) {
final int alarmId = intent.getExtras().getInt(EXTRA_ALARM_ID);
Log.i(TAG, "/onReceive with an alarmVo.id of " + alarmId);

// RUN MY THREAD
new Thread(new Runnable() {
@Override
public void run() {
AlarmUtil.setNextAlarm(context, alarmId);
}
}).start();
}

据我了解: http://developer.android.com/reference/android/content/BroadcastReceiver.html是的,但我不太确定。

"anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes. "

如果它被垃圾收集,那么我该如何解决这个问题?我的方法应该是什么?

最佳答案

没有。通过 start() 方法启动但尚未完成的任何 Thread 对象都充当垃圾收集根......在其 run() 方法完成之前,它或它强烈引用的任何东西都没有资格被垃圾收集。

另请参阅这些答案:

编辑:现在您已经为您的问题添加了额外的上下文,事情就更清楚了。问题是这种情况与垃圾收集完全不同。对于静态发布的 BroadcastReceiver(在带有 <receiver> 标记的应用程序 list 中定义),Android 可以在 onReceive(Context, Intent) 之后自由终止其进程。返回。您的异步操作不会因 GC 而停止,它会因 Android 终止托管它的进程而停止。

至于您的方法,这完全取决于您要实现的目标。如果您要在 BroadcastReceiver 中执行的代码可以同步运行,那么这将是最简单的方法。我假设这是不可能的。在这种情况下,this portion的文档似乎适用(强调我的):

Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.

This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.

因此,要么同步运行您的接收器代码,要么使用服务让您的异步操作保持足够长的时间以完成。

(当然,这仅适用于您在其他非 Activity 应用程序中静态注册接收器的情况。如果您从其他 Activity 组件(例如 Activity )中动态注册它,则该组件可以管理您的异步操作. 有关详细信息,请参阅 this answer。)

关于android - onReceive 异步操作和垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6809545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com