I have a TabActivity called MyTabActivity containing several tabs that I create using this code:
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;
}
}
One of the activities on a tab (MyTab2) registers a BroadcastReceiver so that on a specific event, the tab will refresh its displayed data. I am not unregistering the BroadcastReceiver in onPause, because I want this activity to refresh itself even if it is not currently in front.
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();
}
My problem is that I am finding that even after backing up to the activity that preceded the display of MyTabActivity and starting MyTabActivity a second time, that the instance of MyTab2 that was created on the first entrance into MyTabActivity seems to still be alive and when I broadcast the event that triggers the tab to refresh its data, that both the old instance of MyTab2 and the new instance of MyTab2 are refreshing because both receive the broadcast. My question is how can I kill all child activities of the TabActivity when backing out of the TabActivity?
Are the old instances of child activities staying around because I am not unregistering the BroadcastReceiver when the activity leaves the front?
As you can imagine, this problem is compounded each time a subsequent MyTabActivity is started.