使用Handler的步骤

1. 在Activity中定义Handler并实现handleMessage方法用来处理接收到的消息。

2. 定义一个Runable实例,并在run方法中设置和发送消息(使用Bundle实现)

3. 新建一个Thread并运行步骤2中的Runable。调用Thread.start().

完整代码

public class MainActivity extends AppCompatActivity {
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // Get message from another thread.
            String msgStr = msg.getData().getString("msg");
            Toast.makeText(MainActivity.this, msgStr, Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonClick(View view) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Bundle bundle = new Bundle();
                bundle.putString("msg", "Hello, world");

                // Send the message to main thread.
                Message msg = handler.obtainMessage();
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        };

        Thread myThread = new Thread(runnable);
        myThread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

Handler的两个用途:

1. 在其他线程中执行一个操作,上面的例子就是。

2. 在将来的某个时间执行一个操作(同一线程),比如显示应用的启动画面(Splash Screen)可用此法。

如下:3秒钟之后显示Post run.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "Post run", Toast.LENGTH_SHORT).show();
            }
        };

        Handler handler = new Handler();
        handler.postDelayed(runnable, 3000);
    }
}

也可以简写成如下形式:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(MainActivity.this, "Post run", Toast.LENGTH_SHORT).show();
    }
}, 5000);

==

你可能感兴趣的:(使用Handler的步骤)