android handler runnable使用執行個體(關鍵是內部run中停止),androidrunnable
.java
1 package com.example.mydemo; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Handler; 6 import android.os.Message; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button;10 import android.widget.TextView;11 12 public class MainActivity extends Activity {13 private TextView text_view = null;14 private Button start = null;15 private Button end = null;16 private int count = 0;17 // 使用handler時首先要建立一個handler18 Handler handler = new Handler();19 // 要用handler來處理多線程可以使用runnable介面,這裡先定義該介面20 // 線程中運行該介面的run函數21 Runnable update_thread = new Runnable() {22 public void run() {23 // 線程每次執行時輸出"UpdateThread..."文字,且自動換行24 // textview的append功能和Qt中的append類似,不會覆蓋前面25 // 的內容,只是Qt中的append預設是自動換行模式26 // text_view.append("\nUpdateThread...");27 text_view.setText(String.valueOf(count++));28 // 延時1s後又將線程加入到線程隊列中29 if (count >= 5) {30 // handler.removeCallbacks(update_thread);//用此行停止不行,需要發訊息外部停止才可以。不明白?31 Message message = new Message();32 message.what = 1;33 handlerStop.sendMessage(message);34 }35 handler.postDelayed(update_thread, 1000);36 37 }38 };39 40 @Override41 public void onCreate(Bundle savedInstanceState) {42 super.onCreate(savedInstanceState);43 setContentView(R.layout.activity_main);44 45 text_view = (TextView) findViewById(R.id.text_view);46 start = (Button) findViewById(R.id.start);47 start.setOnClickListener(new StartClickListener());48 end = (Button) findViewById(R.id.end);49 end.setOnClickListener(new EndClickListener());50 handler.post(update_thread);51 }52 53 private class StartClickListener implements OnClickListener {54 public void onClick(View v) {55 // TODO Auto-generated method stub56 // 將線程介面立刻送到線程隊列中57 handler.post(update_thread);58 }59 }60 61 private class EndClickListener implements OnClickListener {62 public void onClick(View v) {63 // TODO Auto-generated method stub64 // 將介面從線程隊列中移除65 count = 0;66 handler.removeCallbacks(update_thread);67 }68 }69 70 final Handler handlerStop = new Handler() {71 public void handleMessage(Message msg) {72 switch (msg.what) {73 case 1:74 count = 0;75 handler.removeCallbacks(update_thread);76 break;77 }78 super.handleMessage(msg);79 }80 81 };82 }
.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <TextView 8 android:id="@+id/text_view" 9 android:layout_width="fill_parent"10 android:layout_height="200dip"11 android:text="@string/hello_world"12 tools:context=".MainActivity" />13 14 <Button15 android:id="@+id/start"16 android:layout_width="fill_parent"17 android:layout_height="wrap_content"18 android:text="start" />19 20 <Button21 android:id="@+id/end"22 android:layout_width="fill_parent"23 android:layout_height="wrap_content"24 android:text="end" />25 26 </LinearLayout>