main.xml
<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"
>
<EditText
android:id="@+id/etNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:phoneNumber="true"
/>
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="单击计算质数"
/>
</LinearLayout>
CalPrime.java
package com.example.handleexample;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class CalPrime extends Activity {
static final String UPPER_NUM = "upper";
EditText etNum;
Button bn;
CalThread calThread;
String num = null;
class CalThread extends Thread
{
public Handler mHandler;
public void run()
{
Looper.prepare();
mHandler = new Handler()
{
public void handleMessage(Message msg)
{
if(msg.what == 0x123)
{
int upper = msg.getData().getInt(UPPER_NUM);
List<Integer> nums = new ArrayList<Integer>();
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.add(i);
}
Toast.makeText(CalPrime.this, nums.toString(), Toast.LENGTH_LONG).show();
}
}
};
Looper.loop();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etNum = (EditText)findViewById(R.id.etNum);
bn = (Button)findViewById(R.id.bn);
bn.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
cal();
}
}
);
calThread = new CalThread();
calThread.start();
}
public void cal()
{
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM, Integer.parseInt(etNum.getText().toString()));
msg.setData(bundle);
calThread.mHandler.sendMessage(msg);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cal_prime, menu);
return true;
}
}