下面这个例子是使用新线程计算质数
先看图片的演示效果:
下面上代码:界面的布局文件很简单,只是有一个按钮和一个输入的文本框
界面文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true"
tools:context="com.example.administrator.hander.Main2Activity">
<EditText
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入一个数"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交"
android:onClick="text"/>
</LinearLayout>
下面是主文件:
package com.example.administrator.hander;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
final static String NUM="unper";
EditText editText;
myThread mhread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText=(EditText)findViewById(R.id.show);
mhread=new myThread();
Thread thread=new Thread(mhread);
//启动新的线程
thread.start();
}
public void text(View view){
//创建消息
Message message=new Message();
message.what=0x123;
//创建bundle,用于传数据用的,然后把在editText输入的信息传入到bundle中,然后setData
Bundle bundle=new Bundle();
bundle.putInt(NUM,Integer.parseInt(editText.getText().toString()));
message.setData(bundle);
//向线程中的handler发送消息
mhread.handler.sendMessage(message);
}
//定义一个线程类,用于计算判断指数
class myThread implements Runnable{
public Handler handler;
@Override
public void run() {
//在新的线程中创建Looper实例
Looper.prepare();
//创建handler对象的实例,用于处理发过来的消息
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
//下面是判断质数的方法
if(msg.what==0x123){
int upper=msg.getData().getInt(NUM);
List<Integer> nums=new ArrayList<>();
outer:
for(int i=2;i<=upper;i++){
for(int j=2;j<=Math.sqrt(i);j++){
if(i!=2&&i%j==0){
continue outer;
}
}
//把质数存入到nums的List中
nums.add(i);
}
Toast.makeText(Main2Activity.this,nums.toString(),Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
}
}
Handler:它的作用是有两个,一个是发送消息和处理消息,在线程中使用Handler的步骤如下:
1:调用Looper的prepare发法为当前的线程创建looper对像,这时它的构造器就会创建了与之配套的MessageQueue
2:有了looper之后,创建Handler之类的实例,重写handlerMessage()发法,该方法负责处理来着其他线程的消息
3:调用Loop的loop()方法启动Looper
注意:1:在UI的线程中,已经初始化了一个Looper的对象,所以程序中直接创建Handler对象就可以通过Handler直接发送信息和接收信息了
2:而上面的例子中,就要自己创建Looper对象了