編輯:關於Android編程
package com.zf.thread_test; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.app.ProgressDialog; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private static final int TIME_OUT = 0; private static final int SUCCESS = 1; // 超時的時限為5秒 private static final int TIME_LIMIT = 5000; ProgressDialog proDialog; Timer timer; Thread thread; Button btn1, btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button) findViewById(R.id.button1); btn2 = (Button) findViewById(R.id.button2); // 測試未超時的線程,為btn1綁定事件 btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { proDialog = ProgressDialog.show(MainActivity.this, "提示", "線程運行中"); // 匿名內部線程 thread = new Thread() { @Override public void run() { while (true) { try { //線程休眠時間,超時 sleep(10000); } catch (InterruptedException e) { break; } } } }; thread.start(); // 設定定時器 timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { sendTimeOutMsg(); } }, TIME_LIMIT); } }); // 測試超時的線程,為btn2綁定事件 btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { proDialog = ProgressDialog.show(MainActivity.this, "提示", "線程運行中"); // 匿名內部線程 thread = new Thread() { public void run() { try { // 線程休眠時間,未超時 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } Message msgSuc = new Message(); msgSuc.what = SUCCESS; myHandler.sendMessage(msgSuc); } }; thread.start(); // 設定定時器 timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { sendTimeOutMsg(); } }, TIME_LIMIT); } }); } // 接收消息的Handler final Handler myHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case TIME_OUT: //打斷線程 thread.interrupt(); proDialog.dismiss(); Toast.makeText(MainActivity.this, "線程超時", Toast.LENGTH_SHORT) .show(); break; case SUCCESS: //取消定時器 timer.cancel(); proDialog.dismiss(); Toast.makeText(MainActivity.this, "線程運行完成", Toast.LENGTH_SHORT) .show(); break; default: break; } }; }; //向handler發送超時信息 private void sendTimeOutMsg() { Message timeOutMsg = new Message(); timeOutMsg.what = TIME_OUT; myHandler.sendMessage(timeOutMsg); } }
使用Intent來啟動Activity Intent的用途是綁定應用程序組件, 並在應用程序之間進行通信; startActivity(),
Android Studio 大家應該都很熟悉了,但是可能很多人都僅限基本的功能使用,而 Android Studio 非常強大,有很多非常實用卻又鮮為人知的小技巧,熟練
本例子演示如何添加一個簡單的單頁導航,在此基礎上,再演示如何在第2個頁面中顯示第1個頁面中撥打過的所有電話號碼。(1)通過該例子理解Android App的基本架構。(2
復習一下view滑動的幾種實現方式1.通過layout實現通過不斷重新layout view 達到滑動的效果。 @Override public boolea