このコードを使用して作成したいくつかのタブを含む 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;
}
}
タブのアクティビティの 1 つ (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 が開始されるたびに悪化します。