The error message "Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?" typically occurs when attempting to show a dialog or create a window in an activity that is no longer active or has been destroyed.

To resolve this issue, you can try the following:

  1. Check if the activity is still running: Make sure that the activity is not finishing or has not been destroyed before attempting to show the dialog. You can use the isFinishing() method to check the activity's status.

  2. Use the correct context: Ensure that you are using the correct context when creating or showing the dialog. You should use the activity's context instead of the application context in most cases. You can use YourActivity.this or getActivity() (if you are in a fragment) to get the correct context.

  3. Handle configuration changes: If the error occurs during a configuration change, such as screen rotation, you can try handling the configuration changes manually by adding android:configChanges="orientation|screenSize" to your activity's declaration in the manifest file. This will prevent the activity from being recreated during configuration changes.

  4. Delay the dialog creation: If the error occurs during an asynchronous operation, such as a background task, try delaying the creation or showing of the dialog until the activity is fully resumed. You can use Handler or postDelayed() to delay the execution of code.

  5. Check for any other related issues: Review your code and make sure there are no other issues that may cause the activity to be destroyed or the context to become invalid.

By following these steps, you should be able to resolve the "Unable to add window -- token null is not valid; is your activity running?" error

Caused by androidviewWindowManager$BadTokenException Unable to add window -- token null is not valid; is your activity running

原文地址: https://www.cveoy.top/t/topic/hCA6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录