it-swarm.cn

Android:“BadTokenException:无法添加窗口;您的活动是否正在运行?”在PreferenceActivity中显示对话框

我想请求一些帮助:在我的应用程序中,我只有一个活动,一个PreferenceActivity(不需要其他活动,它只是一个简单的后台同步应用程序,所以PrefsActivity是Main/Launcher)。在用户设置首选项之后,检查checkBoxPreference,然后启动(或停止)服务。在开始时,会出现一个对话框。但问题是:如果用户按下(离开活动),再次启动它,然后尝试检查checkBoxPref,则prefsactivity崩溃。对话框没有显示。我不知道为什么,以及如何解决它。

这段代码与那部分完全相同,是什么给了我这个问题:

PrefsActivity.Java:

   package is.it.works;

   // imports .....

   public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
SharedPreferences prefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.prefs);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);
}// onCreate

@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
    if (key.equals("checkTest")) {
        showDialog(1);
    }
    if (key.equals("cancel")) {
        dismissDialog(1);
    }
}// onSPC

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case 1: {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("press back twice, start the app again, and click checkbox...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                prefs.edit().putBoolean("cancel", false).commit();
            }
        });
        return dialog;
    }// case
    }// switch
    return null;
}// onCreateDialog
}// PrefsActivity

的prefs.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:Android="http://schemas.Android.com/apk/res/Android">

    <CheckBoxPreference Android:key="checkTest" Android:title="test" />

</PreferenceScreen>

和清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
package="is.it.works" Android:versionCode="1" Android:versionName="1.0">
<uses-sdk Android:minSdkVersion="4" />

<application Android:icon="@drawable/icon" Android:label="@string/app_name">
    <activity Android:name=".PrefsActivity" Android:label="@string/app_name">
        <intent-filter>
            <action Android:name="Android.intent.action.MAIN" />
            <category Android:name="Android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
</manifest>

LogCat错误:

09-14 10:34:34.472: ERROR/AndroidRuntime(281): Uncaught handler: thread main exiting due to uncaught exception
09-14 10:34:34.502: ERROR/AndroidRuntime(281): Android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running?
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.view.ViewRoot.setView(ViewRoot.Java:456)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.view.WindowManagerImpl.addView(WindowManagerImpl.Java:177)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.view.WindowManagerImpl.addView(WindowManagerImpl.Java:91)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.view.Window$LocalWindowManager.addView(Window.Java:409)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.app.Dialog.show(Dialog.Java:238)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.app.Activity.showDialog(Activity.Java:2413)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at is.it.works.PrefsActivity.onSharedPreferenceChanged(PrefsActivity.Java:27)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.app.ApplicationContext$SharedPreferencesImpl$EditorImpl.commit(ApplicationContext.Java:2727)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.Preference.tryCommit(Preference.Java:1199)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.Preference.persistBoolean(Preference.Java:1404)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.CheckBoxPreference.setChecked(CheckBoxPreference.Java:155)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.CheckBoxPreference.onClick(CheckBoxPreference.Java:143)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.Preference.performClick(Preference.Java:811)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.preference.PreferenceScreen.onItemClick(PreferenceScreen.Java:190)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.widget.AdapterView.performItemClick(AdapterView.Java:284)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.widget.ListView.performItemClick(ListView.Java:3246)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.widget.AbsListView$PerformClick.run(AbsListView.Java:1635)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.os.Handler.handleCallback(Handler.Java:587)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.os.Handler.dispatchMessage(Handler.Java:92)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.os.Looper.loop(Looper.Java:123)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Android.app.ActivityThread.main(ActivityThread.Java:4203)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Java.lang.reflect.Method.invokeNative(Native Method)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at Java.lang.reflect.Method.invoke(Method.Java:521)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:791)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:549)
09-14 10:34:34.502: ERROR/AndroidRuntime(281):     at dalvik.system.NativeStart.main(Native Method)
09-14 10:34:34.522: INFO/Process(52): Sending signal. PID: 281 SIG: 3
09-14 10:34:34.532: INFO/dalvikvm(281): threadid=7: reacting to signal 3
09-14 10:34:34.592: INFO/dalvikvm(281): Wrote stack trace to '/data/anr/traces.txt'
09-14 10:34:38.533: DEBUG/dalvikvm(107): GC freed 437 objects / 21560 bytes in 136ms
09-14 10:34:39.183: INFO/global(175): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
09-14 10:34:44.632: INFO/global(175): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
09-14 10:34:47.412: INFO/Process(281): Sending signal. PID: 281 SIG: 9
09-14 10:34:47.472: INFO/ActivityManager(52): Process is.it.works (pid 281) has died.
09-14 10:34:47.492: INFO/WindowManager(52): WIN DEATH: Window{4394f638 is.it.works/is.it.works.PrefsActivity paused=false} 

