标签:
唔,来自疯狂安卓这本书
首先自己建个布局
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/etNum" android:hint="input" android:selectAllOnFocus="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按下去" android:id="@+id/btn"/> </LinearLayout>
然后去主文件
package com.example.deemo; 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; public class MainActivity extends Activity { static final String UPPER_NUM = "upper"; EditText etNum; CalThread calThread; private Button button; //定义一个线程类 class CalThread extends Thread{ public Handler mHandler; public void run(){//执行方法 Looper.prepare(); mHandler = new 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 <= Math.sqrt(i); j++) { if(i != 2 && i%j ==0){ continue outer; } } nums.add(i); } Toast.makeText(MainActivity.this, nums.toString(), Toast.LENGTH_LONG).show();; } } }; Looper.loop(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etNum = (EditText) findViewById(R.id.etNum); calThread = new CalThread(); calThread.start();//启动新线程 initClick();//点击事件 } private void initClick() { button = (Button) findViewById(R.id.btn); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //创建消息 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); } }); } }
本来这个线程想干点别的,太晚了就按书上栗子吧~
最最简单的多线程处理吧大概,反正UI主线程不能有别的请求,避免异常。所以网络啊啥的扔到别的线程里面。
标签:
原文地址:http://www.cnblogs.com/webgavin/p/5820251.html