removeCallbacksAndMessage.java
package com.jing.example.nknu_.removecallbacksandmessage;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class removeCallbacksAndMessage extends AppCompatActivity {
Object tag = new Object();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_callbacks_and_message);
}
public void Start (View v){
Handler handler = new Handler(){
public void handleMessage(Message msg) {
//訊息處理
System.out.println("訊息已被處理");
}
};
Message message = handler.obtainMessage(0,tag);
handler.sendMessage(message);
System.out.println("訊息已傳送出去");
handler.postAtTime(new Runnable() {
public void run() {
}
}, tag, SystemClock.uptimeMillis());
//handler.removeCallbacksAndMessages(tag);
final Handler final_handler = handler;
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
final_handler.removeCallbacksAndMessages(tag);//進行訊息攔截與刪除
}
});
t1.start();
/*
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
}
}
activity_remove_callbacks_and_message.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.jing.example.nknu_.removecallbacksandmessage.removeCallbacksAndMessage"
tools:showIn="@layout/activity_remove_callbacks_and_message">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:layout_marginTop="170dp"
android:onClick="Start" />
</RelativeLayout>