gpt4 book ai didi

android - 在应用程序类的警报对话框中获取上下文时出错

转载 作者:行者123 更新时间:2023-11-29 16:06:10 25 4
gpt4 key购买 nike

我正在创建一个应用程序类以在应用程序启动期间执行一些版本检查。下面是我的课。

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 语句都工作正常。

最佳答案

您不能在应用程序类中创建对话框,因为对话框应该附加到窗口,应用程序不是 UI 类并且没有窗口,因此它不能显示对话框。

你可以通过创建一个显示对话框的 Activity 来解决它(你可以将数据作为额外的 Intent 传递),当数据准备好时触发并显示对话框

关于android - 在应用程序类的警报对话框中获取上下文时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18136247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com