軟件-camera final-計算機軟件及應(yīng)用-IT計算機-專業(yè)資料_第1頁
軟件-camera final-計算機軟件及應(yīng)用-IT計算機-專業(yè)資料_第2頁
軟件-camera final-計算機軟件及應(yīng)用-IT計算機-專業(yè)資料_第3頁
軟件-camera final-計算機軟件及應(yīng)用-IT計算機-專業(yè)資料_第4頁
軟件-camera final-計算機軟件及應(yīng)用-IT計算機-專業(yè)資料_第5頁
已閱讀5頁,還剩32頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

Camera

TheAndroidframeworkincludessupportforvariouscamerasandcamerafeaturesavailableon

devices,allowingyoutocapturepicturesandvideosinyourapplications.Thisdocument

discussesaquick,simpleapproachtoimageandvideocaptureandoutlinesanadvancedapproach

forcreatingcustomcameraexperiencesforyourusers.

Android框架包含了對多種camera的支持以及設(shè)備上可用的camera功能,允許你在應(yīng)用程

序中捕捉圖片和視頻文件。本文檔將討論一個簡單快速的圖像及視頻的捕獲方式并會概述一

種高級的方法來為你的用戶創(chuàng)建自定義的camera體驗。

Considerations

BeforeenablingyourapplicationtousecamerasonAndroiddevices,youshouldconsiderafew

questionsabouthowyourappintendstousethishardwarefeature.

在開始讓應(yīng)用程序使用Android設(shè)備上的cameras之前,你應(yīng)當考慮一些關(guān)于應(yīng)用程序計劃

如何使用這一硬件特性的諸多問題。

CameraRequirement-Istheuseofacamerasoimportanttoyourapplicationthatyoudo

notwantyourapplicationinstalledonadevicethatdoesnothaveacamera?Ifso,youshould

declarethecamerarequirementinyourmanifest.

Camera需求?對你的應(yīng)用程序而言使用一個camera是否非常重要以至于你并不期望

應(yīng)用程序被安裝到一個沒有camera的設(shè)備上?如果是,你應(yīng)當在你的清單文件中聲明

camera需求

QuickPictureorCustomizedCamera-Howwillyourapplicationusethecamera?Areyou

justinterestedinsnappingaquickpictureorvideoclip,orwillyourapplicationprovidea

newwaytousecameras?Foragettingaquicksnaporclip,considerUsingExistingCamera

Apps.Fordevelopingacustomizedcamerafeature,checkouttheBuildingaCameraApp

section.

快拍或自定義的camera-你的應(yīng)用程序?qū)绾问褂胏amera?是不是你只是對拍攝一

張照片或視頻剪輯感興趣,還是你的應(yīng)用程序?qū)峁┮粋€新的使用cameras的方式?

對于快拍或剪輯而言,請查看UsingExistingCameraApps的內(nèi)容。對于開發(fā)一個自定

義的camera功能而言,請查看BuildingaCameraApp章節(jié)。

Storage-Aretheimagesorvideosyourapplicationgeneratesintendedtobeonlyvisibleto

yourapplicationorsharedsothatotherapplicationssuchasGalleryorothermediaandsocial

appscanusethem?Doyouwantthepicturesandvideostobeavailableevenifyour

applicationisuninstalled?CheckouttheSavingMediaFilessectiontoseehowtoimplement

theseoptions.

存儲?應(yīng)用程序生成的照片或視頻是打算僅對你的應(yīng)用程序可用還是共享這樣其他的

應(yīng)用程序諸如Gallery或其他的媒體或社交類應(yīng)用程序也可以使用它們?你想讓圖片

和視頻一直可用就算你的應(yīng)用程序被卸載了也依舊如此么?查看SavingMediaFiles章

節(jié)以查看如何實現(xiàn)這些選項。

TheBasics

TheAndroidframeworksupportscapturingimagesandvideothroughthe

android.hardware.camera2APIorcameraIntent.Herearetherelevantclasses:

