我的other posting稍有不同
基本上,我在我的Fragment
中有一个消息Handler
,它接收一堆消息,这些消息可能会导致对话框被取消或显示。
当应用程序被放到后台时,我得到了一个onPause
,但仍然可以像预期的那样让我的消息通过。但是,因为我使用的是片段,所以我不能忽略并显示对话框,因为这将导致IllegalStateException
。
我不能就这样驳回或取消州政府的损失。
鉴于我有一个Handler
,我想知道是否有推荐的方法来说明我应该如何在暂停状态下处理消息。
我正在考虑的一种可能的解决方案是,在暂停时录制消息,然后在onResume
上播放它们。这有点不令人满意,我认为框架中一定有一些东西可以更优雅地处理这一问题。
发布于 2011-11-14 22:09:44
尽管Android操作系统似乎没有足够的机制来解决您的问题,但我相信这个模式确实提供了一种相对简单的实现方法。
下面的类是一个围绕android.os.Handler
的包装器,它在活动暂停时缓冲消息,并在恢复时播放它们。
确保只从处理程序中的消息调用您拥有的异步更改片段状态的任何代码(例如,提交、解除)。
从PauseHandler
类派生您的处理程序。
每当您的活动收到onPause()
call PauseHandler.pause()
和onResume()
call PauseHandler.resume()
时。
将您的处理程序handleMessage()
实现替换为processMessage()
。
提供一个始终返回true
的storeMessage()
的简单实现。
/**
* Message Handler class that supports buffering up of messages when the
* activity is paused i.e. in the background.
*/
public abstract class PauseHandler extends Handler {
/**
* Message Queue Buffer
*/
final Vector<Message> messageQueueBuffer = new Vector<Message>();
/**
* Flag indicating the pause state
*/
private boolean paused;
/**
* Resume the handler
*/
final public void resume() {
paused = false;
while (messageQueueBuffer.size() > 0) {
final Message msg = messageQueueBuffer.elementAt(0);
messageQueueBuffer.removeElementAt(0);
sendMessage(msg);
}
}
/**
* Pause the handler
*/
final public void pause() {
paused = true;
}
/**
* Notification that the message is about to be stored as the activity is
* paused. If not handled the message will be saved and replayed when the
* activity resumes.
*
* @param message
* the message which optional can be handled
* @return true if the message is to be stored
*/
protected abstract boolean storeMessage(Message message);
/**
* Notification message to be processed. This will either be directly from
* handleMessage or played back from a saved message when the activity was
* paused.
*
* @param message
* the message to be handled
*/
protected abstract void processMessage(Message message);
/** {@inheritDoc} */
@Override
final public void handleMessage(Message msg) {
if (paused) {
if (storeMessage(msg)) {
Message msgCopy = new Message();
msgCopy.copyFrom(msg);
messageQueueBuffer.add(msgCopy);
}
} else {
processMessage(msg);
}
}
}
下面是如何使用PausedHandler
类的一个简单示例。
在单击按钮时,会向处理程序发送延迟的消息。
当处理程序(在UI线程上)接收到消息时,它会显示一个DialogFragment
。
如果未使用PausedHandler
类,则在按下测试按钮启动对话框后按下home按钮,将显示IllegalStateException。
public class FragmentTestActivity extends Activity {
/**
* Used for "what" parameter to handler messages
*/
final static int MSG_WHAT = ('F' << 16) + ('T' << 8) + 'A';
final static int MSG_SHOW_DIALOG = 1;
int value = 1;
final static class State extends Fragment {
static final String TAG = "State";
/**
* Handler for this activity
*/
public ConcreteTestHandler handler = new ConcreteTestHandler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onResume() {
super.onResume();
handler.setActivity(getActivity());
handler.resume();
}
@Override
public void onPause() {
super.onPause();
handler.pause();
}
public void onDestroy() {
super.onDestroy();
handler.setActivity(null);
}
}
/**
* 2 second delay
*/
final static int DELAY = 2000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState == null) {
final Fragment state = new State();
final FragmentManager fm = getFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
ft.add(state, State.TAG);
ft.commit();
}
final Button button = (Button) findViewById(R.id.popup);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final FragmentManager fm = getFragmentManager();
State fragment = (State) fm.findFragmentByTag(State.TAG);
if (fragment != null) {
// Send a message with a delay onto the message looper
fragment.handler.sendMessageDelayed(
fragment.handler.obtainMessage(MSG_WHAT, MSG_SHOW_DIALOG, value++),
DELAY);
}
}
});
}
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
}
/**
* Simple test dialog fragment
*/
public static class TestDialog extends DialogFragment {
int value;
/**
* Fragment Tag
*/
final static String TAG = "TestDialog";
public TestDialog() {
}
public TestDialog(int value) {
this.value = value;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View inflatedView = inflater.inflate(R.layout.dialog, container, false);
TextView text = (TextView) inflatedView.findViewById(R.id.count);
text.setText(getString(R.string.count, value));
return inflatedView;
}
}
/**
* Message Handler class that supports buffering up of messages when the
* activity is paused i.e. in the background.
*/
static class ConcreteTestHandler extends PauseHandler {
/**
* Activity instance
*/
protected Activity activity;
/**
* Set the activity associated with the handler
*
* @param activity
* the activity to set
*/
final void setActivity(Activity activity) {
this.activity = activity;
}
@Override
final protected boolean storeMessage(Message message) {
// All messages are stored by default
return true;
};
@Override
final protected void processMessage(Message msg) {
final Activity activity = this.activity;
if (activity != null) {
switch (msg.what) {
case MSG_WHAT:
switch (msg.arg1) {
case MSG_SHOW_DIALOG:
final FragmentManager fm = activity.getFragmentManager();
final TestDialog dialog = new TestDialog(msg.arg2);
// We are on the UI thread so display the dialog
// fragment
dialog.show(fm, TestDialog.TAG);
break;
}
break;
}
}
}
}
}
我已经向PausedHandler
类添加了一个storeMessage()
方法,以防即使在活动暂停时也要立即处理任何消息。如果处理了消息,则应返回false,并丢弃该消息。
发布于 2014-08-15 14:49:39
quickdraw优秀的PauseHandler的一个稍微简单一点的版本是
/**
* Message Handler class that supports buffering up of messages when the activity is paused i.e. in the background.
*/
public abstract class PauseHandler extends Handler {
/**
* Message Queue Buffer
*/
private final List<Message> messageQueueBuffer = Collections.synchronizedList(new ArrayList<Message>());
/**
* Flag indicating the pause state
*/
private Activity activity;
/**
* Resume the handler.
*/
public final synchronized void resume(Activity activity) {
this.activity = activity;
while (messageQueueBuffer.size() > 0) {
final Message msg = messageQueueBuffer.get(0);
messageQueueBuffer.remove(0);
sendMessage(msg);
}
}
/**
* Pause the handler.
*/
public final synchronized void pause() {
activity = null;
}
/**
* Store the message if we have been paused, otherwise handle it now.
*
* @param msg Message to handle.
*/
@Override
public final synchronized void handleMessage(Message msg) {
if (activity == null) {
final Message msgCopy = new Message();
msgCopy.copyFrom(msg);
messageQueueBuffer.add(msgCopy);
} else {
processMessage(activity, msg);
}
}
/**
* Notification message to be processed. This will either be directly from
* handleMessage or played back from a saved message when the activity was
* paused.
*
* @param activity Activity owning this Handler that isn't currently paused.
* @param message Message to be handled
*/
protected abstract void processMessage(Activity activity, Message message);
}
它假定您总是想要存储脱机消息以供重播。并将活动作为输入提供给#processMessages
,因此您不需要在子类中管理它。
发布于 2016-10-02 11:14:49
这里有一种略微不同的方法来解决在回调函数中执行片段提交并避免IllegalStateException问题的问题。
首先创建一个自定义的runnable接口。
public interface MyRunnable {
void run(AppCompatActivity context);
}
接下来,创建一个用于处理MyRunnable对象的片段。如果MyRunnable对象是在活动暂停之后创建的,例如,如果屏幕旋转,或用户按下主页按钮,则将其放入队列中,以便稍后使用新的上下文进行处理。由于setRetain实例设置为true,因此队列在任何配置更改后仍然有效。runProtected方法在UI线程上运行,以避免出现带有isPaused标志的争用条件。
public class PauseHandlerFragment extends Fragment {
private AppCompatActivity context;
private boolean isPaused = true;
private Vector<MyRunnable> buffer = new Vector<>();
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = (AppCompatActivity)context;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onPause() {
isPaused = true;
super.onPause();
}
@Override
public void onResume() {
isPaused = false;
playback();
super.onResume();
}
private void playback() {
while (buffer.size() > 0) {
final MyRunnable runnable = buffer.elementAt(0);
buffer.removeElementAt(0);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//execute run block, providing new context, incase
//Android re-creates the parent activity
runnable.run(context);
}
});
}
}
public final void runProtected(final MyRunnable runnable) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if(isPaused) {
buffer.add(runnable);
} else {
runnable.run(context);
}
}
});
}
}
最后,该片段可以在主应用中使用,如下所示:
public class SomeActivity extends AppCompatActivity implements SomeListener {
PauseHandlerFragment mPauseHandlerFragment;
static class Storyboard {
public static String PAUSE_HANDLER_FRAGMENT_TAG = "phft";
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
//register pause handler
FragmentManager fm = getSupportFragmentManager();
mPauseHandlerFragment = (PauseHandlerFragment) fm.
findFragmentByTag(Storyboard.PAUSE_HANDLER_FRAGMENT_TAG);
if(mPauseHandlerFragment == null) {
mPauseHandlerFragment = new PauseHandlerFragment();
fm.beginTransaction()
.add(mPauseHandlerFragment, Storyboard.PAUSE_HANDLER_FRAGMENT_TAG)
.commit();
}
}
// part of SomeListener interface
public void OnCallback(final String data) {
mPauseHandlerFragment.runProtected(new MyRunnable() {
@Override
public void run(AppCompatActivity context) {
//this block of code should be protected from IllegalStateException
FragmentManager fm = context.getSupportFragmentManager();
...
}
});
}
}
https://stackoverflow.com/questions/8040280
复制相似问题