2个活动 - A发射B - 有时在从B重新启动之前销毁A?

时间:2013-11-25 11:41:35

标签: android android-intent android-activity android-lifecycle

我在活动B中尝试使用此代码重新启动:

intent.setFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
SettingsActivity.this.startActivity(intent);    
finish();

然后onBackPressed()调用一个alertDialog调用:clearBackStack();设置一个标志并再次调用onBackPressed(),因为该标志直接启动super.onBackPressed();

看起来super.onBackPressed()将我发送到活动A所在的旧任务。

我应该怎么做才能从B重启A(只在某些情况下,所以noHistory不会这样做)和API 8 compat?

编辑:当用户只需按回或向上时,我不想重新启动。我想在应用程序收到消息告知其更新时重新启动A.我的错误是要求在返回堆栈时未执行的onCreate()方法中进行更新。我现在把它放在onStart()中。

我最初把它放在onCreate()尽快启动与服务器的连接,因为布局的绘图需要一些时间;现在,当用户启动appli时,此调用将稍后执行。您有关于如何更好地解决这个问题的意见,建议和相关链接吗?

编辑2:忘记“一段时间”,我忘了我已经优化并放置了异步的东西,现在我只需要150 - 200毫秒即可到达onResume()的末尾;因此,在网络连接延迟之前,延迟可以忽略不计。解决了。

1 个答案:

答案 0 :(得分:0)

请查看活动生命周期here。基本上,当您启动活动时,将按特定顺序调用回调方法 - 请参见图表:

enter image description here

所以onCreate()只有在你的活动被破坏时才会被调用,正如你所注意到的那样,当你回到堆栈中时,onStart()被调用了。

此外,将密集型任务(例如连接到服务器)移动到单独的线程中也是一个好主意 - 不要在UI线程上执行此操作。

有几种方法可以执行此操作,请参阅herehere

例如,您可以使用AsyncTask:

  

要使用它,必须将AsyncTask子类化并实现doInBackground()回调方法,该方法在后台线程池中运行。要更新UI,您应该实现onPostExecute(),它从doInBackground()传递结果并在UI线程中运行,因此您可以安全地更新UI。然后,您可以通过从UI线程调用execute()来运行任务。

来自文档的示例代码:

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}