我的Android應用程序需要延遲後顯示對話框。問題是,當顯示對話框時,上下文可能已經改變。如何在另一個上下文中顯示對話框?
我該如何解決這個問題?
我的代碼現在看起來是這樣的:
class UpdateRunnable extends Runnable {
private Context ctx;
UpdateRunnable(Context ctx) {
this.ctx = ctx
}
@Override
public void run() {
//throws exception: "Unable to add window -- token null is not for an application"
AlertDialog.Builder builder = new AlertDialog.Builder(ctx.getApplicationContext());
builder.setTitle("Time to refresh data");
builder.setMessage("Data needs updating");
builder.show();
}
}
class MyAvtivity extends AppCompatActivity {
@override
public void onCreate(...) {
Handler updateHandler = new Handler();
updateHandler.postDelayed(new UpdateRunnable(this), 10000);
//do some stuff
//start another activity
}
}
這不會引發異常,但它也不會顯示對話框(因爲它試圖在不再可見的活動上顯示它),並且稍後會泄漏該窗口 – B1CL0PS