我正在显示从AsyncTask到Fragment的错误消息,但是当我的应用程序在后台运行时,应用程序崩溃了。
代码如下:
import android.support.v4.app.FragmentManager;
public class AppUtil {
public static void showErrorDialog(FragmentManager fm, int messageResourceId) {
if (fm != null && !fm.isDestroyed()) {
InfoDialogFragment.newInstance("", messageResourceId).show(fm, "ERROR");
}
}
public static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
}
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment implements ILoginable,
View.OnClickListener {
private ProgressDialog pd ;
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank,
container, false);
rootView.findViewById(R.id.pressBT).setOnClickListener(this);
return rootView;
}
@Override
public void starProgress(int messageId) {
if (pd == null) {
pd = new ProgressDialog(getContext(), R.string.loading);
pd.show();
}
}
@Override
public void endProgress() {
if(pd != null && isAdded()) {
pd.dismiss();
pd = null;
}
}
@Override
public void displayError(int messageId) {
if (isAdded()) {
AppUtil.showErrorDialog(getFragmentManager(), R.string.app_name);
}
}
@Override
public void loginResult(boolean success) {
}
@Override
public void onClick(View v) {
if (R.id.pressBT == v.getId()) {
new LoginAsyncTask(this).execute("x");
}
}
}
public interface ILoginable {
void starProgress(int messageId);
void endProgress();
void displayError(int messageId);
void loginResult(boolean success);
}
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
public class LoginAsyncTask extends AsyncTask<String, Void, String> {
private WeakReference<ILoginable> reference;
public LoginAsyncTask(ILoginable iLoginable) {
reference = new WeakReference<>(iLoginable);
}
@Override
protected void onPreExecute() {
reference.get().starProgress(R.string.loading);
}
@Override
protected String doInBackground(String... strings) {
return "xx";
}
@Override
protected void onPostExecute(String s) {
if (reference.get() != null) {
reference.get().endProgress();
reference.get().displayError(R.string.hello_blank_fragment);
}
reference.clear();
}
}
如您所见,这是基本asyncTask的简单行为。但是,我无法弄清楚为什么当应用程序在后台运行时,i Exclusive方法会返回true,以及为什么应用程序崩溃并显示以下消息:
*** Process: com.roscasend.android.testadd, PID: 2891
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:2053)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2079)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:678)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:632)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
at com.roscasend.android.testadd.AppUtil.showErrorDialog(AppUtil.java:17)
at com.roscasend.android.testadd.BlankFragment.displayError(BlankFragment.java:51)
at com.roscasend.android.testadd.LoginAsyncTask.onPostExecute(LoginAsyncTask.java:37)
at com.roscasend.android.testadd.LoginAsyncTask.onPostExecute(LoginAsyncTask.java:15)***
最好的问候, 奥雷利亚
答案 0 :(得分:2)
即使您的应用程序在后台,该片段也始终会附加,我认为您可以使用isVisible(),如果该片段当前对用户可见,则返回true。因此,如果该片段可见,则显示对话框
答案 1 :(得分:2)
IllegalStateException: Can not perform this action after onSaveInstanceState
Android FragmentManager使用savedInstanceState
捆绑软件来跟踪当前向用户显示的片段。如果保存状态并且您尝试执行片段事务,则系统崩溃,因为用户将永远不会看到该事务。
较新版本的支持库在FragmentManager上提供了一种isStateSaved()
方法,您可以使用该方法检查您是否在安全窗口中以显示对话框。
@Override
public void displayError(int messageId) {
FragmentManager fm = getFragmentManager();
if (!fm.isStateSaved()) {
AppUtil.showErrorDialog(fm, R.string.app_name);
}
}
但是,这仍然给您带来问题。如果您的AsyncTask完成并在状态保存后尝试显示错误,则用户将永远不会看到错误。
您可以让应用程序记录它已 尝试显示错误,然后还可以在应用恢复时执行检查以查看它现在是否应该显示错误。我们需要一个地方来保存试图显示对话框的信息,它不能只是活动/片段上的boolean
(因为这将导致相同的状态保存问题)。我建议使用SharedPreferences
来存储信息。
将此代码添加到您的片段中:
private static final String SHOW_DIALOG = "SHOW_DIALOG";
private SharedPreferences getSharedPreferences() {
return getActivity().getPreferences(Context.MODE_PRIVATE);
}
然后使用此代码显示对话框:
@Override
public void displayError(int messageId) {
FragmentManager fm = getFragmentManager();
if (!fm.isStateSaved()) {
AppUtil.showErrorDialog(getFragmentManager(), R.string.app_name);
} else {
getSharedPreferences()
.edit()
.putBoolean(SHOW_DIALOG, true)
.apply();
}
}
此代码可在应用恢复时显示对话框:
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = getSharedPreferences();
boolean triedToShowInBackground = prefs.getBoolean(SHOW_DIALOG, false);
if (triedToShowInBackground) {
AppUtil.showErrorDialog(getFragmentManager(), R.string.app_name);
prefs.edit().remove(SHOW_DIALOG).apply();
}
}
答案 2 :(得分:0)
如果尝试使用FragmentDialog
而不是commitAllowingStateLoss()
显示commit()
,则问题得到解决。要模仿父show
方法并设置内部字段,我们必须使用反射。您可以在show
类中重写InfoDialogFragment
方法,如下所示:
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import java.lang.reflect.Field;
public class InfoDialogFragment extends DialogFragment {
@Override
public void show(FragmentManager manager, String tag) {
try {
Field mDismissedField = DialogFragment.class.getField("mDismissed");
mDismissedField.setAccessible(true);
mDismissedField.setBoolean(this, false);
Field mShownByMeField = DialogFragment.class.getField("mShownByMe");
mShownByMeField.setAccessible(true);
mShownByMeField.setBoolean(this, true);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
// Other parts of code ...
}
答案 3 :(得分:0)
尝试将其添加到片段中
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && isResumed())
onResume();
}
@Override
public void onResume() {
super.onResume();
if(!getUserVisibleHint()){
return;
}
// Populate UI
}