I'm studying about Threads and Services and I know that to run a longer process, like searching internet signal or download, I must put it to run on a Background Thread and not on the UI (User Interface) Thread. In the app below I made an example of code running in the background and as this process progresses, there are updates in the progress bar, but when I run the application, I get an error saying the following:
java.lang.IllegalStateException: The specified message queue synchronization barrier token has not been posted or has already been removed.
Below is the code:
package com.gabrielm.myapplication;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
Handler mHandler;
Button mButton;
ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mButton = (Button) findViewById(R.id.button);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mProgressBar.setProgress(msg.arg1);
}
};
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
for (int i = 0; i < 100; i++) {
msg.arg1 = i;
mHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}
Searching the internet for a possible solution to the problem, I found that the sendMessage(msg)
method has to always send a new object of type Message
to the message queue every time I want to send a new message. That is, I can not reuse the same object, I have to always create a new one every time I want to send a data to handleMessage(Message msg);
. So what I did was remove the code line Message msg = Message.obtains();
from the place where it was and place it inside the for
block, because so every time for
executes, it creates a new object of type Message
.
This little change in code made the program work, but I'm not sure if what I did was the most correct way to do the process. So I wonder if the logic I've developed here is right.