3
  1. ハンドラーを使用したアクティビティ(UIスレッド)があります
  2. 新しいスレッドを開始し、handler.post(new MyRunnable())-(新しい作業スレッド)を作成します

Androidのドキュメントには、postメソッドについて次のように記載されています。「Runnablerがメッセージキューに追加されます。Runnableは、このハンドラーが接続されているスレッドで実行されます。」

UIスレッドにアタッチされたハンドラー。新しいスレッドを作成せずに、Androidを同じUIスレッドで実行可能にするにはどうすればよいですか?

新しいスレッドはhandler.post()からRunnableを使用して作成されますか?または、run()メソッドのみがRunnableサブクラスから呼び出されますか?

4

2 に答える 2

5

ハンドラーの使用方法の大まかな疑似コードの例を次に示します-お役に立てば幸いです:)

class MyActivity extends Activity {

    private Handler mHandler = new Handler();

    private Runnable updateUI = new Runnable() {
        public void run() {
            //Do UI changes (or anything that requires UI thread) here
        }
    };

    Button doSomeWorkButton = findSomeView();

    public void onCreate() {
        doSomeWorkButton.addClickListener(new ClickListener() {
            //Someone just clicked the work button!
            //This is too much work for the UI thread, so we'll start a new thread.
            Thread doSomeWork = new Thread( new Runnable() {
                public void run() {
                    //Work goes here. Werk, werk.
                    //...
                    //...
                    //Job done! Time to update UI...but I'm not the UI thread! :(
                    //So, let's alert the UI thread:
                    mHandler.post(updateUI);
                    //UI thread will eventually call the run() method of the "updateUI" object.
                }
            });
            doSomeWork.start();
        });
    }
}
于 2011-03-15T20:33:39.397 に答える
3

UIスレッドにアタッチされたハンドラー。

正しい。

新しいスレッドを作成せずに、Androidを同じUIスレッドで実行可能にするにはどうすればよいですか?

メインアプリケーション(「UI」)スレッドを含むすべてのスレッドは、Handler(または、さらに言えば、任意Viewの)でpost()を呼び出すことができます。

于 2011-03-15T18:56:00.060 に答える