【发布时间】:2019-03-19 12:40:29
【问题描述】:
我有一个包含片段的活动,这个片段使用 android youtube api 播放 youtube 视频,我在 youtube 视频完成时为它注册了一个事件侦听器。
在onVideoEnded 事件中,我获得了对活动的引用以执行某些操作,这就是我在片段中获取活动的方式:
private Activity theActivity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
theActivity = (Activity) context;
}
/*
* Deprecated on API 23
* Use onAttachToContext instead
*/
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < 23) {
theActivity = activity;
}
}
@Override
public void onDetach() {
super.onDetach();
theActivity = null;
}
protected Activity getTheActivity() {
Activity activity = getActivity();
if (activity != null)
return activity;
else return this.theActivity;
}
正如您在我的getTheActivity 方法中看到的,我首先检查getActivity 方法,如果它返回空值,我会在创建片段时从onAttach 获得变量。
然而,在像三星 getTheActivity 这样的设备上,方法仍然返回 null !
我认为这可能是一个内存不足的问题!
在任何情况下,如何从我的片段中获取对我的活动的引用?
【问题讨论】:
-
此时活动是否可见?还是您在谈论一些边缘情况?
-
@azizbekian 我真的不知道,因为我从 crashlytics 得到这些报告!
-
当用户将活动移到后台时,可能已经调用了回调。您无法保证托管活动的实例届时会存在。
-
我认为如果用户将活动移到后台它会被破坏,因为我在我的清单中使用 android:noHistory="true" @azizbekian
-
if the user moved the activity into the background it would have been destroyed不太正确。如果系统决定终止进程,活动将被销毁。当用户离开应用程序时,你会暂停你的 youtube 视频吗?
标签: android android-fragments memory android-activity low-memory