編輯:關於android開發
通常我們在處理耗時任務時候都會通過新建線程來處理,當任務處理完後通過Handler將結果發送回主線程。比如下面示例:
1 package com.example.testlistener; 2 3 import java.util.Timer; 4 import java.util.TimerTask; 5 6 import android.app.Activity; 7 import android.content.res.Configuration; 8 import android.os.Bundle; 9 import android.os.Handler; 10 import android.os.Message; 11 import android.view.View; 12 import android.view.View.OnClickListener; 13 import android.view.View.OnLongClickListener; 14 import android.widget.Button; 15 import android.widget.EditText; 16 import android.widget.Toast; 17 18 public class MainActivity extends Activity { 19 EditText txt; 20 final Handler hander = new Handler(){ 21 public void handleMessage(android.os.Message msg) { 22 if(msg.what == 0x1234){ 23 Toast.makeText(MainActivity.this, msg.arg1 + "", 1000).show(); 24 } 25 }; 26 }; 27 @Override 28 protected void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.activity_main); 31 32 new Timer().schedule(new TimerTask() { 33 int i = 0; 34 @Override 35 public void run() { 36 i++; 37 Message msg = new Message(); 38 msg.what = 0x1234; 39 msg.arg1 = i; 40 hander.sendMessage(msg); 41 } 42 }, 0, 2000); 43 } 44 45 }
那麼,我們能不能通過Handler從主線程發送消息給子線程呢?答案是肯定的,需要用到Looper.prepare()和Looper.loop()。如下面的代碼:
1 public class MainActivity extends Activity { 2 EditText txt; 3 Button bt; 4 TestThread testThread; 5 int j = 0; 6 7 @Override 8 protected void onCreate(Bundle savedInstanceState) { 9 super.onCreate(savedInstanceState); 10 setContentView(R.layout.activity_main); 11 txt = (EditText) findViewById(R.id.txt); 12 bt = (Button) findViewById(R.id.bn); 13 testThread = new TestThread(); 14 testThread.start(); 15 bt.setOnClickListener(new OnClickListener() { 16 17 @Override 18 public void onClick(View arg0) { 19 j++; 20 Message msg = new Message(); 21 msg.what = 0x1000; 22 msg.arg1 = j; 23 testThread.thander.sendMessage(msg); 24 } 25 }); 26 27 28 } 29 30 //自定義子線程 31 class TestThread extends Thread{ 32 public Handler thander; 33 @Override 34 public void run() { 35 //創建一個Looper對象 36 Looper.prepare(); 37 thander = new Handler(){ 38 @Override 39 public void handleMessage(Message msg) { 40 if(msg.what == 0x1000){ 41 System.out.println("j = " + msg.arg1); 42 //txt.setText(msg.arg1 + ""); 43 } 44 } 45 }; 46 //啟動Looper 47 Looper.loop(); 48 } 49 } 50 51 }
android WindowManager解析與騙取QQ密碼案例分析 最近在網上看見一個人在烏雲上提了一個漏洞,應用可以開啟一個後台Service,檢測當前頂部應用
Android Studio導入修改,androidstudio導入
基於PinnedSectionListView實現聯系人通訊錄並且點擊打電話,手機通訊錄聯系人恢復PinnedSectionListView具體下載地址、使用方法和注意事
Android開發學習之路--圖表實現(achartengine/MPAndroidChart)之初體驗 ??已經有一段時間沒有更新博客了,在上周離開工作了4年的公司,從