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エラー104 Uncought:ArrayIndexOutOfBoundsException」

4

1 に答える 1

2

答えを見つけました:

「メインイベントスレッド以外のスレッドからダイアログを開くことはできません」

Synchronizedは、現在のスレッドでステートメントを実行しますが、イベント ロックを保持します。代わりにinvokeAndWait、ステートメントをイベント キューに送信し、後でメイン イベント スレッドで実行します。

それが私のコードがうまくいかなかった理由ですsynchronized

これは役に立ちました:https://stackoverflow.com/a/6515542/1680787

@Nate、あなたは私のキャッチブロック、+1、そして私の悪いことについて絶対に正しいです。

于 2013-01-30T19:30:27.010 に答える