user722826
user722826

Reputation: 41

Android:AlertDialog triggered by Timer

Hello and thanks in advance for any advice you can offer with the following problem. I have a simple Activity that shows an AlertDialog. It works fine if I instantiate the AlertDialog in the constructor. If, however, I move the AlertDialog to another method, one triggered by a Timer event, nothing happens and I see no errors:

public class RecipesPage extends Activity
{
    private WebView browser;
    private Timer timer = new Timer();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recipes);

        browser = (WebView)findViewById(R.id.webkit);
        browser.getSettings().setJavaScriptEnabled(true);
        browser.loadUrl("file:///android_asset/html/index.html");

        TimerTask task=new TimerTask() {
            public void run() {
                notifyMe();
            }
        };
        timer.schedule(task, 10000);
    }

    private void notifyMe()
    {
        new AlertDialog.Builder(this)
        .setTitle("MessageDemo")
        .setMessage("eek!")
        .setNeutralButton("Close", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sumthin) {
                // do nothing -- it will close on its own
            }
        })
        .show();
    }

}

Upvotes: 1

Views: 1248

Answers (1)

Volo
Volo

Reputation: 29438

Use a Handler instead of TimerTask - it will run your Runnable on the UI thread.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recipes);

    browser = (WebView)findViewById(R.id.webkit);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.loadUrl("file:///android_asset/html/index.html");

    Handler handler = new Handler();
    handler.postDelayed(
        new Runnable() {
            public void run() {
              notifyMe();
            }
        }, 10000L);
}

Upvotes: 1

Related Questions