版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Camera
TheAndroidframeworkincludessupportforvariouscamerasandcamerafeaturesavailableon
devices,allowingyoutocapturepicturesandvideosinyourapplications.Thisdocument
discussesaquick,simpleapproachtoimageandvideocaptureandoutlinesanadvancedapproach
forcreatingcustomcameraexperiencesforyourusers.
Android框架包含了对多种camera的支持以及设备上可用的camera功能,允许你在应用程
序中捕捉图片和视频文件。本文档将讨论一个简单快速的图像及视频的捕获方式并会概述一
种高级的方法来为你的用户创建自定义的camera体验。
Considerations
BeforeenablingyourapplicationtousecamerasonAndroiddevices,youshouldconsiderafew
questionsabouthowyourappintendstousethishardwarefeature.
在开始让应用程序使用Android设备上的cameras之前,你应当考虑一些关于应用程序计划
如何使用这一硬件特性的诸多问题。
CameraRequirement-Istheuseofacamerasoimportanttoyourapplicationthatyoudo
notwantyourapplicationinstalledonadevicethatdoesnothaveacamera?Ifso,youshould
declarethecamerarequirementinyourmanifest.
Camera需求・对你的应用程序而言使用一个camera是否非常重要以至于你并不期望
应用程序被安装到一个没有camera的设备上?如果是,你应当在你的清单文件中声明
camera需求
QuickPictureorCustomizedCamera-Howwillyourapplicationusethecamera?Areyou
justinterestedinsnappingaquickpictureorvideoclip,orwillyourapplicationprovidea
newwaytousecameras?Foragettingaquicksnaporclip,considerUsingExistingCamera
Apps.Fordevelopingacustomizedcamerafeature,checkouttheBuildingaCameraApp
section.
快拍或自定义的camera-你的应用程序将会如何使用camera?是不是你只是对拍摄一
张照片或视频剪辑感兴趣,还是你的应用程序将会提供一个新的使用cameras的方式?
对于快拍或剪辑而言,请查看UsingExistingCameraApps的内容。对于开发一个自定
义的camera功能而言,请查看BuildingaCameraApp章节。
Storage-Aretheimagesorvideosyourapplicationgeneratesintendedtobeonlyvisibleto
yourapplicationorsharedsothatotherapplicationssuchasGalleryorothermediaandsocial
appscanusethem?Doyouwantthepicturesandvideostobeavailableevenifyour
applicationisuninstalled?CheckouttheSavingMediaFilessectiontoseehowtoimplement
theseoptions.
存储•应用程序生成的照片或视频是打算仅对你的应用程序可用还是共享这样其他的
应用程序诸如Gallery或其他的媒体或社交类应用程序也可以使用它们?你想让图片
和视频一直可用就算你的应用程序被卸载了也依旧如此么?查看SavingMediaFiles章
节以查看如何实现这些选项。
TheBasics
TheAndroidframeworksupportscapturingimagesandvideothroughthe
android.hardware.camera2APIorcameraIntent.Herearetherelevantclasses:
Android框架通过android.hardware.camera2API或camera意图来支持照片和视频的捕获。这
里是相关的类:
android.hardware.camera2
ThispackageistheprimaryAPIforcontrollingdevicecameras.Itcanbeusedtotake
picturesorvideoswhenyouarebuildingacameraapplication.
对于控制设备相机而言此包是主要的APL当你正构建一个camera应用程序时它可以
用于获取图片或视频。
Camera
ThisclassistheolderdeprecatedAPIfbrcontrollingdevicecameras.
对于控制设备相机而言该类是弃用的旧版APL
SurfaceView
Thisclassisusedtopresentalivecamerapreviewtotheuser.
该类用于为用户提供一个现场摄像头预览。
MediaRecorder
Thisclassisusedtorecordvideofromthecamera.
该类用于使用camera录制视频。
Intent
AnintentactiontypeofMediaStore.ACTIONIMAGECAPTUREor
MediaStore.ACTIONVIDEOCAPTUREcanbeusedtocaptureimagesorvideoswithout
directlyusingtheCameraobject.
一个可被用于捕获照片或视频而不用直接使用Camera类对象的
MediaStore.ACTION_IMAGE_CAPTURE或MediaStore.ACTION_VIDEO_CAPTURE意
图动作类型
ManifestDeclarations
BeforestartingdevelopmentonyourapplicationwiththeCameraAPI,youshouldmakesureyour
manifesthastheappropriatedeclarationstoallowuseofcamerahardwareandotherrelated
features.
在开始使用相机API开发应用程序之前,你应该确保清单文件中有允许使用camera硬件及
其他相关特性的合理声明。
CameraPermission-Yourapplicationmustrequestpennissiontouseadevicecamera.
相机权限・你的应用程序必须请求使用设备相机的权限
<uses-permissionandroid:name="android.permission.CAMERA”/>
Note:Ifyouareusingthecameraviaanintent,yourapplicationdoesnotneedtorequestthis
pennission.
注意:如果你正通过•个Intent来使用camera的话,你的应用程序并不需要请求该权限。
CameraFeatures-Yourapplicationmustalsodeclareuseofcamerafeatures,fbrexample:
相机特性•你的应用程序也必须声明使用camera特性。例如:
<uses-featureandroid:name="android.hardware.camera"/>
Foralistofcamerafeatures,seethemanifestFeaturesReference.
查看camera功能列表,查看清单FeaturesReferenceo
AddingcamerafeaturestoyourmanifestcausesGooglePlaytopreventyourapplicationfrom
beinginstalledtodevicesthatdonotincludeacameraordonotsupportthecamerafeaturesyou
specify.Formoreinformationaboutusingfeature-basedfilteringwithGooglePlay,seeGoogle
PlayandFeature-BasedFiltering.
添加camera功能到你的清单文件会阻止谷歌GooglePlay在不包含camera或不支持你指定
的camera特性的设备上安装你的应用程序。关于使用GooglePlay基于特性的过滤的更多信
息,请查看GooglePlayandFeature-BasedFilteringo
Ifyourapplicationcanuseacameraorcamerafeaturefbrproperoperation,butdoesnotrequireit,
youshouldspecifythisinthemanifestbyincludingtheandroid:requiredattribute,andsettingitto
false:
如果你的应用程序可以正确使用一个camera或camera特性的操作,但并不作要求时,你应
该在清单文件中通过包含android:required属性来指明它,并设置为false:
<uses-featureandroid:name="android.hardware.camera'*android:required=Hfalse"/>
StoragePermission-Ifyourapplicationsavesimagesorvideostothedevice*sexternalstorage
(SDCard),youmustalsospecifythisinthemanifest.
存储权限-如果你的应用程序将保存图片或视频到设备的扩展存储(SDCard),你必须也
得在清单文件中指明.
<uses-permissionandroid:name=nandroid.pennission.WRITEEXTERNALSTORAGE"/>
AudioRecordingPermission-Forrecordingaudiowithvideocapture,yourapplicationmust
requesttheaudiocapturepermission.
音频录制权限-对于录制音频的视频捕获,你的应用程序必须请求音频捕获权限。
<uses-permissionandroid:name=,,android.permission.RECORDAUDIOn/>
LocationPermission-IfyourapplicationtagsimageswithGPSlocationinformation,youmust
requestlocationpermission:
定位权限-如果你的应用程序使用GPS定位信息标记图片•,你必须请求定位权限:
<uses-permissionandroid:name=nandroid.permission.ACCESSFINELOCATIONn/>
Formoreinfonnationaboutgettinguserlocation,seeLocationStrategies.
关于获取用户地理位置的更多信息,请查看LocationStrategieso
UsingExistingCameraApps
Aquickwaytoenabletakingpicturesorvideosinyourapplicationwithoutalotofextracodeis
touseanIntenttoinvokeanexistingAndroidcameraapplication.Acameraintentmakesarequest
tocaptureapictureorvideoclipthroughanexistingcameraappandthenreturnscontrolbackto
yourapplication.Thissectionshowsyouhowtocaptureanimageorvideousingthistechnique.
在你的应用程序中捕获照片或视频而不用很多额外代码的•个捷径是使用一个Intent来激
活一个已经存在的Android相机应用。一个camera意图会传递一个照片捕获或视频剪辑的
请求到•个已存在的应用并在之后返回控制到你的应用程序。这部分会教你如何使用这种技
术捕获照片或视频。
Theprocedurefbrinvokingacameraintentfollowsthesegeneralsteps:
激活一个相机意图的过程遵照如下通用步骤:
1.ComposeaCameraIntent-CreateanIntentthatrequestsanimageorvideo,usingoneof
theseintenttypes:
组成一个Camera意图・使用如下意图类型之•来创建一个请求照片或视频的Intent:
MediaStore.ACTIONIMAGECAPTURE-Intentactiontypefbrrequestinganimagefroman
existingcameraapplication.
MediaStore.ACTION」MAGE_CAPTURE-从某个已存在的camera应用请求一张照片的意
图动作类型
MediaStore.ACTION_VIDEO_CAPTURE-Intentactiontypefbrrequestingavideofroman
existingcameraapplication.
从一个已存在的camera应用请求一个视频文件的意图动作类型。
2.StarttheCameraIntent-UsethestartActivityForResult()methodtoexecutethecameraintent.
Afteryoustarttheintent,theCameraapplicationuserinterfaceappearsonthedevicescreenand
theusercantakeapictureorvideo.
发送Camera意图■使用startActivityForResult。方法来执行camera意图。发送camera意图
之后,Camera应用程序用户界面会出现在设备屏幕上,用户可以捕获一张照片或视频。
3.ReceivetheIntentResult-SetupanonActivityResult。methodinyourapplicationtoreceive
thecallbackanddatafromthecameraintent.Whentheuserfinishestakingapictureorvideo(or
cancelstheoperation),thesystemcallsthismethod.
接受意图结果-在你的应用程序中建立•个onActivityResult。方法以接受来自camera意图
的回调及数据。当用户完成了照片或视频捕获(或返回该操作)操作后,系统会调用该方法。
Imagecaptureintent
Capturingimagesusingacameraintentisquickwaytoenableyourapplicationtotakepictures
withminimalcoding.Animagecaptureintentcanincludethefollowingextrainformation:
使用carmera意图的图像捕获是让应用程序用最少量代码获取照片的捷径。一个图片捕获意
图可以包含如下额外的信息:
MediaStore.EXTRAOUTPUT-ThissettingrequiresaUriobjectspecifyingapathandfilename
whereyou'dliketosavethepicture.Thissettingisoptionalbutstronglyrecommended.Ifyoudo
notspecifythisvalue,thecameraapplicationsavestherequestedpictureinthedefaultlocation
withadefaultname,specifiedinthereturnedintentsIntent.getData()field.
MediaStore.EXTRA_OUTPUT-该设置需要一个指定照片保存的路径及文件名的Uri对象。
该设置是可选的但是强烈建议使用。如果你确实没有指定该值,camera应用会在返回意图
的Intent.getData()字段中指定的默认路径及文件名处保存该请求的图片。
Thefollowingexampledemonstrateshowtoconstructaimagecaptureintentandexecuteit.The
getOutputMediaFileUri()methodinthisexamplereferstothesamplecodeshowninSaving
MediaFiles.
如下示例示范了如何构造一个图片捕获意图并执行它。在该示例中的getOutputMediaFilellriO
方法参考在SavingMediaFiles中给出的示例代码。
privatestaticfinalintCAPTURE_IMAGE_ACTIVITY_REQUEST_CODE=100;
privateUrifileUri;
@Override
publicvoidonCreate(BundlesavedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.main);
//createIntenttotakeapictureandreturncontroltothecallingapplication
Intentintent=newIntent(MediaStore.ACTIONIMAGECAPTURE);
fileUri=getOutputMediaFileUri(MEDlATYPEIMAGE);//createafiletosavetheimage
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//settheimagefilename
//starttheimagecaptureIntent
startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
WhenthestartActivityForResult()methodisexecuted,usersseeacameraapplicationinterface.
Aftertheuserfinishestakingapicture(orcancelstheoperation),theuserinterfacereturnstoyour
application,andyoumustintercepttheonActivityResult()methodtoreceivetheresultofthe
intentandcontinueyourapplicationexecution.Forinformationonhowtoreceivethecompleted
intent,seeReceivingcameraintentresult.
当startActivityForResult。方法被执行后,用户会看到一个相机应用界面。在用户完成拍照(或
取消了该操作)之后,用户界面会返回到你的应用程序,且你必须拦截onActivityResult()
方法以接受意图结果并继续应用程序的执行。关于如何接收已完成意图的更多信息,请查看
Receivingcameraintentresulto
Videocaptureintent
Capturingvideousingacameraintentisaquickwaytoenableyourapplicationtotakevideos
withminimalcoding.Avideocaptureintentcanincludethefollowingextrainformation:
使用camera意图捕获视频是让你的应用程序以最少量代码捕获视频的捷径。一个视频捕获
意图可以包含如下的额外信息:
MediaStore.EXTRAOUTPUT-ThissettingrequiresaUrispecifyingapathandfilenamewhere
you'dliketosavethevideo.Thissettingisoptionalbutstronglyrecommended.Ifyoudonot
specifythisvalue,theCameraapplicationsavestherequestedvideointhedefaultlocationwitha
defaultname,specifiedinthereturnedintent'sIntent.getData()field.
MediaStore.EXTRA_OUTPUT-该设置需要一个指定该视频文件保存的路径及文件名的Uri
对象。该设置是可选的但强烈建议使用。如果你确实没有指定该值,Camera应用程序会以
返回意图的Intent.getData()字段中指定的默认路径及文件名保存该请求的视频文件。
MediaStore.EXTRAVIDEOQUALITY-Thisvaluecanbe0forlowestqualityandsmallestfile
sizeor1forhighestqualityandlargerfilesize.
MediaStore.EXTRA_VIDEO_QUALITY-该值可以是对应最低质量与最小文件尺寸的0或
对应最高质量与最大文件尺寸的1
MediaStore.EXTRADURATlONLIMIT-Setthisvaluetolimitthelength,inseconds,ofthe
videobeingcaptured.
MediaStore.EXTRA_DURATlON_LIMIT-设置该值以限制被捕获视频的长度,单位为秒。
MediaStore.EXTRASIZELIMIT-Setthisvaluetolimitthefilesize,inbytes,ofthevideobeing
captured.
MediaStore.EXTRA_SlZE_LIMIT-设置该值以限制被捕获视频的文件大小,单位为字节。
Thefollowingexampledemonstrateshowtoconstructavideocaptureintentandexecuteit.The
getOutputMediaFileUri()methodinthisexamplereferstothesamplecodeshowninSaving
MediaFiles.
如下示例示范了如何构造一个视频捕获意图并执行它。该示例中的getOutputMediaFileUri()
方法参考SavingMediaFiles给出的示例代码。
privatestaticfinalintCAPTURE_VIDEO_ACTIVITY_REQUEST_CODE=200;
privateUrifileUri;
@Override
publicvoidonCreate(BundlesavedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.main);
//createnewIntent
Intentintent=newIntent(MediaStore.ACTIONVIDEOCAPTURE);
fileUri=getOutputMediaFileUri(MEDIATYPEVIDEO);//createafiletosavethevideo
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//settheimagefilename
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);//setthevideoimagequalityto
high
//starttheVideoCaptureIntent
startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
WhenthestartActivityForResult()methodisexecuted,usersseeamodifiedcameraapplication
interface.Aftertheuserfinishestakingavideo(orcancelstheoperation),theuserinterface
returnstoyourapplication,andyoumustintercepttheonActivityResult()methodtoreceivethe
resultoftheintentandcontinueyourapplicationexecution.Forinformationonhowtoreceivethe
completedintent,seethenextsection.
当startActivityForResult。方法被执行后,用户会看到一个camera应用程序的修改界面。在
用户完成视频捕获(或取消了该操作)后,用户界面会返回到你的应用程序,你必须拦截
onActivityResu%方法以接受该意图的结果并继续应用程序的执行。关于如何接受已完成意
图的更多信息,查看下一个章节。
接受camera意图结果
Onceyouhaveconstructedandexecutedanimageorvideocameraintent,yourapplicationmust
beconfiguredtoreceivetheresultoftheintent.Thissectionshowsyouhowtointerceptthe
callbackfromacameraintentsoyourapplicationcandofurtherprocessingofthecapturedimage
orvideo.
一旦你构造并执行了一个图像或视频camera意图,你必须配置应用程序以接受该意图的结
果。这部分会教你如何拦截来自一个camera意图的回调这样你的应用程序就可以进一步处
理捕获的图像或视频。
Inordertoreceivetheresultofanintent,youmustoverridetheonActivityResult()intheactivity
thatstartedtheintent.ThefollowingexampledemonstrateshowtooverrideonActivityResult()to
capturetheresultoftheimagecameraintentorvideocameraintentexamplesshowninthe
previoussections.
为了接受某个Intent结果,必须重写activity中启动该意图的onActivityResult()方法。如下
示例示范了如何重写onActivityResult()方法来捕获以上章节中给出的图像camera意图或视
频camera意图例子的结果。
privatestaticfinalintCAPTUREJMAGE_ACTIVITY_REQUEST_CODE=100;
privatestaticfinalintCAPTURE_VIDEO_ACTIVITY_REQUEST_CODE=200;
©Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
if(requestCode=CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
if(resultCode==RESULT_OK){
//ImagecapturedandsavedtofileUrispecifiedintheIntent
Toast.makeText(this,''Imagesavedto:\nn+
data.getData(),Toast.LENGTH_LONG).show();
}elseif(resultCode=RESULTCANCELED){
//Usercancelledtheimagecapture
}else{
//Imagecapturefailed,adviseuser
if(requestCode==CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE){
if(resultCode==RESULT_OK){
//VideocapturedandsavedtofileUrispecifiedintheIntent
Toast.makeText(this,MVideosavedto:\n"+
data.getData(),Toast.LENGTH_LONG).show();
}elseif(resultCode=RESULT_CANCELED){
//Usercancelledthevideocapture
}else{
//Videocapturefailed,adviseuser
}
)
Onceyouractivityreceivesasuccessfulresult,thecapturedimageorvideoisavailableinthe
specifiedlocationforyourapplicationtoaccess.
一旦你的activity接受到一个成功的结果,应用程序可在指定的位置访问被捕获的图像或视
频。
BuildingaCameraApp
Somedevelopersmayrequireacamerauserinterfacethatiscustomizedtothelookoftheir
applicationorprovidesspecialfeatures.Creatingacustomizedcameraactivityrequiresmorecode
thanusinganintent,butitcanprovideamorecompellingexperienceforyourusers.
一些开发者可能需要一个针对应用程序外观而定制的或提供特定功能的camera用户界面。
创建一个自定义的cameraactivity比使用一个意图需要更多的代码,但是这可以为你的用户
提供更引人注目的体验。
Note:Thefollowingguideisfortheolder,deprecatedCameraAPI.Forneworadvancedcamera
applications,thenewerandroid.hardware.camera2APIisrecommended.
注意:如下指南对应于旧版本的,废弃的CameraAPI。对于新版本的或高级的camera应用
程序而言,推荐较新的android.hardware.camera2APL
Thegeneralstepsfbrcreatingacustomcamerainterfaceforyourapplicationareasfollows:
为应用程序创建•个自定义的camera界面的•般步骤如下所示:
DetectandAccessCamera-Createcodetocheckfortheexistenceofcamerasandrequest
access.
检测并访问Camera-创建代码来检测cameras的存在性并请求访问
CreateaPreviewClass-CreateacamerapreviewclassthatextendsSurfaceViewand
implementstheSurfaceHoiderinterface.Thisclasspreviewstheliveimagesfromthecamera.
创建一个预览类-创建,个继承SurfaceView类并实现了接口SurfaceHoider的camera预
览类。该类将预览camera的现场图片。
BuildaPreviewLayout-Onceyouhavethecamerapreviewclass,createaviewlayoutthat
incorporatesthepreviewandtheuserinterfacecontrolsyouwant.
构建一个预览布周・一旦你创建了camera预览类,创建一个包含了预览及你期望的用户界
面控件的视图布局。
SetupListenersforCapture-Connectlistenersfbryourinterfacecontrolstostartimageorvideo
captureinresponsetouseractions,suchaspressingabutton.
对捕捉设置监听器・为开启图像或视频捕获对界面控件连接监听器以响应用户动作,诸如
按下一个按钮。
CaptureandSaveFiles-Setupthecodefbrcapturingpicturesorvideosandsavingtheoutput.
捕获并保存文件-设置捕获图片或视频并保存输出结果的代码。
ReleasetheCamera-Afterusingthecamera,yourapplicationmustproperlyreleaseitfbruseby
otherapplications.
释放Camera-你的应用程序必须在camera使用完毕之后正确释放它以供其他的应用程序使
用。
Camerahardwareisasharedresourcethatmustbecarefullymanagedsoyourapplicationdoesnot
collidewithotherapplicationsthatmayalsowanttouseit.Thefollowingsectionsdiscusseshow
todetectcamerahardware,howtorequestaccesstoacamera,howtocapturepicturesorvideo
andhowtoreleasethecamerawhenyourapplicationisdoneusingit.
相机硬件是必须被小心管理这样你的应用程序就不会同其他也想要使用相机的应用程序冲
突的一个共享资源。如下的章节会讨论如何检测相机硬件,如何请求访问camera,如何捕
获照片或视频以及在你的应用程序完成camera的使用后如何释放它。
Caution:RemembertoreleasetheCameraobjectbycallingtheCamera.release()whenyour
applicationisdoneusingit!Ifyourapplicationdoesnotproperlyreleasethecamera,all
subsequentattemptstoaccessthecamera,includingthosebyyourownapplication,willfailand
maycauseyourorotherapplicationstobeshutdown.
警告:当你的应用程序完成camera的使用时记得通过调用Camera.reslease。以释放Camera
对象!如果你的应用程序没有合理地释放camera,所有的访问该camera的后续尝试,包括
你的应用程序的,都会失败并可能导致你的或其他的应用程序被关闭。
检测相机硬件
Ifyourapplicationdoesnotspecificallyrequireacamerausingamanifestdeclaration,youshould
checktoseeifacameraisavailableatruntime.Toperformthischeck,usethe
PackageManager.hasSystemFeature()method,asshownintheexamplecodebelow:
如果你的应用程序并没有使用清单文件声明明确地请求一个camera,那么你应该在运行时
检查看看camera是否是可用的。要完成该检查,使用PackageManager.hasSystemFeature(/
法,就像在下面的示例代码中展示的那样:
/**Checkifthisdevicehasacamera*/
privatebooleancheckCameraHardware(Contextcontext){
if(context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)){
//thisdevicehasacamera
returntrue;
}else{
//nocameraonthisdevice
returnfalse;
Androiddevicescanhavemultiplecameras,forexampleaback-facingcameraforphotography
andafront-facingcameraforvideocalls.Android2.3(APILevel9)andlaterallowsyoutocheck
thenumberofcamerasavailableonadeviceusingtheCamera.getNumberOfCameras()method.
Android设备可以有多个cameras,例如一个用于摄影的后置camera及一个用于视频电话的
前置cameraoAndroid2.3(APILevel9)及以上允许你使用Camera.getNumberOfCameras()
方法检查设备上可用的camera的数量。
相机访问
Ifyouhavedeterminedthatthedeviceonwhichyourapplicationisrunninghasacamera,you
mustrequesttoaccessitbygettinganinstanceofCamera(unlessyouareusinganintenttoaccess
thecamera).
如果你已经确定了正运行应用程序的设备上含有camera,你必须通过获取一个Camera实例
(除非你正使用一个意图来访为该camera)来请求对它的访问。
Toaccesstheprimarycamera,usetheCamera.open()methodandbesuretocatchanyexceptions,
asshowninthecodebelow:
要访问主camera,使用Camera.open。方法并确保捕获任何异常,就像下面的代码中展示的
那样:
/**AsafewaytogetaninstanceoftheCameraobject.*/
publicstaticCameragetCameraInstance(){
Camerac=null;
try{
c=Camera.open();//attempttogetaCamerainstance
}
catch(Exceptione){
//Cameraisnotavailable(inuseordoesnotexist)
}
returnc;//returnsnullifcameraisunavailable
)
Caution:AlwayscheckforexceptionswhenusingCamera.open().Failingtocheckforexceptions
ifthecameraisinuseordoesnotexistwillcauseyourapplicationtobeshutdownbythesystem.
警告:当使用Camera.open()方法时一定要检测异常。如果camera在使用中或并不存在时未
检查异常会导致你的应用程序被系统关闭。
OndevicesrunningAndroid2.3(APILevel9)orhigher,youcanaccessspecificcamerasusing
Camera.open(int).Theexamplecodeabovewillaccessthefirst,back-facingcameraonadevice
withmorethanonecamera.
在运行Android2.3(APILevel9)或更高平台的设备上,你可以使用Camera.open(int)方法
访问指定的相机。在有一个以上的camera的设备上,上面的示例代码将会访问第一个
camera,后置camerao
Checkingcamerafeatures
Onceyouobtainaccesstoacamera,youcangetfurtherinformationaboutitscapabilitiesusing
theCamera.getParameters()methodandcheckingthereturnedCamera.Parametersobjectfor
supportedcapabilities.WhenusingAPILevel9orhigher,usetheCamera.getCameraInfb()to
determineifacameraisonthefrontorbackofthedevice,andtheorientationoftheimage.
一旦你获得对某个camera的访问,你可以使用Camera.getParameters()方法来获取更多它的
功能相关信息并检查返回的Camera.Parameters对象支持的功能。当使用9或更高的API
LevelR'J',使用Camera.getCameralnfo。方法来确定设备上的一个camera是前置的还是后置
的,以及图像的方向。
GreatingapreviewcIass
Foruserstoeffectivelytakepicturesorvideo,theymustbeabletoseewhatthedevicecamera
sees.AcamerapreviewclassisaSurfaceViewthatcandisplaytheliveimagedatacomingfroma
camera,souserscanframeandcaptureapictureorvideo.
用户要有效地捕获照片或视频,那么他们必须能够看到设备相机所看到的。camera预览类
是一个可以显示来自某个camera现场图像数据的SurfaceView,这样用户就可以frame并捕
获一个照片或视频了。
Thefollowingexamplecodedemonstrateshowtocreateabasiccamerapreviewclassthatcanbe
includedinaViewlayout.ThisclassimplementsSurfaceHolder.Callbackinordertocapturethe
callbackeventsforcreatinganddestroyingtheview,whichareneededforassigningthecamera
previewinput.
如下的示例代码示范了如何创建一个基本的可被包含到一个View布局中的camera预览类。
该类实现了SurfaceHolder.Callback以捕获view的创建或销毁所对应的回调事件,这对于设
定camera预览输入而言是必需的。
/**AbasicCamerapreviewclass*/
publicclassCameraPreviewextendsSurfaceViewimplementsSurfaceHolder.Callback{
privateSurfaceHoldermHolder;
privateCameramCamera;
publicCameraPreview(Contextcontext,Cameracamera){
super(context);
mCamera=camera;
//InstallaSurfaceHolder.Callbacksowegetnotifiedwhenthe
//underlyingsurfaceiscreatedanddestroyed.
mHolder=getHolder();
mHolder.addCallback(this);
//deprecatedsetting,butrequiredonAndroidversionspriorto3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
)
publicvoidsurfaceCreated(SurfaceHolderholder){
//TheSurfacehasbeencreated,nowtellthecamerawheretodrawthepreview,
try(
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(lOExceptione){
Log.d(TAG,nErrorsettingcamerapreview:”+e.getMessage());
publicvoidsurfaceDestroyed(SurfaceHolderholder){
//empty.TakecareofreleasingtheCamerapreviewinyouractivity.
)
publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intw,inth){
//Ifyourpreviewcanchangeorrotate,takecareofthoseeventshere.
//Makesuretostopthepreviewbeforeresizingorreformattingit.
if(mHolder.getSurface()=null){
//previewsurfacedoesnotexist
return;
)
//stoppreviewbeforemakingchanges
try{
mCamera.stopPreview();
}catch(Exceptione){
//ignore:triedtostopanon-existentpreview
)
//setpreviewsizeandmakeanyresize,rotateor
//refbnnattingchangeshere
//startpreviewwithnewsettings
try(
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
}catch(Exceptione){
Log.d(TAG,nErrorstartingcamerapreview:”+e.getMessage());
Ifyouwanttosetaspecificsizeforyourcamerapreview,setthisinthesurfaceChanged()method
asnotedinthecommentsabove.Whensettingpreviewsize,youmustusevaluesfrom
getSupportedPreviewSizes().DonotsetarbitraryvaluesinthesetPreviewSize()method.
如果你想要为camera预览设置一个指定的大小,在surfaceChanged。方法中设置它,就像上
面注释中的那样。当设置预览尺寸时,你必须使用getSupportedPreviewSizes()方法所给定的
值。不要在setPreviewSize。方法中设置任何值。
PlacingpreviewinaIayout
Acamerapreviewclass,suchastheexampleshownintheprevioussection,mustbeplacedinthe
layoutofanactivityalongwithotheruserinterfacecontrolsfortakingapictureorvideo.This
sectionshowsyouhowtobuildabasiclayoutandactivityforthepreview.
一个camera预览类,诸如如上章节中展示的示例那样,必须同其他的捕获照片或视频的用
户界面控件一•块被放置到一个activity的布局中。这部分会教你如何为预览构建一个基本的
布局及activityo
Thefollowinglayoutcodeprovidesaverybasicviewthatcanbeusedtodisplayacamera
preview.Inthisexample,theFrameLayoutelementismeanttobethecontainerforthecamera
previewclass.Thislayouttypeisusedsothatadditionalpictureinformationorcontrolscanbe
overlayedonthelivecamerapreviewimages.
如下的布局代码提供了一个非常基本的可被用于显示一个camera预览的view。在该示例中,
FrameLayout标签是camera预览类的容器。使用该布局类型则额外的图片信息或控制就可
以被覆盖到现场的camera预览图片上。
<?xmlversion-11.0nencoding=,,utf-8H?>
<LinearLayoutxmlns:android=,,/apk/res/androidn
android:orientation=nhorizontar,
android:layout_width=nfill_parentn
android:layout_height=nfill_parentn
>
<FrameLayout
android:id="@+id/camera_preview"
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年江西省上饶市余干县数学六年级第一学期期末调研试题含解析
- 2024年江西省赣州市安远县数学六年级第一学期期末统考模拟试题含解析
- 2024年专用仪器仪表:化工仪表项目发展计划
- 2024年湖南省农业厅招聘人员历年高频500题难、易错点模拟试题附带答案详解
- 2024年湖南益阳市人力资源和社会保障局所属事业单位招聘历年高频500题难、易错点模拟试题附带答案详解
- 2024年湖南湘西州保靖县事业单位招聘工作人员141人高频500题难、易错点模拟试题附带答案详解
- 2024年湖南永州第三人民医院招聘历年高频500题难、易错点模拟试题附带答案详解
- 2024年湖南永州市城市社会经济调查队遴选2人历年高频500题难、易错点模拟试题附带答案详解
- 2024年湖南怀化市麻阳县招聘事业单位工作人员58人历年高频500题难、易错点模拟试题附带答案详解
- 2024年湖南张家界市食品药品检验所公益性岗位招聘历年高频500题难、易错点模拟试题附带答案详解
- 模板支撑工程危险源辩识与风险评价清单
- 银行融资贷款流程PPT课件
- 口腔生物学复习全新版整理
- 产品模拟召回方案
- 电镀锌原理及工艺流程56169
- 节假日公车封条模版
- 计量器具管理
- 室内装饰装修工程竣工报告
- 大体积混凝土测温记录
- 21剖宫产术前讨论术后审核制度
- 1重庆房屋建筑与装饰工程计价定额-建筑工程
评论
0/150
提交评论