Android 线程模型
1.
import android.os.Handler;
import android.os.Message;
public class MainActivity extends Activity
{
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what)
{
case 1:
//Code Run In UI Thread
break;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button=(Button)findViewById(R.id.button);
Thread thread=new Thread(new Runnable()
{
@Override
public void run()
{
//Code Run In Thread
Message message=new Message();
message.what=1;
mHandler.sendMessage(message);
}
});
thread.start();
}
}
2.
Activity currentActivity = ContextUtils.getCurrentActivity();
final Handler handler = new Handler(currentActivity.getMainLooper());
(new Thread(new Runnable() {
public void run() {
//Code Run In Thread
handler.post(new Runnable() {
public void run() {
//Code Run In UI Thread
}
});
}
})).start();