Android框架通過android.hardware.camera2API或camera意圖來支持照片和視頻的捕獲。這

里是相關(guān)的類:

android.hardware.camera2

ThispackageistheprimaryAPIforcontrollingdevicecameras.Itcanbeusedtotake

picturesorvideoswhenyouarebuildingacameraapplication.

對于控制設(shè)備相機而言此包是主要的APL當你正構(gòu)建一個camera應(yīng)用程序時它可以

用于獲取圖片或視頻。

Camera

ThisclassistheolderdeprecatedAPIfbrcontrollingdevicecameras.

對于控制設(shè)備相機而言該類是棄用的舊版APL

SurfaceView

Thisclassisusedtopresentalivecamerapreviewtotheuser.

該類用于為用戶提供一個現(xiàn)場攝像頭預(yù)覽。

MediaRecorder

Thisclassisusedtorecordvideofromthecamera.

該類用于使用camera錄制視頻。

Intent

AnintentactiontypeofMediaStore.ACTIONIMAGECAPTUREor

MediaStore.ACTIONVIDEOCAPTUREcanbeusedtocaptureimagesorvideoswithout

directlyusingtheCameraobject.

一個可被用于捕獲照片或視頻而不用直接使用Camera類對象的

MediaStore.ACTION_IMAGE_CAPTURE或MediaStore.ACTION_VIDEO_CAPTURE意

圖動作類型

ManifestDeclarations

BeforestartingdevelopmentonyourapplicationwiththeCameraAPI,youshouldmakesureyour

manifesthastheappropriatedeclarationstoallowuseofcamerahardwareandotherrelated

features.

在開始使用相機API開發(fā)應(yīng)用程序之前,你應(yīng)該確保清單文件中有允許使用camera硬件及

其他相關(guān)特性的合理聲明。

CameraPermission-Yourapplicationmustrequestpennissiontouseadevicecamera.

相機權(quán)限?你的應(yīng)用程序必須請求使用設(shè)備相機的權(quán)限

<uses-permissionandroid:name="android.permission.CAMERA”/>

Note:Ifyouareusingthecameraviaanintent,yourapplicationdoesnotneedtorequestthis

pennission.

注意:如果你正通過?個Intent來使用camera的話,你的應(yīng)用程序并不需要請求該權(quán)限。

CameraFeatures-Yourapplicationmustalsodeclareuseofcamerafeatures,fbrexample:

相機特性?你的應(yīng)用程序也必須聲明使用camera特性。例如:

<uses-featureandroid:name="android.hardware.camera"/>

Foralistofcamerafeatures,seethemanifestFeaturesReference.

查看camera功能列表,查看清單FeaturesReferenceo

AddingcamerafeaturestoyourmanifestcausesGooglePlaytopreventyourapplicationfrom

beinginstalledtodevicesthatdonotincludeacameraordonotsupportthecamerafeaturesyou

specify.Formoreinformationaboutusingfeature-basedfilteringwithGooglePlay,seeGoogle

PlayandFeature-BasedFiltering.

添加camera功能到你的清單文件會阻止谷歌GooglePlay在不包含camera或不支持你指定

的camera特性的設(shè)備上安裝你的應(yīng)用程序。關(guān)于使用GooglePlay基于特性的過濾的更多信

息,請查看GooglePlayandFeature-BasedFilteringo

Ifyourapplicationcanuseacameraorcamerafeaturefbrproperoperation,butdoesnotrequireit,

youshouldspecifythisinthemanifestbyincludingtheandroid:requiredattribute,andsettingitto

false:

如果你的應(yīng)用程序可以正確使用一個camera或camera特性的操作,但并不作要求時,你應(yīng)

該在清單文件中通過包含android:required屬性來指明它,并設(shè)置為false:

<uses-featureandroid:name="android.hardware.camera'*android:required=Hfalse"/>

StoragePermission-Ifyourapplicationsavesimagesorvideostothedevice*sexternalstorage

(SDCard),youmustalsospecifythisinthemanifest.

