2

我想从一个单独的线程打开一个对话框,但是在使用这种synchronized方式时,我得到了一个错误。

如果我使用该方法invokeAndWait一切正常,但是我不明白为什么我不能使用synchronized.

这是我在屏幕上调用的代码:

public void Login() {

        new HttpRequestDispatcher("http://www.google.com", "GET", this) {
            public void onSuccess(byte[] baos, String contentType) {
                synchronized(UiApplication.getEventLock()){
                    Dialog.alert("Cooooooool....");
                }
            }
            public void onFail(String message){
                synchronized(UiApplication.getEventLock()){
                    Dialog.alert(message);
                }
            }
        }.start();
    }

这是 HttpRequestDispatcherThread:

public abstract class HttpRequestDispatcher extends Thread {

    String url;
    String method;
    Screen scr;

    public HttpRequestDispatcher(String url, String method, Screen scr) {
        this.url = url;
        this.method = method;
        this.scr = scr;
    }

    public abstract void onFail(String message);
    public abstract void onSuccess(byte[] baos, String contentType);
    public void beforeSend() {}
    public void onComplete() {}

    public void run() {

        beforeSend();

        try {

            HttpConnection connection = (HttpConnection) Connector.open(url);
            connection.setRequestMethod(method);

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpConnection.HTTP_OK) {
                onFail(connection.getResponseMessage());
                connection.close();
                return;
            }

            String contentType = connection.getHeaderField("Content-type");
            int contentLength = (int) connection.getLength();
            if (contentLength < 0)
                contentLength = 10000;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream responseData = connection.openInputStream();
            byte[] buffer = new byte[contentLength];
            int bytesRead = responseData.read(buffer);

            while (bytesRead > 0) {
                baos.write(buffer, 0, bytesRead);
                bytesRead = responseData.read(buffer);
            }

            baos.close();
            connection.close();

            onComplete();
            onSuccess(baos.toByteArray(), contentType);

        } catch (Exception e) {
        }
    }
}

我在模拟器中收到此错误:“JVM Error 104 Uncought: ArrayIndexOutOfBoundsException”

4

1 回答 1

2

找到了答案:

“不能从主事件线程以外的线程打开对话框”

Synchronized在当前线程中执行一条语句,但持有事件锁,相反,invokeAndWait将语句发送到事件队列,稍后在主事件线程上执行。

这就是为什么我的代码无法使用synchronized

这有帮助:https ://stackoverflow.com/a/6515542/1680787

@Nate,您对我的 catch 块、+1 和我的坏事是绝对正确的,只是黑莓的新手。

于 2013-01-30T19:30:27.010 回答