網站首頁 編程語言 正文
簡介
前一章我們以一個簡單的小動畫來解釋了Handler。
這章我們會介紹在子線程里寫Handler。如果是Handler寫在了子線程中的話,我們就需要自己創建一個Looper對象了:創建的流程如下:
- 直接調用Looper.prepare()方法即可為當前線程創建Looper對象,而它的構造器會創建配套的MessageQueue;
- 創建Handler對象,重寫handleMessage( )方法就可以處理來自于其他線程的信息了!
- 調用Looper.loop()方法啟動Looper
本章示例
使用示例: 輸入一個數,計算后通過Toast輸出在這個范圍內的所有質數,如下截圖。
前端代碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/inputNum" android:inputType="number" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="請輸入計算范圍"/> <Button android:id="@+id/buttonCalc" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="開始計算"/> </LinearLayout>
很簡單,前端有一個輸入框一個按鈕。
來看后端代碼
后端代碼
package org.mk.android.demo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String INPUT_NUM = "inputNum";
private EditText inputNum;
private Button buttonCal;
CalThread calThread;
class CalThread extends Thread
{
public Handler mHandler;
public void run()
{
Looper.prepare();
mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
if(msg.what == 101)
{
int inputNum = msg.getData().getInt(INPUT_NUM);
List<Integer> nums = new ArrayList<Integer>();
// 計算從2開始、到upper的所有質數
outer:
for (int i = 2 ; i <= inputNum ; i++)
{
// 用i處于從2開始、到i的平方根的所有數
for (int j = 2 ; j <= Math.sqrt(i) ; j++)
{
// 如果可以整除,表明這個數不是質數
if(i != 2 && i % j == 0)
{
continue outer;
}
}
nums.add(i);
}
// 使用Toast顯示統計出來的所有質數
Toast.makeText(MainActivity.this , nums.toString()
, Toast.LENGTH_LONG).show();
}
return false;
}
});
Looper.loop();
}
}
public void cal(View source)
{
// 創建消息
Message msg = new Message();
msg.what = 101;
Bundle bundle = new Bundle();
bundle.putInt(INPUT_NUM ,
Integer.parseInt(inputNum.getText().toString()));
msg.setData(bundle);
// 向新線程中的Handler發送消息
calThread.mHandler.sendMessage(msg);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCal=(Button)findViewById(R.id.buttonCalc);
inputNum=(EditText)findViewById(R.id.inputNum);
buttonCal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cal(view);
}
});
calThread=new CalThread();
calThread.start();
}
}
后端代碼我們使用的是求給定數字范圍內有幾個質數里比較高效的一種算法。
關鍵在于:
- 使用線程,在線程開始我們使用:Loop.prepare,在運算完后使用Loop.loop();
- 使用mHandler = new Handler(new Handler.Callback()進行監聽;
- 使用message發送主界面輸入的“質數”給到在監聽的mHandler;
- 當mHandler監聽到有消息到達后開始運算質數集,運算后把結果以Toast輸出
自己動一手吧。
原文鏈接:https://blog.csdn.net/lifetragedy/article/details/128168389
相關推薦
- 2022-11-01 Flask路由尾部有沒有斜杠有什么區別_python
- 2022-11-06 python使用minimize()?函數替代matlab的fmincon函數_python
- 2022-04-25 python遞歸&迭代方法實現鏈表反轉_python
- 2023-03-28 Python中的len()函數是什么意思_python
- 2023-04-03 python中super().__init__()作用詳解_python
- 2022-09-17 Go語言學習筆記之錯誤和異常詳解_Golang
- 2024-07-15 SpringBoot使用itext導出pdf(含圖片和表格)
- 2023-07-29 iview的表格實現單元格行編輯功能
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支