WindowManager$BadTokenException in Android

2019-02-20 05:28发布

问题:

First of all, I'm well aware that this error is occur because I'm trying to call window/dialog through a Context that is not an Activity.

But isn't there any solution to that. My requirements are; I have a Dialog with a custom style sheet in a method of a normal JAVA class. I want to call that method from any Activity class when I need to load the Dialog.

In my Activity class I'm having following code set;

HomeClass homeClass = new HomeClass();
homeClass.showSplashScreen();

Then in my HomeClass I have following code set;

public void showSplashScreen() {        
 splashDialog = new Dialog(HomeActivity.getAppContext(), R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
 splashDialog.show();
}

By maintaining this design, is there any way to get rid of the WindowManager$BadTokenException

Thank You

回答1:

I am going to modify your code, that maybe helpful for you...

HomeClass homeClass = new HomeClass(this);
homeClass.showSplashScreen();

In Your Home class.. add parametric constructor..

public class Home {
private Context context;
public Home(Context context){
this.context = context;
}
public void showSplashScreen() {        
splashDialog = new Dialog(context, R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
splashDialog.show();
}


回答2:

Pass Your Activity to showSplashScreen() Method...

Do like this..

HomeClass homeClass = new HomeClass();
homeClass.showSplashScreen(Your Actvity);

In Your Home class

public void showSplashScreen(Activity curActivity) {        
 splashDialog = new Dialog(curActivity, R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
 splashDialog.show();
}