存儲權(quán)限-如果你的應(yīng)用程序?qū)⒈4鎴D片或視頻到設(shè)備的擴展存儲(SDCard),你必須也

得在清單文件中指明.

<uses-permissionandroid:name=nandroid.pennission.WRITEEXTERNALSTORAGE"/>

AudioRecordingPermission-Forrecordingaudiowithvideocapture,yourapplicationmust

requesttheaudiocapturepermission.

音頻錄制權(quán)限-對于錄制音頻的視頻捕獲,你的應(yīng)用程序必須請求音頻捕獲權(quán)限。

<uses-permissionandroid:name=,,android.permission.RECORDAUDIOn/>

LocationPermission-IfyourapplicationtagsimageswithGPSlocationinformation,youmust

requestlocationpermission:

定位權(quán)限-如果你的應(yīng)用程序使用GPS定位信息標記圖片?,你必須請求定位權(quán)限:

<uses-permissionandroid:name=nandroid.permission.ACCESSFINELOCATIONn/>

Formoreinfonnationaboutgettinguserlocation,seeLocationStrategies.

關(guān)于獲取用戶地理位置的更多信息,請查看LocationStrategieso

UsingExistingCameraApps

Aquickwaytoenabletakingpicturesorvideosinyourapplicationwithoutalotofextracodeis

touseanIntenttoinvokeanexistingAndroidcameraapplication.Acameraintentmakesarequest

tocaptureapictureorvideoclipthroughanexistingcameraappandthenreturnscontrolbackto

yourapplication.Thissectionshowsyouhowtocaptureanimageorvideousingthistechnique.

在你的應(yīng)用程序中捕獲照片或視頻而不用很多額外代碼的?個捷徑是使用一個Intent來激

活一個已經(jīng)存在的Android相機應(yīng)用。一個camera意圖會傳遞一個照片捕獲或視頻剪輯的

請求到?個已存在的應(yīng)用并在之后返回控制到你的應(yīng)用程序。這部分會教你如何使用這種技

術(shù)捕獲照片或視頻。

Theprocedurefbrinvokingacameraintentfollowsthesegeneralsteps:

激活一個相機意圖的過程遵照如下通用步驟:

1.ComposeaCameraIntent-CreateanIntentthatrequestsanimageorvideo,usingoneof

theseintenttypes:

組成一個Camera意圖?使用如下意圖類型之?來創(chuàng)建一個請求照片或視頻的Intent:

MediaStore.ACTIONIMAGECAPTURE-Intentactiontypefbrrequestinganimagefroman

existingcameraapplication.

MediaStore.ACTION」MAGE_CAPTURE-從某個已存在的camera應(yīng)用請求一張照片的意

圖動作類型

MediaStore.ACTION_VIDEO_CAPTURE-Intentactiontypefbrrequestingavideofroman

existingcameraapplication.

從一個已存在的camera應(yīng)用請求一個視頻文件的意圖動作類型。

2.StarttheCameraIntent-UsethestartActivityForResult()methodtoexecutethecameraintent.

Afteryoustarttheintent,theCameraapplicationuserinterfaceappearsonthedevicescreenand

theusercantakeapictureorvideo.

發(fā)送Camera意圖■使用startActivityForResult。方法來執(zhí)行camera意圖。發(fā)送camera意圖

之后,Camera應(yīng)用程序用戶界面會出現(xiàn)在設(shè)備屏幕上,用戶可以捕獲一張照片或視頻。

3.ReceivetheIntentResult-SetupanonActivityResult。methodinyourapplicationtoreceive

thecallbackanddatafromthecameraintent.Whentheuserfinishestakingapictureorvideo(or

cancelstheoperation),thesystemcallsthismethod.

接受意圖結(jié)果-在你的應(yīng)用程序中建立?個onActivityResult。方法以接受來自camera意圖

的回調(diào)及數(shù)據(jù)。當用戶完成了照片或視頻捕獲(或返回該操作)操作后,系統(tǒng)會調(diào)用該方法。

