MalCamera和Camera都继承了CameraView类并分别实现了commandAction()方法先来看一下MalCamera
以下是引用片段
/**
*MalCamerajava
*/
packagenjuhysteriathreadcamera;
importjavaxmicroeditionlcduiCommand;
importjavaxmicroeditionlcduiDisplayable;
importjadiaMediaException;
importjavaxmicroeditionmidletMIDlet;
/**
*ThisclassdisplaythemalcameraIncommandAction()
*forcapturecommandjustgetthedatawithoutcreatea
*newthreadandthuscauseprogramblocked
*@authorMagic
*
*/
publicclassMalCameraextendsCameraView{
publicMalCamera(MIDletmidlet){
super(midlet);
}
publicvoidcommandAction(CommandcmdDisplayabledisplayable){
if(cmd==exitCommand){
try{
playerstop();
}catch(MediaExceptione){
eprintStackTrace();
}
playerclose();
((MalCameraMidlet)midlet)destroyApp(false);
midletnotifyDestroyed();
}elseif(cmd==captureCommand){
//Donothandleinanewthread try{
byte[]data=vcgetSnapshot(null);
newSnapShot(midletdata);
}catch(MediaExceptione){
eprintStackTrace();
}
}
}
} 其中SnapShot是显示捕捉到的图像的界面详细请看文后的源代码这里不再赘述
现在运行MalCameraMidlet按下拍照命令后出现询问是否记录图像的提示但是当你按下Yes后程序就再也没有响应了如图所示
图
查看控制台窗口得到如下提示
以下是引用片段
Warning:Toavoidpotentialdeadlockoperationsthatmayblocksuchas
networkingshouldbeperformedinadifferentthreadthanthe
commandAction()handler
同样还是由于没有创建新的线程进行处理的原因下面我们就把处理的代码放到新的线程中来完成看看情况如何如下是修改过的MalCamera代码Camerajava:
以下是引用片段
/**
*Camerajava
*/
packagenjuhysteriathreadcamera;
importjavaxmicroeditionlcduiCommand;
importjavaxmicroeditionlcduiDisplayable;
importjadiaMediaException;
importjavaxmicroeditionmidletMIDlet;
/**
*ThisclassdisplayscameraAnddotherightthing
*forcapturecommandputtingcodeinanewthread
*@authorMagic
*
*/
publicclassCameraextendsCameraView{
publicCamera(MIDletmidlet){
super(midlet);
}
publicvoidcommandAction(CommandcmdDisplayabledisplayable){
if(cmd==exitCommand){
try{
playerstop();
}catch(MediaExceptione){
eprintStackTrace();
}
playerclose();
((CameraMidlet)midlet)destroyApp(false);
midletnotifyDestroyed();
}elseif(cmd==captureCommand){
//Handleinanewthread newThread(){
publicvoidrun(){
try{
byte[]data=vcgetSnapshot(null);
newSnapShot(midletdata);
}catch(MediaExceptione){
eprintStackTrace();
}
}
}start();
}
}
} 同样我们也需要在MIDlet中创建Camera的对象而不是MalCameraCameraMidlet的代码如下
以下是引用片段
/**
*CameraMidletjava
*/
packagenjuhysteriathreadcamera;
importjavaxmicroeditionlcduiDisplay;
importjavaxmicroeditionmidletMIDlet;
/**
*ThecorrectMIDlet
*@authorMagic
*
*/
publicclassCameraMidletextendsMIDlet{
protectedDisplaydisplay;
privateCameraViewcamera;
publicCameraMidlet(){
super();
display=DisplaygetDisplay(this);
}
protectedvoidstartApp(){
camera=newCamera(this);
displaysetCurrent(camera);
}
/**
*Showcurrentcamera
*/
publicvoidshowCamera(){
displaysetCurrent(camera);
}
protectedvoidpauseApp(){
}
protectedvoiddestroyApp(booleanarg){
}
} 运行CameraMidlet按下拍照命令这次程序没有堵塞我们可以得到捕捉到的图片如图所示
图