3
I am studying about Threads and Services and I know that to run a longer process, such as looking for internet signal or download, I must put it to run in a Background Thread and not in the UI (User Interface) Thread. In the app below I did 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 method sendMessage(msg)
always send a new object of the type Message
for the queue of messages each time I want to send a new message. I mean, I can’t reuse the same object, I always have to create a new one every time I want to send a data to the handleMessage(Message msg);
. So what I did was remove the line of code Message msg = Message.obtains();
from the place where it was and put inside the block for
, because so each time for
executes, it creates a new object of type Message
.
This small change in the code made the program work, but I’m not sure if what I did was the right way to do it. So I’d like to know if the logic I’ve developed here is right.
Thanks for the feedback, it’s good to know I’m on the right track. It took me a few hours to get that right, but I think I’ve finally managed to dilute that content. By the way, I was wondering if I should use Message msg = Message.obtains() or Message msg = new Message(), but now I understand that the best is Message.obtains(), since it is reusing a recycled object and not creating a new one. Anyway, thank you for your reply, it was of great help.
– Gabriel Linassi