因目前在寫遊戲,需要使用到"倒數計時器"。
所以參考了網路上文章,先做一個簡單的功能。
底下範例是 在TextView上顯示倒數30秒,歸零後停止倒數
Step1.定義一些物件
private Thread gameThread; //執行緒
private Boolean isGameThreadOver = true; //通知執行緒結束
private Handler handler = new Handler(); //Handler
private int iCntDown_Sec=30; //倒數秒數
private Boolean isCounDown = false; //開始倒數Flag
private TextView tv_CountDown;
Step2. 開始及結束函式...
/*******啟動執行緒*******/
private void gameStart()
{
try
{
isGameThreadOver = false;
isCounDown = true;
handler.post(gameRun);
//runOnUiThread(gameRun);
}
catch(Exception ex)
{
Log.e("JB_TAG", "gameStart Error:"+ex.getMessage());
}
}
/*******結束執行緒*******/
private void gameStop()
{
try
{
isGameThreadOver = true;
isCounDown = false;
//停止runnable
handler.removeCallbacks(gameRun);
Log.v("JB_TAG", "遊戲結束!");
}
catch(Exception ex)
{
Log.e("JB_TAG", "無法成功結束,錯誤原因:"+ex.getMessage());
}
}
/*******遊戲主迴圈*******/
Runnable gameRun = new Runnable() {
public void run()
{
try
{
//當倒數秒數歸零後,停止thread
if(iCntDown_Sec<=0)
{
gameStop();
}
else
{
//每一秒作一次顯示
handler.postDelayed(this, 1000);
iCntDown_Sec--;
tv_CountDown.setText(Integer.toString(iCntDown_Sec));
}
}
catch(Exception ex)
{
Log.e("JB_TAG", "Runnable執行錯誤 :"+ex.getMessage());
}
}
};
Step3. OnCreate
public void onCreate(Bundle savedInstanceState)
{ gameStart(); }
PS.
因為是在MainThread以外的thread 改變UI,所以必須使用
-->handler.post(runnable);
或
-->runOnUiThread(runnable);
有興趣可以上網搜尋一下這兩者的詳細用法!!
參考網站 : 第1天: Minutes To Midnight
文章分類
.NET 5
.NET Core
.NET FrameWork
3C
工作室佈告欄
心理探討
專案測試
軟體工程
開發流程
Agile
Algorithm
ALM
Android SDK
Angular
AngularJS
Architecture
ASP.NET
ASP.NET Core
Books
Bower
C#
C# (Extensions)
ChatBot
CLOUD
Comic
CSS
Dapper
Design Pattern
DevOps
Django
Docker
Domain Driven Design
Entity framework
EXCEL
Financial Derivatives
Firebase
Flask
Front-end
GIT
GitHub
Golang
GraphQL
Gulp
Identity Server
IIS
javascript
jQuery
Keyboard
L-I-F-E
LetsEncrypt
LINQ
LINUX
MongoDB
Multi-Thread
Nuget
Open Source
Oracle
OS
Performance issue
PostgreSQL
Project Management
Python
RabbitMQ
Redis
Redux
RxJS
SAP TM
Scrum
SEO
Sharepoint
Sql Server
SSRS
Study
Swagger
Team Foundation Server
TensorFlow
Testing
Toolkits
Tricking
Trouble Shooting
UML
Unit Test
Vim
Visual Studio
Visual SVN Server
VSCODE
Vue
Web Api
Web Service
WebStorm
Windows Application
WSL
沒有留言:
張貼留言