1
我正在開發一個Android應用程序,我在後臺運行一個新線程時出現問題。Android線程在後臺
我做一類以下代碼:
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();
}
目的是等待接收新的消息,並調用API。
這個對象在一個新線程運行在這個活動
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);
但當thread.start()
被稱爲UI仍然受阻。我認爲這不應該發生,因爲是一個新線程。
任何人都可以幫助我嗎?
謝謝