如何优先管理多个活动

时间:2013-10-25 10:33:08

标签: java android android-activity

public class MyApplication extends Application {
  ArrayList<Activity> mActivityList = new ArrayList<Activity>();

  public void addActivity(Activity a){

     mActivityList.add(a);
   } 

   public void removeActivity(Activity a){
      for(...){
         ...name equals..
         a.finish();
      }

   }

    public void removeAll(){
       for(){
        ...
        a.finish();
        }
   }

    public Activity getActivity(){...};

}

管理活动是一种非常简单的方法,但mActivityList的堆内存成本很高。那么还有另一种管理活动的方法

1 个答案:

答案 0 :(得分:1)

列表中的跟踪活动绝对不是一个好方法。

如果你这样做的唯一目的是方便地完成所有(或任何)它们,我建议你看一下BroadcastReceiver

以下是您可以在所有活动中添加的代码段:

private BroadcastReceiver finishBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        finish();
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Start listening to any broadcast "tagged" with action name actionFinish.
    LocalBroadcastManager.getInstance(this).registerReceiver(finishBroadcastReceiver,
            new IntentFilter("actionFinish"));
}

@Override
public void onDestroy() {
    super.onDestroy();
    // Stop listening to broadcast when the activity is destroyed.
    LocalBroadcastManager.getInstance(this).unregisterReceiver(finishBroadcastReceiver);
}

每当你想完成所有活动时都这样做:

LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("actionFinish"));

使用Intent.putExtra()来操作Intent对象,以识别您希望处置的Activity,如果不是全部的话。