经过googleing,我认为,错误的部分是ProgressDialog dialog = new ProgressDialog(this);。原因this更改。但是将其更改为getApplicationContext()PrefsActivity.this没有帮助,问题仍然存在。请告诉我为什么会发生这种情况,可能是什么解决方案!谢谢!我被卡住了,现在我不知道......

55
Lama

我有一个非常相似的问题(让我来到这里)并找到了一个非常简单的解决方案。虽然我的代码不同,但应该很容易适应。这是我的修复:

public void showBox() {
    mActive = true;
    if (! ((Activity) mContext).isFinishing()) {
        mDialogBox.show();
    }
} 

所以,在问题的示例代码中,修复本来是(猜测):

@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
    if (key.equals("checkTest")) {
        if (! this.isFinishing()) {
            showDialog(1);
        }
    }
    if (key.equals("cancel")) {
        dismissDialog(1);
    }
}// onSPC
81
Tigger

也许您没有关闭或取消注册活动中的某些内容。在这种情况下,请尝试在onDestroy上取消注册broadcastreceiver。

4
yoryo

对我来说,这解决了问题..检查对话框是否为空或不显示,如果是,则再次创建。

    // create alert dialog
    if (enableNetworkDialog == null || !enableNetworkDialog.isShowing())
        enableNetworkDialog = alertDialogBuilder.create();
    if (context instanceof AppCompatActivity && !((AppCompatActivity) context).isFinishing())
        enableNetworkDialog.show(); 
1
Amit Tumkur

在将崩溃跟踪引入项目之后,我注意到这个问题频繁出现,并发现整个项目中的相同修复工作可以消除崩溃:

  • 永远不要将Dialog声明/实例化为局部变量。
  • 制作Activity的所有Dialogs实例变量。
  • 覆盖onDestroy并调用if(dialog!= null)dialog.dismiss();

例:

MyActivity extends Activity {
  ProgressDialog mProgressDialog;
  AlertDialog mAlertDialog;


  @Override
  public void onCreate(Bundle savedInstanceState) {
    mProgressDialog = new ProgressDialog(MyActivity.this);
    mAlertDialog = new AlertDialog.Builder(MyActivity.this).show();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if(mProgressDialog != null) {
      mProgressDialog.dismiss();
    }
    if(mAlertDialog != null) {
      mAlertDialog.dismiss();
    }
  }

错误消息显示“无法添加窗口”是误导性的,因为我发现当您离开活动时发生错误并且传递给您的Dialog的上下文已经死亡。

1
Brendan Weinstein

顶级解决方案只能防止崩溃。对我来说问题是我引用了一个错误的context来显示警告对话框。传递正确的context后,问题解决了。

0
TharakaNirmana

这通常是由您的应用尝试使用以前完成的Activity作为上下文显示对话框引起的。然后在显示对话框之前检查活动是否未被某些其他应用程序或其他触发器关闭

if (!isFinishing()) {
    //showdialog here
    }
0
Las Lemieux