简述:
在Android开发中多线程很常用,这里实现一个雏形
知识点:
Handler作为主线程中一直跑的一部分,掌管了子线程对主UI线程的通信,比如要在子线程中修改某个界面元素,必须通过Message的发送,让Handler中得知需要修改,然后在Handler中该主线程的UI
简而言之,子线程不能直接改主线程UI(Activity UI),只能通过send一条message给Handler然后才能修改(个人理解,如果有错,欢迎指谪)
下面实现一个Thread,来达到多线程的雏形
代码:
主UI
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/myBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show dialog"
android:textSize="22dip"
/>
</RelativeLayout>
主界面的Activity
MainActivity.java
package com.atp.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import com.atp.R;
public class MainActivity extends Activity {
private Button myBtn = null;
private ProgressDialog progressDialog = null;
//use of Handler
//messge info
private static final int DISMISS_PROGRESS_DIALOG = 1;
Message message = null;
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case DISMISS_PROGRESS_DIALOG:
progressDialog.dismiss();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
myBtn = (Button) findViewById(R.id.myBtn);
myBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this, "请稍等...",
"加载中...", true);
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
message = handler.obtainMessage(DISMISS_PROGRESS_DIALOG);
handler.sendMessage(message);
}
}.start();
}
});
}
}
显示效果:
点击之后出现滚动条了,等到线程睡了2秒之后,子线程结束,主线程还原