我正在创建一个应用程序类来在应用程序启动期间执行一些版本检查。下面是我的课。
public class MyApp extends Application {
public MyApp() {
}
@Override
public void onCreate() {
super.onCreate();
new checkVersionTask().execute(getApplicationContext)
}
private class checkVersionTask extends AsyncTask<Context, Integer, Long> {
@Override
protected Long doInBackground(Context... contexts) {
TODO—version check code
}
protected void onPostExecute(Long result) {
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(MyApp.this).create();
alertDialog.setMessage(("A new version of app is available. Would you like to upgrade now?"));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(R.string.Button_Text_Yes), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("update URL");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,getResources().getString(R.string.Button_Text_No), new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "ERROR:"+e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
这里 alertDialog.show 抛出错误
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
据我了解,这是因为上下文不可用。在行
alertDialog = new AlertDialog.Builder(MyApp.this).create();
我尝试了 getApplicationContext() 而不是 MyApp.this,仍然是同样的问题。
谁能建议这里出了什么问题。所有 Toast 语句都工作正常。