earsonheart
earsonheart

Reputation: 1052

Showing AlertDialog from not UI thread

I'm connecting to bluetooth in background and I want to show alert or toast befor processing socket.

Here is my code

mmSocket.connect();
connectionHandler.post(new Runnable() {
    public void run() {
        AlertDialog.Builder builder = new AlertDialog.Builder(BluetoothSampleActivity.this);
        builder.setMessage("conneted");
        builder.show();
    }
});
manageConnectedSocket(mmSocket);

but as I understand alert will be shown only when this will end his work. How can i show alert BEFORE executing manageConnectedSocket(mmSocket);?

P.S.: I tryed runOnUiThread - it didn't help

Upvotes: 0

Views: 822

Answers (1)

gwvatieri
gwvatieri

Reputation: 5183

I suggest to move your logic from a normal Thread to an AsyncTask. Whenever you have to do heavy work but also to interact with the UI, AsyncTask is the best practice.

On the preExecute() method you show the dialog or update UI, on doInBackground you do whatever you need to do and on onPostExecute you dismiss the dialog or re-update the UI.

Here the AsyncTask doc.

En plus, if you need to show a progress of the work that you are doing in background, it comes super easy thanks to the methods publishProgress/onProgressUpdate.

Upvotes: 2

Related Questions