Imagecaptureintent

Capturingimagesusingacameraintentisquickwaytoenableyourapplicationtotakepictures

withminimalcoding.Animagecaptureintentcanincludethefollowingextrainformation:

使用carmera意圖的圖像捕獲是讓應(yīng)用程序用最少量代碼獲取照片的捷徑。一個圖片捕獲意

圖可以包含如下額外的信息:

MediaStore.EXTRAOUTPUT-ThissettingrequiresaUriobjectspecifyingapathandfilename

whereyou'dliketosavethepicture.Thissettingisoptionalbutstronglyrecommended.Ifyoudo

notspecifythisvalue,thecameraapplicationsavestherequestedpictureinthedefaultlocation

withadefaultname,specifiedinthereturnedintentsIntent.getData()field.

MediaStore.EXTRA_OUTPUT-該設(shè)置需要一個指定照片保存的路徑及文件名的Uri對象。

該設(shè)置是可選的但是強烈建議使用。如果你確實沒有指定該值,camera應(yīng)用會在返回意圖

的Intent.getData()字段中指定的默認路徑及文件名處保存該請求的圖片。

Thefollowingexampledemonstrateshowtoconstructaimagecaptureintentandexecuteit.The

getOutputMediaFileUri()methodinthisexamplereferstothesamplecodeshowninSaving

MediaFiles.

如下示例示范了如何構(gòu)造一個圖片捕獲意圖并執(zhí)行它。在該示例中的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。方法被執(zhí)行后,用戶會看到一個相機應(yīng)用界面。在用戶完成拍照(或

取消了該操作)之后,用戶界面會返回到你的應(yīng)用程序,且你必須攔截onActivityResult()

方法以接受意圖結(jié)果并繼續(xù)應(yīng)用程序的執(zhí)行。關(guān)于如何接收已完成意圖的更多信息,請查看

Receivingcameraintentresulto

Videocaptureintent

Capturingvideousingacameraintentisaquickwaytoenableyourapplicationtotakevideos

withminimalcoding.Avideocaptureintentcanincludethefollowingextrainformation:

使用camera意圖捕獲視頻是讓你的應(yīng)用程序以最少量代碼捕獲視頻的捷徑。一個視頻捕獲

意圖可以包含如下的額外信息:

MediaStore.EXTRAOUTPUT-ThissettingrequiresaUrispecifyingapathandfilenamewhere

you'dliketosavethevideo.Thissettingisoptionalbutstronglyrecommended.Ifyoudonot

specifythisvalue,theCameraapplicationsavestherequestedvideointhedefaultlocationwitha

defaultname,specifiedinthereturnedintent'sIntent.getData()field.

MediaStore.EXTRA_OUTPUT-該設(shè)置需要一個指定該視頻文件保存的路徑及文件名的Uri

對象。該設(shè)置是可選的但強烈建議使用。如果你確實沒有指定該值,Camera應(yīng)用程序會以

返回意圖的Intent.getData()字段中指定的默認路徑及文件名保存該請求的視頻文件。

MediaStore.EXTRAVIDEOQUALITY-Thisvaluecanbe0forlowestqualityandsmallestfile

sizeor1forhighestqualityandlargerfilesize.

MediaStore.EXTRA_VIDEO_QUALITY-該值可以是對應(yīng)最低質(zhì)量與最小文件尺寸的0或

對應(yīng)最高質(zhì)量與最大文件尺寸的1

MediaStore.EXTRADURATlONLIMIT-Setthisvaluetolimitthelength,inseconds,ofthe

videobeingcaptured.

MediaStore.EXTRA_DURATlON_LIMIT-設(shè)置該值以限制被捕獲視頻的長度,單位為秒。

MediaStore.EXTRASIZELIMIT-Setthisvaluetolimitthefilesize,inbytes,ofthevideobeing

captured.

MediaStore.EXTRA_SlZE_LIMIT-設(shè)置該值以限制被捕獲視頻的文件大小,單位為字節(jié)。

