记一次安卓Handler.removeMessages引发的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int MESSAGE_WHAT_SAY_HI = 0;
private static final int MESSAGE_WHAT_SAY_HELLO = 1;
private static class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_WHAT_SAY_HI:
Log.i(TAG, "hi");
break;
case MESSAGE_WHAT_SAY_HELLO:
Log.i(TAG, "hello");
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new MyHandler();
long delayTime = 5000;
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.i(TAG, "en....");
}
}, delayTime);
handler.sendEmptyMessageDelayed(MESSAGE_WHAT_SAY_HI, delayTime);
handler.sendEmptyMessageDelayed(MESSAGE_WHAT_SAY_HELLO, delayTime);
handler.removeMessages(MESSAGE_WHAT_SAY_HI);
}
}

以上代码输入为:

1
hello

而不是:

1
2
en....
hello