Search code examples
javaandroidhandlerrunnable

Runnable hangs UI thread on Android


I have a piece of code that is run every hour. The code does some SQL tasks on a local SQLite database on the device. Sometimes this task is a little more cumbersome than others, and when it is, the application hangs enough time that a "is not responding" dialog opens up and gives me the option to wait or close the app.

This is my code

UpdateTimerCleanUp = new Runnable() {
    @Override
    public void run() {
        TextView updatedTxt = findViewById(R.id.updated_txt);
        updatedTxt.setText("Performing database history cleanup..");
        archive.archieveHistory();
        ArchiveHandler.postDelayed(UpdateTimerCleanUp, CleanUpCycle);
    }
};
ArchiveHandler.postDelayed(UpdateTimerCleanUp, CleanUpCycle);

I'm using a handler to call the runnable every hour (CleanUpCycle). That part works, but why does it hang my UI? As i understand it a runnable is run on another thread?


Solution

  • Handlers run Runnables on whatever thread the Handler was created on. So if you created ArchiveHandler on the main thread, it will run the UpdateTimerCleanUp code on the main trough. I'm not sure what your archieveHistory() method does exactly, but I'm guessing it takes long enough to run that it's causing the application-not-responding error due to blocking the main thread.

    To solve it, you should use some means of background execution that suits your needs (Executors, Threads, etc.).