Thefollowingexampledemonstrateshowtoconstructavideocaptureintentandexecuteit.The

getOutputMediaFileUri()methodinthisexamplereferstothesamplecodeshowninSaving

MediaFiles.

如下示例示范了如何構(gòu)造一個視頻捕獲意圖并執(zhí)行它。該示例中的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。方法被執(zhí)行后,用戶會看到一個camera應(yīng)用程序的修改界面。在

用戶完成視頻捕獲(或取消了該操作)后,用戶界面會返回到你的應(yīng)用程序,你必須攔截

onActivityResu%方法以接受該意圖的結(jié)果并繼續(xù)應(yīng)用程序的執(zhí)行。關(guān)于如何接受已完成意

圖的更多信息,查看下一個章節(jié)。

接受camera意圖結(jié)果

Onceyouhaveconstructedandexecutedanimageorvideocameraintent,yourapplicationmust

beconfiguredtoreceivetheresultoftheintent.Thissectionshowsyouhowtointerceptthe

callbackfromacameraintentsoyourapplicationcandofurtherprocessingofthecapturedimage

orvideo.

一旦你構(gòu)造并執(zhí)行了一個圖像或視頻camera意圖,你必須配置應(yīng)用程序以接受該意圖的結(jié)

果。這部分會教你如何攔截來自一個camera意圖的回調(diào)這樣你的應(yīng)用程序就可以進一步處

理捕獲的圖像或視頻。

Inordertoreceivetheresultofanintent,youmustoverridetheonActivityResult()intheactivity

thatstartedtheintent.ThefollowingexampledemonstrateshowtooverrideonActivityResult()to

capturetheresultoftheimagecameraintentorvideocameraintentexamplesshowninthe

previoussections.

為了接受某個Intent結(jié)果,必須重寫activity中啟動該意圖的onActivityResult()方法。如下

示例示范了如何重寫onActivityResult()方法來捕獲以上章節(jié)中給出的圖像camera意圖或視

頻camera意圖例子的結(jié)果。

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接受到一個成功的結(jié)果,應(yīng)用程序可在指定的位置訪問被捕獲的圖像或視

頻。

BuildingaCameraApp

Somedevelopersmayrequireacamerauserinterfacethatiscustomizedtothelookoftheir

applicationorprovidesspecialfeatures.Creatingacustomizedcameraactivityrequiresmorecode

thanusinganintent,butitcanprovideamorecompellingexperienceforyourusers.

一些開發(fā)者可能需要一個針對應(yīng)用程序外觀而定制的或提供特定功能的camera用戶界面。

創(chuàng)建一個自定義的cameraactivity比使用一個意圖需要更多的代碼,但是這可以為你的用戶

提供更引人注目的體驗。

Note:Thefollowingguideisfortheolder,deprecatedCameraAPI.Forneworadvancedcamera

applications,thenewerandroid.hardware.camera2APIisrecommended.

注意:如下指南對應(yīng)于舊版本的,廢棄的CameraAPI。對于新版本的或高級的camera應(yīng)用

程序而言,推薦較新的android.hardware.camera2APL

Thegeneralstepsfbrcreatingacustomcamerainterfaceforyourapplicationareasfollows:

為應(yīng)用程序創(chuàng)建?個自定義的camera界面的?般步驟如下所示:

DetectandAccessCamera-Createcodetocheckfortheexistenceofcamerasandrequest

access.

檢測并訪問Camera-創(chuàng)建代碼來檢測cameras的存在性并請求訪問

CreateaPreviewClass-CreateacamerapreviewclassthatextendsSurfaceViewand

implementstheSurfaceHoiderinterface.Thisclasspreviewstheliveimagesfromthecamera.

創(chuàng)建一個預(yù)覽類-創(chuàng)建,個繼承SurfaceView類并實現(xiàn)了接口SurfaceHoider的camera預(yù)

覽類。該類將預(yù)覽camera的現(xiàn)場圖片。

