Android中實(shí)現(xiàn)Runnable接口簡單例子
本課講的是如何實(shí)現(xiàn)一個Runnable,在一個獨(dú)立線程上運(yùn)行Runnable.run()方法.Runnable對象執(zhí)行特別操作有時叫作任務(wù)。
Thread和Runnable都是基礎(chǔ)的類,靠他們自己,能力有限。作為替代,Android有強(qiáng)大的基礎(chǔ)類,像HandlerThread,AsyncTask,IntentService。Thread和Runnable也是ThreadPoolExecutor的基礎(chǔ)類。這個類可以自動管理線程和任務(wù)隊列,甚至可以并行執(zhí)行多線程。
定義一個實(shí)現(xiàn)Runnable接口的類
public class PhotoDecodeRunnable implements Runnable {
...
@Override
public void run() {
/*
* Code you want to run on the thread goes here
*/
...
}
...
}
實(shí)現(xiàn)run()方法
Runnable.run()方法包含了要執(zhí)行的代碼。通常,Runnable里可以放任何東西。記住,Runnable不會在UI運(yùn)行,所以不能直接修改UI對象屬性。與UI通訊,參考Communicate with the UI Thread
在run()方法的開始,調(diào)用 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);設(shè)置線程的權(quán)重,android.os.Process.THREAD_PRIORITY_BACKGROUND比默認(rèn)的權(quán)重要低,所以資源會優(yōu)先分配給其他線程(UI線程)
你應(yīng)該保存線程對象的引用,通過調(diào)用 Thread.currentThread()
class PhotoDecodeRunnable implements Runnable {
...
/*
* Defines the code to run for this task.
*/
@Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
...
/*
* Stores the current Thread in the PhotoTask instance,
* so that the instance
* can interrupt the Thread.
*/
mPhotoTask.setImageDecodeThread(Thread.currentThread());
...
}
...
}
- android Gallery組件實(shí)現(xiàn)的iPhone圖片滑動效果實(shí)例
- Android實(shí)現(xiàn)GPS定位代碼實(shí)例
- Unity3D游戲引擎實(shí)現(xiàn)在Android中打開WebView的實(shí)例
- android界面布局之實(shí)現(xiàn)文本塊布局效果示例
- Android中自定義加載樣式圖片的具體實(shí)現(xiàn)
- android自定義按鈕示例(重寫imagebutton控件實(shí)現(xiàn)圖片按鈕)
- android實(shí)現(xiàn)通知欄下載更新app示例
- Android實(shí)現(xiàn)的可以調(diào)整透明度的圖片查看器實(shí)例
相關(guān)文章
Android圖片處理教程之全景查看效果實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于Android圖片處理教程之全景查看效果實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
Android UTF-8轉(zhuǎn)碼實(shí)例詳解
這篇文章主要介紹了Android UTF-8轉(zhuǎn)碼實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
Android 實(shí)現(xiàn)仿支付寶的密碼均分輸入框
這篇文章主要介紹了Android 實(shí)現(xiàn)仿支付寶的密碼均分輸入框的相關(guān)資料,需要的朋友可以參考下2017-06-06
Android調(diào)用系統(tǒng)圖庫獲取圖片的方法
這篇文章主要為大家詳細(xì)介紹了Android調(diào)用系統(tǒng)圖庫獲取圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08
Android仿知乎客戶端關(guān)注和取消關(guān)注的按鈕點(diǎn)擊特效實(shí)現(xiàn)思路詳解
這篇文章主要介紹了Android仿知乎客戶端關(guān)注和取消關(guān)注的按鈕點(diǎn)擊特效實(shí)現(xiàn)思路詳解的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09
解析Android開發(fā)優(yōu)化之:對Bitmap的內(nèi)存優(yōu)化詳解
在Android應(yīng)用里,最耗費(fèi)內(nèi)存的就是圖片資源。而且在Android系統(tǒng)中,讀取位圖Bitmap時,分給虛擬機(jī)中的圖片的堆棧大小只有8M,如果超出了,就會出現(xiàn)OutOfMemory異常。所以,對于圖片的內(nèi)存優(yōu)化,是Android應(yīng)用開發(fā)中比較重要的內(nèi)容2013-05-05
Android ServiceManager的啟動和工作原理
這篇文章主要介紹了Android ServiceManager的啟動和工作原理,幫助大家更好的理解和學(xué)習(xí)使用Android開發(fā),感興趣的朋友可以了解下2021-03-03

