我有一个名为 MyTabActivity 的 TabActivity,其中包含我使用以下代码创建的几个选项卡:
public class MyTabActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.my_tabs);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
Intent intent = new Intent().setClass(this, MyTab1.class);
setupTab(new TextView(this), "Tab1", intent);
intent = new Intent().setClass(this, MyTab2.class);
setupTab(new TextView(this), "Tab2", intent);
intent = new Intent().setClass(this, MyTab3.class);
setupTab(new TextView(this), "Tab3", intent);
}
private void setupTab(final View view, final String tag, Intent intent) {
View tabview = createTabView(tabHost.getContext(), tag);
TabHost.TabSpec setContent = tabHost.newTabSpec(tag).setIndicator(tabview).setContent(intent);
tabHost.addTab(setContent);
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
}
选项卡上的一个活动 (MyTab2) 注册了一个 BroadcastReceiver,以便在特定事件上,选项卡将刷新其显示的数据。我没有在 onPause 中取消注册 BroadcastReceiver,因为我希望此活动能够自行刷新,即使它当前不在前面。
public class MyTab2 extends Activity {
// listener to receive broadcasts from activities that change
// data that this activity needs to refresh on the view
protected class MyListener extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("myapp.REFLECT__CHANGES")) {
//request new data from the server
refreshData();
}
}
}
protected void onResume() {
// if listener is not registered yet, register it
// normally we would unregister the listener onPause, but we want
// the listener to fire even if the activity is not in front
if (!listenerIsRegistered) {
registerReceiver(listener, new IntentFilter("myapp.REFLECT_CHANGES"));
listenerIsRegistered = true;
}
super.onResume();
}
我的问题是,我发现即使在备份到显示 MyTabActivity 之前的活动并第二次启动 MyTabActivity 之后,在第一次进入 MyTabActivity 时创建的 MyTab2 实例似乎仍然存在,当我广播触发选项卡刷新其数据的事件,MyTab2 的旧实例和 MyTab2 的新实例都在刷新,因为它们都接收到广播。我的问题是如何在退出 TabActivity 时杀死 TabActivity 的所有子活动?
子活动的旧实例是否存在,因为当活动离开前台时我没有取消注册 BroadcastReceiver?
可以想象,每次启动后续 MyTabActivity 时,这个问题都会变得复杂。