package com.example.shujie.helloworld2;
import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
public class CalPrime extends Activity {
static final String UPPER_NUM="upper";
EditText etNum;
CalThread calThread;
class CalThread extends Thread{
android.os.Handler mHandler;
@Override
public void run() {
Looper.prepare();
mHandler=new android.os.Handler(){
@Override
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<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);
Button bn=(Button)findViewById(R.id.button);
calThread = new CalThread();
calThread.start();
bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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);
}
});
}
}
<?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"
android:gravity="center_horizontal">
<EditText
android:id="@+id/etNum"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>