在做界面时候,我们经常用到button,但是好多时候我们直接把响应事件写在在了Onclick函数里面。但是这样做的坏处就是占用了ui线程。如果是请求数据库或者是进行网络数据请求,那么这样做可能会有点得不偿失。
Button testButton = new Button(this);
testButton .setOnClickListener(new OnclickListener(){
public void onClick(View view){// do something
}
});所以在UI处理的时候,我们应该尽量做到异步处理。也就是起我们自己的处理线程。
import android.content.*;
import android.graphics.*; import android.net.*; import android.os.Handler; import android.os.Message; import android.view.*; import android.widget.*;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.*;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(); }}
代码不能直接运行。 但是思想是这个思想。另起一个线程去获取网络数据,进行播放。这样可以快速响应事件。