繁体   English   中英

在活动关闭时如何防止添加片段

[英]How to prevent a Fragment from being added when an Activity is closing

我正在创建一个与Service进行通信的Activity ,以通过POST方法从Internet下载一些数据。 为此,我使用Messenger 这是我的代码,可以让您更加清楚:

我的onCreated()方法:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comments);

    CommentsHandler commentsHandler = new CommentsHandler(this, savedInstanceState);
    Messenger messenger = new Messenger(commentsHandler);

    Intent serviceIntent = new Intent(this, WindowService.class);
    serviceIntent.putExtra("messenger", messenger);
    serviceIntent.putExtra("state", 888);
    serviceIntent.putExtra("number", getIntent().getStringExtra("number"));
    startService(serviceIntent);
}

Service线程中用于通过Messenger对象将结果数据发布到Activity的代码:

    /** ... **/
    Messenger messenger = intent.getParcelableExtra("messenger");
    /** ... **/
    Message resultMsg = this.obtainMessage();
    resultMsg.obj = jParser.getArrayList(); //This is an ArrayList of my downloaded data.
    messenger.send(resultMsg);

Activity用于处理来自ServiceMessage的代码:

public static class CommentsHandler extends Handler {
    Bundle mSavedInstanceState;
    ActionBarActivity activity;

    public CommentsHandler(Activity a, Bundle savedInstanceState) {
        activity = (ActionBarActivity) a;
        mSavedInstanceState = savedInstanceState;
    }

    @Override
    public void handleMessage(Message msg) {
        comments = (ArrayList<HashMap<String, String>>) msg.obj;
        if (mSavedInstanceState == null && msg.arg1 != 793) {
            activity.getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new CommentsFragment()).commit();
        } else if (msg.arg1 == 793) { //793 is my preferred code to determine
                                      //if the internet connection could not be
                                      //established when the Service was trying
                                      //to download the data.
            activity.finish();
        }
    }
}

问题是:如果我在下载数据之前打开Activity并关闭它,则此代码.add(R.id.container, new CommentsFragment()).commit(); 给我一个错误, Can not perform this action after onSaveInstanceState ,因为仅在处理和通过Messenger对象发送我的Service的数据之后才执行此代码,但那时该Activity已被用户关闭,因此无法对Fragment进行操作。添加。 如何解决这个问题? 如何在添加Fragment之前检查Activity是否未关闭/正在关闭? 或者,更好的是,如何停止在ActivityonDestroy()方法上运行该代码的线程,以便在Activity关闭时不执行该线程? 提前致谢!

在您的活动中,您应该创建一个布尔值以检查该活动是否可见:

public ActionBarActivity extends Activity {
  private boolean isActivityVisible = false;

  @Override
  protected void onResume(){
     isActivityVisible = true;
  }

  @Override
  protected void onPause(){
     isActivityVisible = false;
  }

  public boolean isVisible(){
     return this.isActivityVisible;
  }
}

然后修改您的Handler类定义:

public static class CommentsHandler extends Handler {
Bundle mSavedInstanceState;
ActionBarActivity activity;

public CommentsHandler(Activity a, Bundle savedInstanceState) {
    activity = (ActionBarActivity) a;
    mSavedInstanceState = savedInstanceState;
}

@Override
public void handleMessage(Message msg) {
    // here you check if your activity is no longer visible and then break up
    if(activity == null || !activity.isVisible())
        return;

    comments = (ArrayList<HashMap<String, String>>) msg.obj;
    if (mSavedInstanceState == null && msg.arg1 != 793) {
        activity.getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new CommentsFragment()).commit();
    } else if (msg.arg1 == 793) { //793 is my preferred code to determine
                                  //if the internet connection could not be
                                  //established when the Service was trying
                                  //to download the data.
        activity.finish();
    }
}
}

最小的更改是在Activity中具有一个布尔字段,在onResume()中将其设置为true,在onPause() handleMessage()其设置为false,并在handleMessage()检查其值(即,如果标志当前为false,则忽略消息) 。

另一种选择,而不是使用Messenger和handleMessage()用做BroadcastReceiver onResume()注册接收者,并在onPause()注销它。 这样,来自该服务的广播将被简单地忽略。

无论如何,这两种解决方案基本相同,但是广播有些“更高级别”。

假设活动暂停,您对服务的结果不感兴趣。 如果您是(例如,如果您退出应用程序然后再返回,并且需要显示更新),则应该将接收到的数据放在一个字段中,并在随后的onResume()

您执行此操作的方式与我的处理方式不同,但是使用您拥有的内容,我将进行以下调整:

public static class CommentsHandler extends Handler {
    Bundle mSavedInstanceState;
    ActionBarActivity activity;

    public CommentsHandler(Activity a, Bundle savedInstanceState) {
        activity = (ActionBarActivity) a;
        mSavedInstanceState = savedInstanceState;
    }

    public void setActivity(Activity a){
        activity = a;
    }

    @Override
    public void handleMessage(Message msg) {
        if(activity == null){
            return;
        }
        comments = (ArrayList<HashMap<String, String>>) msg.obj;
        if (mSavedInstanceState == null && msg.arg1 != 793) {
            activity.getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new CommentsFragment()).commit();
        } else if (msg.arg1 == 793) { //793 is my preferred code to determine
                                      //if the internet connection could not be
                                      //established when the Service was trying
                                      //to download the data.
            activity.finish();
        }
    }
}

然后,我将使用您的活动onPause()/ onResume()方法来像这样:

@Override
protected void onPause() {
    super.onPause();
    commentsHandler.setActivity(null);  
}

@Override
protected void onResume() {
    super.onResume();
    commentsHandler.setActivity(this);  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM