Looper 没个线程都只有一个Looper 负责管理MessageQueue,不断从中读取Message,并交给Hanlder处理
MssageQueue Looper管理里,先进先出
Handler 消息发送给MessageQueue,并可以处理Looper分给的信息
1,调用Looper.prepare() 创建当前线程的Looper,MessageQueue会被Looper的构造器直接创建配套的。
2,创建Handler子类,重写handlerMessage() ,处理消息
3,Looper.loop() 启动Looper。
这是疯狂android上的例子 计算质数
<?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/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numeric="integer" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提交" />
</LinearLayout>
package main;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.calprime.R;
public class Main extends Activity implements OnClickListener
{
public CalThread cal;
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cal = new CalThread();
et = (EditText)findViewById(R.id.edittext);
new Thread(cal).start();
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(this);
}
public void onClick(View source)
{
Message msg = new Message();
msg.what = 123;
Bundle b = new Bundle();
b.putInt("NUM", Integer.parseInt(et.getText().toString()));
msg.setData(b);
cal.h.sendMessage(msg);
}
class CalThread implements Runnable
{
public Handler h;
public CalThread()
{
// TODO Auto-generated constructor stub
}
@Override
public void run()
{
// TODO Auto-generated method stub
Looper.prepare();
h = new Handler()
{
@Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == 123)
{
int upper = msg.getData().getInt("NUM");
List<Integer> nums = new ArrayList<Integer>();
for(int i = 2;i<=upper;i++)
{
if(isPrime(i))
{
nums.add(i);
}
}
Toast.makeText(Main.this, nums.toString(), Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
public boolean isPrime(int num)
{
for(int i=2;i<Math.sqrt(num);i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
}
}
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name="main.Main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>