I’m developing an Android application and I have a problem running a new thread in background.
I make a class with this code:
public class Downloader implements Runnable {
private Vector <DownloadRequest>messages = new Vector<DownloadRequest>();
static final int MAXQUEUE = 5;
ApiRequest mApi;
public void run() {
try {
while ( true ) {
getMessage();
}
}
catch( ErrorException e ) { }
}
private synchronized void getMessage() throws ErrorException{
try {
notify();
Log.d("DOWNLOADER", "empiezo a coger los mensajes");
while ( messages.size() == 0 )
wait();
DownloadRequest dr = messages.firstElement();
mApi.setMethod(dr.getRequest());
try {
mApi.executeRequest();
} catch (ErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object o = dr.getObject();
o.notify();
return;
}catch(InterruptedException e) {
throw new ErrorException();
}
The purpose is wait for receive a new message and call the api.
This object is running in a new thread in this Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
mDownloader = new Downloader(new ApiRequest());
Thread thread = new Thread(mDownloader);
thread.start();
DownloadRequest dr = new DownloadRequest(this,TRIPS_METHOD);
try {
mDownloader.putMessage(dr);
But when thread.start() is called the UI remains blocked. I thinks this shouldn’t happen because is a new thread.
Can anyone help me?
Thanks
You are much better served using pre-established classes for this. In Android,
AsyncTaskhandles both the background thread pool and the work queue. If you absolutely feel you have to fork your own thread, use aLinkedBlockingQueueinstead of attempting to synchronize access to aVector. There are a couple of books on Java concurrency available if you wish to read more on the subject.