BuildaPreviewLayout-Onceyouhavethecamerapreviewclass,createaviewlayoutthat

incorporatesthepreviewandtheuserinterfacecontrolsyouwant.

構(gòu)建一個預(yù)覽布周?一旦你創(chuàng)建了camera預(yù)覽類,創(chuàng)建一個包含了預(yù)覽及你期望的用戶界

面控件的視圖布局。

SetupListenersforCapture-Connectlistenersfbryourinterfacecontrolstostartimageorvideo

captureinresponsetouseractions,suchaspressingabutton.

對捕捉設(shè)置監(jiān)聽器?為開啟圖像或視頻捕獲對界面控件連接監(jiān)聽器以響應(yīng)用戶動作,諸如

按下一個按鈕。

CaptureandSaveFiles-Setupthecodefbrcapturingpicturesorvideosandsavingtheoutput.

捕獲并保存文件-設(shè)置捕獲圖片或視頻并保存輸出結(jié)果的代碼。

ReleasetheCamera-Afterusingthecamera,yourapplicationmustproperlyreleaseitfbruseby

otherapplications.

釋放Camera-你的應(yīng)用程序必須在camera使用完畢之后正確釋放它以供其他的應(yīng)用程序使

用。

Camerahardwareisasharedresourcethatmustbecarefullymanagedsoyourapplicationdoesnot

collidewithotherapplicationsthatmayalsowanttouseit.Thefollowingsectionsdiscusseshow

todetectcamerahardware,howtorequestaccesstoacamera,howtocapturepicturesorvideo

andhowtoreleasethecamerawhenyourapplicationisdoneusingit.

相機硬件是必須被小心管理這樣你的應(yīng)用程序就不會同其他也想要使用相機的應(yīng)用程序沖

突的一個共享資源。如下的章節(jié)會討論如何檢測相機硬件,如何請求訪問camera,如何捕

獲照片或視頻以及在你的應(yīng)用程序完成camera的使用后如何釋放它。

Caution:RemembertoreleasetheCameraobjectbycallingtheCamera.release()whenyour

applicationisdoneusingit!Ifyourapplicationdoesnotproperlyreleasethecamera,all

subsequentattemptstoaccessthecamera,includingthosebyyourownapplication,willfailand

maycauseyourorotherapplicationstobeshutdown.

警告:當你的應(yīng)用程序完成camera的使用時記得通過調(diào)用Camera.reslease。以釋放Camera

對象!如果你的應(yīng)用程序沒有合理地釋放camera,所有的訪問該camera的后續(xù)嘗試,包括

你的應(yīng)用程序的,都會失敗并可能導(dǎo)致你的或其他的應(yīng)用程序被關(guān)閉。

檢測相機硬件

Ifyourapplicationdoesnotspecificallyrequireacamerausingamanifestdeclaration,youshould

checktoseeifacameraisavailableatruntime.Toperformthischeck,usethe

PackageManager.hasSystemFeature()method,asshownintheexamplecodebelow:

如果你的應(yīng)用程序并沒有使用清單文件聲明明確地請求一個camera,那么你應(yīng)該在運行時

檢查看看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設(shè)備可以有多個cameras,例如一個用于攝影的后置camera及一個用于視頻電話的

前置cameraoAndroid2.3(APILevel9)及以上允許你使用Camera.getNumberOfCameras()

方法檢查設(shè)備上可用的camera的數(shù)量。

相機訪問

Ifyouhavedeterminedthatthedeviceonwhichyourapplicationisrunninghasacamera,you

mustrequesttoaccessitbygettinganinstanceofCamera(unlessyouareusinganintenttoaccess

thecamera).

如果你已經(jīng)確定了正運行應(yīng)用程序的設(shè)備上含有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在使用中或并不存在時未

檢查異常會導(dǎo)致你的應(yīng)用程序被系統(tǒng)關(guān)閉。

OndevicesrunningAndroid2.3(APILevel9)orhigher,youcanaccessspecificcamerasusing

Camera.open(int).Theexamplecodeabovewillaccessthefirst,back-facingcameraonadevice

