先介绍和handler一起工作的几个组件
Handler的方法介绍
代码示例
package liu.peng.weather;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private int imageIds[] = new int[]{R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher,R.drawable.ic_launcher};
private int currentId = 0;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.image);
final Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
image.setImageResource(imageIds[currentId++%imageIds.length]);
}
}
};
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myHandler.sendEmptyMessage(0x123);
}
}, 0,1200);
}
}
另外一个代码示例
package liu.peng.weather;
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.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
static final String UPPER_NUM = "upper";
EditText edit;
CalThread calThread;
class CalThread extends Thread{
public Handler myHandler;
@Override
public void run() {
Looper.prepare();
myHandler = new Handler(){
public void handleMessage(android.os.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);
edit = (EditText)findViewById(R.id.edit);
calThread.start();
}
public void cal(View source){
Message msg = new Message();
msg.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM,Integer.parseInt(edit.getText().toString()));
msg.setData(bundle);
calThread.myHandler.sendMessage(msg);
}
}