在作界面時候,咱們常常用到button,可是好多時候咱們直接把響應事件寫在在了Onclick函數裏面。可是這樣作的壞處就是佔用了ui線程。若是是請求數據庫或者是進行網絡數據請求,那麼這樣作可能會有點得不償失。android
Button testButton = new Button(this);數據庫
testButton .setOnClickListener(new OnclickListener(){
public void onClick(View view){網絡
// do something異步
}
});ide
因此在UI處理的時候,咱們應該儘可能作到異步處理。也就是起咱們本身的處理線程。函數
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.widget.*;ui
import com.sc.lib.Base64;
import com.sc.lib.ui.BusyDialog;
import com.sc.netvision.TopCommander;
import com.sc.netvision.Utils;
import com.sc.netvision.xml.*;this
public class videoPlay extends LinearLayout implements
Runnable ,View.OnClickListener{
private VideoView mPlayer = null;
private String path = null;
private Button playButton = null;
private BusyDialog dlgBusy = null;
private final int FAILCONNECTSERVER = 1;
private final int PLAYMEDIAVIEW = 20;
public ClipVideoPlay( Context context, String loadPath) {
super(context);
initial( context);
path = loadPaht;
}
private Handler uiHandler = new Handler() {
public void handleMessage(Message msg) {
try {
switch (msg.what) {
case FAILCONNECTSERVER:
Toast.makeText(currentContext, "Can not connect to server",
Toast.LENGTH_SHORT).show();
break;
case PLAYMEDIAVIEW:
playMedia(currentContext);
default:
super.handleMessage(msg);
break;
}
} finally {
dlgBusy.cancel();
}
}
};
public void onClick(View view) {
// TODO Auto-generated method stub
isPlay = false;
if(view == playButton) {
dlgBusy = BusyDialog.showBusyDialog(currentContext, "Please wait", "Returning ...");
new Thread(this).start();
}
}
public void run() {
// TODO Auto-generated method stub
Message msg = new Message();
try {
msg.what = PLAYMEDIAVIEW;
} finally {
uiHandler.sendMessage(msg);
}
}
private void initial( Context context) {
setOrientation(VERTICAL);
currentContext = context;
clipList = clips;
deviceName = devName;
playButton = new Button(context);
playButton.setOnClickListener(this);
path = URL;
mPlayer = new VideoView(context);
addView(playButton,new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
addView(addPlayTitle(context));
addView(mPlayer,new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
setGravity(Gravity.CENTER);
}
private void playMedia(Context context) {
String uriPath = path ;
Uri uri = Uri.parse(uriPath);
MediaController controller = new MediaController(context);
controller.show();
mPlayer.setMediaController(controller);
mPlayer.setVideoURI(uri);
mPlayer.requestFocus();
mPlayer.start();
}spa
}.net
代碼不能直接運行。 可是思想是這個思想。另起一個線程去獲取網絡數據,進行播放。這樣能夠快速響應事件。