withmorethanonecamera.

在運行Android2.3(APILevel9)或更高平臺的設(shè)備上,你可以使用Camera.open(int)方法

訪問指定的相機。在有一個以上的camera的設(shè)備上,上面的示例代碼將會訪問第一個

camera,后置camerao

Checkingcamerafeatures

Onceyouobtainaccesstoacamera,youcangetfurtherinformationaboutitscapabilitiesusing

theCamera.getParameters()methodandcheckingthereturnedCamera.Parametersobjectfor

supportedcapabilities.WhenusingAPILevel9orhigher,usetheCamera.getCameraInfb()to

determineifacameraisonthefrontorbackofthedevice,andtheorientationoftheimage.

一旦你獲得對某個camera的訪問,你可以使用Camera.getParameters()方法來獲取更多它的

功能相關(guān)信息并檢查返回的Camera.Parameters對象支持的功能。當使用9或更高的API

LevelR'J',使用Camera.getCameralnfo。方法來確定設(shè)備上的一個camera是前置的還是后置

的,以及圖像的方向。

GreatingapreviewcIass

Foruserstoeffectivelytakepicturesorvideo,theymustbeabletoseewhatthedevicecamera

sees.AcamerapreviewclassisaSurfaceViewthatcandisplaytheliveimagedatacomingfroma

camera,souserscanframeandcaptureapictureorvideo.

用戶要有效地捕獲照片或視頻,那么他們必須能夠看到設(shè)備相機所看到的。camera預(yù)覽類

是一個可以顯示來自某個camera現(xiàn)場圖像數(shù)據(jù)的SurfaceView,這樣用戶就可以frame并捕

獲一個照片或視頻了。

Thefollowingexamplecodedemonstrateshowtocreateabasiccamerapreviewclassthatcanbe

includedinaViewlayout.ThisclassimplementsSurfaceHolder.Callbackinordertocapturethe

callbackeventsforcreatinganddestroyingtheview,whichareneededforassigningthecamera

previewinput.

如下的示例代碼示范了如何創(chuàng)建一個基本的可被包含到一個View布局中的camera預(yù)覽類。

該類實現(xiàn)了SurfaceHolder.Callback以捕獲view的創(chuàng)建或銷毀所對應(yīng)的回調(diào)事件,這對于設(shè)

定camera預(yù)覽輸入而言是必需的。

/**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預(yù)覽設(shè)置一個指定的大小,在surfaceChanged。方法中設(shè)置它,就像上

面注釋中的那樣。當設(shè)置預(yù)覽尺寸時,你必須使用getSupportedPreviewSizes()方法所給定的

值。不要在setPreviewSize。方法中設(shè)置任何值。

PlacingpreviewinaIayout

Acamerapreviewclass,suchastheexampleshownintheprevioussection,mustbeplacedinthe

layoutofanactivityalongwithotheruserinterfacecontrolsfortakingapictureorvideo.This

sectionshowsyouhowtobuildabasiclayoutandactivityforthepreview.

一個camera預(yù)覽類,諸如如上章節(jié)中展示的示例那樣,必須同其他的捕獲照片或視頻的用

戶界面控件一?塊被放置到一個activity的布局中。這部分會教你如何為預(yù)覽構(gòu)建一個基本的

布局及activityo

Thefollowinglayoutcodeprovidesaverybasicviewthatcanbeusedtodisplayacamera

preview.Inthisexample,theFrameLayoutelementismeanttobethecontainerforthecamera

previewclass.Thislayouttypeisusedsothatadditionalpictureinformationorcontrolscanbe

overlayedonthelivecamerapreviewimages.

如下的布局代碼提供了一個非常基本的可被用于顯示一個camera預(yù)覽的view。在該示例中,

FrameLayout標簽是camera預(yù)覽類的容器。使用該布局類型則額外的圖片信息或控制就可

以被覆蓋到現(xiàn)場的camera預(yù)覽圖片上。

<?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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論