Error : BinderProxy#45d459c0 is not valid; is your activity running? - android
What is this error... i haven't found any discussion on this error in the stackoverflow community Detailed :-
10-18 23:53:11.613: ERROR/AndroidRuntime(3197): Uncaught handler: thread main exiting due to uncaught exception
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#45d459c0 is not valid; is your activity running?
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.ViewRoot.setView(ViewRoot.java:468)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.app.Dialog.show(Dialog.java:239)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.vishal.contacte.Locationlistener$MyLocationListener.onLocationChanged(Locationlistener.java:86)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:179)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:112)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:128)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.os.Handler.dispatchMessage(Handler.java:99)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.os.Looper.loop(Looper.java:123)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at android.app.ActivityThread.main(ActivityThread.java:4363)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
10-18 23:53:11.658: ERROR/AndroidRuntime(3197): at dalvik.system.NativeStart.main(Native Method)
This is most likely happening because you are trying to show a dialog after execution of a background thread, while the Activity is being destroyed.
I was seeing this error reported once in a while from some of my apps when the activity calling the dialog was finishing for some reason or another when it tried to show a dialog. Here's what solved it for me:
if(!((Activity) context).isFinishing())
{
//show dialog
}
I've been using this to work around the issue on older versions of Android for several years now, and haven't seen the crash since.
2021 Update
It's been noted in some of the comments that it's bad to blindly cast Context to an Activity. I agree!
When I'm writing similar code these days in a Fragment (8+ years after the original answer was provided), I do it more like this:
if (!requireActivity().isFinishing) {
// show dialog
}
The main takeaway is that trying to show a dialog or update any UI after the hosting Activity has been killed will result in a crash. Do what you can to prevent that by killing your background threads when your Activity is killed, or at a minimum, use the answer here to stop your app from crashing.
I faced the same problem and used the code proposed by DiscDev above with minor changes as follows:
if (!MainActivity.this.isFinishing()){
alertDialog.show();
}
if dialog is trowing this problem because of the thread you should do run this on UI thread like that :-
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.show();
}
});
This error occurs when you are showing the dialog for a context that no longer exists.
Before calling .show() check that activity/context is not finishing
if (!(context instanceof Activity && ((Activity) context).isFinishing())) {
alert.show();
}
I encountered this error when I had a countDownTimer in my app. It had a method calling GameOver in my app as
public void onFinish() {
GameOver();
}
but actually the game could be over before the time was up due to a wrong click of the user (it was a clicking game). So when I was looking at the Game Over dialog after e.g. 20 seconds, I forgot to cancel the countDownTimer so once the time was up, the dialog appeared again. Or crashed with the above error for some reason.
The fix to this is pretty simple. Just test if the Activity is going through its finishing phase before displaying the Dialog:
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DISPLAY_DLG:
if (!isFinishing()) {
showDialog(MY_DIALOG);
}
break;
}
}
};
see more here
In my case, the problem was that Context was kept as a weak reference in the class that extends Handler. Then I was passing Messenger, that wraps the handler, through an Intent to a Service. I was doing this each time the activity appeared on screen in onResume() method.
So as you understand, Messenger was serialized together with its fields (including context), because it is the only way to pass objects using Intent - to serialize them. At that moment when Messenger was passed to the service, the activity itself still wasn't ready for showing dialogs as it is in another state (being said onResume(), that is absolutely different from when the activity is already on the screen). So when messenger was deserialized, the context still was at the resuming state, while the activity actually was already on the screen. Moreover, deserialization allocates memory for new object, that is completely different from the original one.
The solution is just to bind to the service each time you need it and return a binder that has a method like 'setMessenger(Messenger messenger)' and call it, when you are binded to the service.
I solve this problem by using WeakReference<Activity> as a context. The crash never appeared again. Here is a sample code in Kotlin:
Dialog manager class:
class DialogManager {
fun showAlertDialog(weakActivity: WeakReference<Activity>) {
val wActivity = weakActivity.get()
wActivity?.let {
val builder = AlertDialog.Builder(wActivity, R.style.MyDialogTheme)
val inflater = wActivity.layoutInflater
val dialogView = inflater.inflate(R.layout.alert_dialog_info, null)
builder.setView(dialogView)
// Set your dialog properties here. E.g. builder.setTitle("MyTitle")
builder.create().show()
}
}
}
And you show the dialog like this:
val dialogManager = DialogManager()
dialogManager.showAlertDialog(WeakReference<Activity>(this#MainActivity))
If you want to be super-duper protected from crashes. Instead of builder.create().show() use:
val dialog = builder.create()
safeShow(weakActivity, dialog)
This is the safeShow method:
private fun safeShow(weakActivity: WeakReference<Activity>, dialog: AlertDialog?) {
val wActivity = weakActivity.get()
if (null != dialog && null != wActivity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!dialog.isShowing && !(wActivity).isFinishing && !wActivity.isDestroyed) {
try {
dialog.show()
} catch (e: Exception) {
//Log exception
}
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!dialog.isShowing && !(wActivity).isFinishing) {
try {
dialog.show()
} catch (e: Exception) {
//Log exception
}
}
}
}
}
This is a similar method that you could use for safe dismissing the dialog:
private fun safeDismissAlertDialog(weakActivity: WeakReference<Activity>, dialog: AlertDialog?) {
val wActivity = weakActivity.get()
if (null != dialog && null != wActivity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (dialog.isShowing && !wActivity.isFinishing && !wActivity.isDestroyed) {
try {
dialog.dismiss()
} catch (e: Exception) {
//Log exception
}
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!dialog.isShowing && !(wActivity).isFinishing) {
try {
dialog.dismiss()
} catch (e: Exception) {
//Log exception
}
}
}
}
}
In Kotlin
if (!(context is Activity && context.isFinishing)) {
pausingDialog!!.show()
}
how about makes a new Instance of that dialog you want to call? I've actually just met the same problem, and that is what I do. so rather than :
if(!((Activity) context).isFinishing())
{
//show dialog
}
how about this?
YourDialog mDialog = new YourDialog();
mDialog1.show(((AppCompatActivity) mContext).getSupportFragmentManager(), "OrderbookDialog");
}
so rather than just checking is it safe or not to show the dialog, I think it's much more safe if we just create a new instance to show the dialog.
Like me, In my case I tried to create one instance (from a Fragment onCreate) and call the instance of those dialog in another content of adapterList and this will result in "is your activity running"- error. I thought that was because I just create one instance (from onCreate) and then it is get destroyed, so when I tried to call it from another adapterList I calling the dialog from old instance.
I am not sure if my solution is memory friendly or not, because I haven't tried to profile it, but it works
(well surely, it is safe if you do not create too many instance)
Related
GDPR Consent form crashing: WindowManager BadTokenException
I am showing Google's GDPR consent form and I am noticing a lot of these reports: Fatal Exception: android.view.WindowManager$BadTokenException Unable to add window -- token android.os.BinderProxy#38734f2 is not valid; is your activity running? com.my.project.MainActivity$4.onConsentFormLoaded As context I use MainActivity.this: private void displayConsentForm() { consentForm = new ConsentForm.Builder(MainActivity.this, GeneralUtils.getAppsPrivacyPolicy()) .withListener(new ConsentFormListener() { #Override public void onConsentFormLoaded() { consentForm.show(); // crashing here for some users } #Override public void onConsentFormOpened() { } #Override public void onConsentFormClosed( ConsentStatus consentStatus, Boolean userPrefersAdFree) { if(userPrefersAdFree) { ConsentInformation.getInstance(MainActivity.this) .setConsentStatus(NON_PERSONALIZED); } else { ConsentInformation.getInstance(MainActivity.this) .setConsentStatus(consentStatus); } initAds(); } #Override public void onConsentFormError(String errorDescription) { Log.e("Error",errorDescription); } }) .withPersonalizedAdsOption() .withNonPersonalizedAdsOption() .withAdFreeOption() .build(); consentForm.load(); } Here is additional Firebase crash report: Why is this happening and how to prevent it? I am not sure what additional check to put before consentForm.show() and I can not reproduce the issue. Maybe it would suffice if I put this check before showing the form: if(!MainActivity.this.isFinishing() && !MainActivity.this.isDestroyed()) ?
The easiest way around this would be to just put a try-catch block around consentForm.show() and catch the BadTokenException. It's not really clean, but it's likely that this is happening when the Activity finishes (maybe the user closes the app from Recents right as the Dialog is loading). If this were my project, I'd first try adding that if statement you have (although you don't need the MainActivity.this. part; you can just call isFinishing() and isDestroyed() directly). Since you're referencing an Activity Context, this should take care of it. However, if it still crashes, you should first look into reproducing it. Try getting to just before displayConsentForm() is called, then closing the app from Recents. Play around with the timing and you'll probably reproduce the crash. If not, then just add the try-catch. The Activity isn't displayed, since it's throwing that error, so the user isn't actually in the app.
In AlertDialog - Unable to add window -- token null is not valid; is your activity running?
I have created a custom notifcation control using AlertDialog which will displays at the Top. It works fine for some devices like Samsung Galaxy S7,S8 where it is running with Android 7.0 OS. However It doesn't works on some mobile devices with same OS running. It is throwing "Unable to add window -- token null is not valid; is your activity running?" in Show Method. Any help would be really appreciated. The below is the code snippit. The syntax is xamarin. However the logics are same as native android. public class MyNotificationControl { AlertDialog b; public MyNotificationControl(Android.Content.Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(Android.App.Application.Context); LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); View dialogView = inflater.Inflate(Resource.Layout.mynotification_layout, null); builder.SetView(dialogView); b = builder.Create(); b.Window.SetType(WindowManagerTypes.Toast); Window window = b.Window; window.SetFlags(WindowManagerFlags.NotTouchModal, WindowManagerFlags.NotTouchModal); window.ClearFlags(WindowManagerFlags.DimBehind); window.SetGravity(GravityFlags.Top); window.SetBackgroundDrawableResource(Android.Resource.Color.Transparent); } public void Show() { try { b.Show(); } catch(Exception ex) { //Here is my exception occurs. Unable to add window -- token null is not valid; is your activity running? } } public void Close() { b?.Dismiss(); } }
Pass the current activity context instead Application context in AlertDialog.Builder(). Set the AlertDialog type to WindowManagerTypes.ApplicationPanel intead of Toast AlertDialog.Builder builder = new AlertDialog.Builder(context);//current activity. b.Window.SetType(WindowManagerTypes.ApplicationPanel);
Please refer to this. This exception occurred while app was trying to notify user from the background thread by opening a Dialog. Do like this: RunOnUiThread(() => { if (!IsFinishing) { //to call the show method } }); Or you can refer to this.
for fragment just use AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
Opencv stopped working on Android 6.0
I am using Opencv on my application and it works fine with Android 4.3 but it doesn't even open with Android 6.0. I looked up for a solution on SO, and found one that says to set the package name. So I did it. Follow code: public static boolean initOpenCV(String Version, final Context AppContext, final LoaderCallbackInterface Callback) { AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback); Intent intent = new Intent("org.opencv.engine.BIND"); intent.setPackage("org.opencv.engine"); if (AppContext.bindService(intent, helper.mServiceConnection, Context.BIND_AUTO_CREATE)) { return true; } else { AppContext.unbindService(helper.mServiceConnection); InstallService(AppContext, Callback); return false; } } But now I am getting the following error: 11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.ViewRootImpl.setView(ViewRootImpl.java:571) 11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310) 11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85) 11-18 10:14:43.447 24901-24930/br.com.ibramed.dermos E/AndroidRuntime: at android.app.Dialog.show(Dialog.java:319) in the following code: case InstallCallbackInterface.NEW_INSTALLATION: { Looper.prepare(); Log.d("Debug", ""+mAppContext); AlertDialog InstallMessage = new AlertDialog.Builder(mAppContext).create(); InstallMessage.setTitle("Package not found"); InstallMessage.setMessage(callback.getPackageName() + " package was not found! Try to install it?"); InstallMessage.setCancelable(false); // This blocks the 'BACK' button InstallMessage.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.install(); } }); InstallMessage.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { callback.cancel(); } }); InstallMessage.show(); } break; I have searched and found some people saying to keep track of the main Context, because Threads doesn't have context. But my app already does this and use the main context to create the AlertDialogs and it still doesn't work. The error is when the app show the AlertDialog. I really don't know what else to do. Can someone help?
As far as I know in service or Aplication class you cant get context with View for android 6.0, so when OpenCv tries to show AlertDialog it does not know to what activity bind dialog and crashes. Try to init OpenCv in Activity onCreate method before usage. My working init method in MainActivity (code on kotlin): override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, object : BaseLoaderCallback(this#HistoryActivity) { override fun onManagerConnected(status: Int) { if (LoaderCallbackInterface.SUCCESS == status) Log.i(TAG, "OpenCV was loaded") else super.onManagerConnected(status) } }) }
How to resolve : android.view.WindowManager$BadTokenException - is your activity running?
I have an activity with lot of Dialogs for ex Dialog_1, Dialog_2, Dialog_3, I have implemented a WebView in one of the Dialogs lets say Dialog_2. When navigate through the Dialog's, first time the Dialog_2 with the WebView opens with no problem, but second time when I navigate to Dialog_3 and come back to Dialog_2 OR Dialog_1 to Dialog_2 and touch the WebView I get an error as mentioned bellow. I have looked at Bad token exception but it does not work still using if (! this.isFinishing()) { showDialog(DIALOG_ADD_A_PERSON_BODY_MAP) } FATAL EXCEPTION: main android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running? FATAL EXCEPTION: main android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:806) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73) at android.widget.ZoomButtonsController.setVisible(ZoomButtonsController.java:373) at android.webkit.ZoomControlEmbedded.show(ZoomControlEmbedded.java:41) at android.webkit.ZoomManager.invokeZoomPicker(ZoomManager.java:1728) at android.webkit.WebViewClassic.startDrag(WebViewClassic.java:11645) at android.webkit.WebViewClassic.handleTouchEventCommon(WebViewClassic.java:11170) at android.webkit.WebViewClassic.onHandleUiTouchEvent(WebViewClassic.java:3225) at android.webkit.WebViewClassic.onHandleUiEvent(WebViewClassic.java:3135) at android.webkit.WebViewClassic.access$12000(WebViewClassic.java:278) at android.webkit.WebViewClassic$PrivateHandler.dispatchUiEvent(WebViewClassic.java:13405) at android.webkit.WebViewInputDispatcher.dispatchUiEvent(WebViewInputDispatcher.java:1078) at android.webkit.WebViewInputDispatcher.dispatchUiEvents(WebViewInputDispatcher.java:1066) at android.webkit.WebViewInputDispatcher.access$300(WebViewInputDispatcher.java:78) at android.webkit.WebViewInputDispatcher$UiHandler.handleMessage(WebViewInputDispatcher.java:1392) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5365) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method) The Dialog code is case DIALOG_ADD_A_PERSON_BODY_MAP: try { LayoutInflater inflaterBodyMap = this .getLayoutInflater(); final View inflatorBodyMap = inflaterBodyMap .inflate( R.layout.dialog_incident_window_body_map, null); bodyMapWebView = (WebView) inflatorBodyMap.findViewById(R.id.webView); bodyMapWebView.getSettings().setJavaScriptEnabled(true); //bodyMapWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH); //bodyMapWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); bodyMapWebView.getSettings().setBuiltInZoomControls(true); bodyMapWebView.getSettings().setSupportZoom(true); bodyMapWebView.loadUrl("https://www.google.co.uk"); bodyMapWebView.addJavascriptInterface(new WebAppInterface(this), "Android"); builder.setTitle("Injured person"); builder.setView(inflatorBodyMap); builder.setPositiveButton("Next", new DialogInterface.OnClickListener() { #Override public void onClick(DialogInterface dialog, int which) { showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED_ET); wasThePersonInjured.setText(map_incident_addAPerson.get("InjuredNotes")); } }); builder.setNegativeButton("Back", new DialogInterface.OnClickListener() { #Override public void onClick(DialogInterface dialog, int which) { showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED); } }); return builder.create(); } catch (Exception e) { e.printStackTrace(); } How do I resolve this error. Your help and suggestions much appreciated.
This happens if your Activity has been killed due to some reason and window token of your activity has expired but you try and access it anyways. So to solve this put this in onPause: #Override protected void onPause() { super.onPause(); if ((progress != null) && progress.isShowing()) { progress.dismiss(); } progress = null; }
Problems creating a Popup Window in Android Activity
I'm trying to create a popup window that only appears the first time the application starts. I want it to display some text and have a button to close the popup. However, I'm having troubles getting the PopupWindow to even work. I've tried two different ways of doing it: First I have an XML file which declares the layout of the popup called popup.xml (a textview inside a linearlayout) and I've added this in the OnCreate() of my main Activity: PopupWindow pw = new PopupWindow(findViewById(R.id.popup), 100, 100, true); pw.showAtLocation(findViewById(R.id.main), Gravity.CENTER, 0, 0); Second I did the exact same with this code: final LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.layout.main) ), 100, 100, true); pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0); The first throws a NullPointerException and the second throws a BadTokenException and says "Unable to add window -- token null is not valid" What in the world am I doing wrong? I'm extremely novice so please bear with me.
To avoid BadTokenException, you need to defer showing the popup until after all the lifecycle methods are called (-> activity window is displayed): findViewById(R.id.main_page_layout).post(new Runnable() { public void run() { pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0); } });
Solution provided by Kordzik will not work if you launch 2 activities consecutively: startActivity(ActivityWithPopup.class); startActivity(ActivityThatShouldBeAboveTheActivivtyWithPopup.class); If you add popup that way in a case like this, you will get the same crash because ActivityWithPopup won't be attached to Window in this case. More universal solusion is onAttachedToWindow and onDetachedFromWindow. And also there is no need for postDelayed(Runnable, 100). Because this 100 millis does not guaranties anything #Override public void onAttachedToWindow() { super.onAttachedToWindow(); Log.d(TAG, "onAttachedToWindow"); showPopup(); } #Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); Log.d(TAG, "onDetachedFromWindow"); popup.dismiss(); }
The accepted answer did not work for me. I still received BadTokenException. So I just called the Runnable from a Handler with delay as such: new Handler().postDelayed(new Runnable() { public void run() { showPopup(); } }, 100);
use class Context eg. MainActivity.this instead of getApplicationContext()
There are two scenarios when this exception could occur. One is mentioned by kordzik. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/ Make sure you handle both of them
the solution is to set the spinner mode to dialog as below: android:spinnerMode="dialog" or Spinner(Context context, int mode) tnxs RamallahDroid See This.
Depending on the use case, for types of pop-up to display a message, setting the pop-up type to TYPE_TOAST using setWindowLayoutType() avoids the issue, as this type of pop-up is not dependent on the underlying activity. Edit: One of the side effects: no interaction in the popup window for API <= 18, as the touchable / focusable events would be removed by the system. ( http://www.jianshu.com/p/634cd056b90c ) I end up with using TYPE_PHONE (as the app happens to have the permission SYSTEM_ALERT_WINDOW, otherwise this won't work too).
You can check the rootview if it has the token. You can get the parent layout defined from your activity xml, mRootView if (mRootView != null && mRootView.getWindowToken() != null) { popupWindow.showAtLocation(); }
Check that findViewById returns something - you might be calling it too early, before the layout is built Also you may want to post logcat output for the exceptions you're getting
You can also try to use this check: public void showPopupProgress (){ new Handler().post(new Runnable() { #Override public void run() { if (getWindow().getDecorView().getWindowVisibility() == View.GONE) { showPopupProgress(); return; } popup.showAtLocation(.....); } }); }
If you show a PopupWindow in another PopupWindow, do not use the view in first POP, use the origin parent view. pop.showAtLocation(parentView, ... );
I had the same problem (BadTokenException) with AlertDialog on dialog.show(). I was making an AlertDialog by following some example. In my case the reason of that problem was a string dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST) Everything became working after I removed it.
Maybe it's time for a newer solution. This methods checks 5 times every 50ms if the parent view for the PopupWindow has a token. I use it inside my customized PopupWindow. private fun tryToShowTooltip(tooltipLayout: View) { Flowable.fromCallable { parentView.windowToken != null } .map { hasWindowToken -> if (hasWindowToken) { return#map hasWindowToken } throw RetryException() } .retryWhen { errors: Flowable<Throwable> -> errors.zipWith( Flowable.range(1, RETRY_COUNT), BiFunction<Throwable, Int, Int> { error: Throwable, retryCount: Int -> if (retryCount >= RETRY_COUNT) { throw error } else { retryCount } }) .flatMap { retryCount: Int -> Flowable.timer(retryCount * MIN_TIME_OUT_MS, TimeUnit.MILLISECONDS) } } .onErrorReturn { false } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ hasWindowToken -> if (hasWindowToken && !isShowing) { showAtLocation(tooltipLayout, Gravity.NO_GRAVITY, 100, 100) } }, { t: Throwable? -> //error logging }) } with companion object { private const val RETRY_COUNT = 5 private const val MIN_TIME_OUT_MS = 50L } class RetryException : Throwable()
You can specify the y-offset to account for the status bar from the pw.showAtLocation method...