android多執行緒--計時案例
阿新 • • 發佈:2019-02-19
在android應用開發中,多執行緒很常見,而且很java中的多執行緒有些不同。在android多執行緒中,主執行緒負責管理其他子執行緒,必須明確主執行緒和子執行緒的職責,否則統會丟擲異常“Only the original thread that created a view hierarchy can touch its views”。這裡我們可以用訊息(Message)或訊息佇列(MessageQueue)解決。
Android執行緒涉及的技術有:Handler;Message;MessageQueue;Looper;HandlerThread。
這裡的android編寫風格雖然違背了java變成規範,但是在實際android開發應用中很常見。
程式執行結果:
下面看程式碼:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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" tools:context=".MainActivity" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="關閉執行緒" android:onClick="closeThreadButton" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/timerView" /> </LinearLayout>
MainActivity.java
package org.mtn.threaddemo; import net.tsz.afinal.FinalActivity; import net.tsz.afinal.annotation.view.ViewInject; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends FinalActivity { @ViewInject(id = R.id.timerView) TextView timerView; private boolean isRunning = true; private int timer = 0; private Handler handler = new Handler() { public void handleMessage(Message msg) { if(0 == msg.what) timerView.setText("運行了" + msg.obj + "秒"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { while(isRunning) { try { Thread.currentThread().sleep(1000); timer ++; Message msg = new Message(); msg.obj = timer; msg.what = 0; handler.sendMessage(msg); Toast.makeText(getApplicationContext(), "運行了" + timer + "秒", 1).show(); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } public void closeThreadButton(View v) { isRunning = false; } }