Android开发实现录屏小功能
最近开发中,要实现录屏功能,查阅相关资料,发现调用MediaProjectionManager的api实现录屏功能即可:
importandroid.Manifest; importandroid.app.Activity; importandroid.content.Context; importandroid.content.Intent; importandroid.content.pm.PackageManager; importandroid.media.projection.MediaProjectionManager; importandroid.os.Build; importandroid.os.Bundle; importandroid.util.DisplayMetrics; importandroid.util.Log; publicclassRecordScreenActivityextendsActivity{ privatebooleanisRecord=false; privateintmScreenWidth; privateintmScreenHeight; privateintmScreenDensity; privateintREQUEST_CODE_PERMISSION_STORAGE=100; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); requestPermission(); getScreenBaseInfo(); startScreenRecord(); } @Override protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){ super.onActivityResult(requestCode,resultCode,data); if(requestCode==1000){ if(resultCode==RESULT_OK){ //获得录屏权限,启动Service进行录制 Intentintent=newIntent(this,ScreenRecordService.class); intent.putExtra("resultCode",resultCode); intent.putExtra("resultData",data); intent.putExtra("mScreenWidth",mScreenWidth); intent.putExtra("mScreenHeight",mScreenHeight); intent.putExtra("mScreenDensity",mScreenDensity); startService(intent); finish(); } } } //startscreenrecord privatevoidstartScreenRecord(){ //ManagestheretrievalofcertaintypesofMediaProjectiontokens. MediaProjectionManagermediaProjectionManager= (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE); //ReturnsanIntentthatmustpassedtostartActivityForResult()inordertostartscreencapture. IntentpermissionIntent=mediaProjectionManager.createScreenCaptureIntent(); startActivityForResult(permissionIntent,1000); } /** *获取屏幕基本信息 */ privatevoidgetScreenBaseInfo(){ //Astructuredescribinggeneralinformationaboutadisplay,suchasitssize,density,andfontscaling. DisplayMetricsmetrics=newDisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); mScreenWidth=metrics.widthPixels; mScreenHeight=metrics.heightPixels; mScreenDensity=metrics.densityDpi; } @Override protectedvoidonDestroy(){ super.onDestroy(); } privatevoidrequestPermission(){ if(Build.VERSION.SDK_INT>=23){ String[]permissions={ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA }; for(Stringstr:permissions){ if(this.checkSelfPermission(str)!=PackageManager.PERMISSION_GRANTED){ this.requestPermissions(permissions,REQUEST_CODE_PERMISSION_STORAGE); return; } } } } @Override publicvoidonRequestPermissionsResult(intrequestCode,String[]permissions,int[]grantResults){ super.onRequestPermissionsResult(requestCode,permissions,grantResults); if(requestCode==REQUEST_CODE_PERMISSION_STORAGE){ startScreenRecord(); } } }
service里面进行相关录制工作
importandroid.app.Service; importandroid.content.Context; importandroid.content.Intent; importandroid.hardware.display.DisplayManager; importandroid.hardware.display.VirtualDisplay; importandroid.media.MediaRecorder; importandroid.media.projection.MediaProjection; importandroid.media.projection.MediaProjectionManager; importandroid.os.Environment; importandroid.os.IBinder; importandroid.support.annotation.Nullable; importandroid.util.Log; importjava.text.SimpleDateFormat; importjava.util.Date; /** *Createdbydzjinon2018/1/9. */ publicclassScreenRecordServiceextendsService{ privateintresultCode; privateIntentresultData=null; privateMediaProjectionmediaProjection=null; privateMediaRecordermediaRecorder=null; privateVirtualDisplayvirtualDisplay=null; privateintmScreenWidth; privateintmScreenHeight; privateintmScreenDensity; privateContextcontext=null; @Override publicvoidonCreate(){ super.onCreate(); } /** *CalledbythesystemeverytimeaclientexplicitlystartstheservicebycallingstartService(Intent), *providingtheargumentsitsuppliedandauniqueintegertokenrepresentingthestartrequest. *Donotcallthismethoddirectly. *@paramintent *@paramflags *@paramstartId *@return */ @Override publicintonStartCommand(Intentintent,intflags,intstartId){ try{ resultCode=intent.getIntExtra("resultCode",-1); resultData=intent.getParcelableExtra("resultData"); mScreenWidth=intent.getIntExtra("mScreenWidth",0); mScreenHeight=intent.getIntExtra("mScreenHeight",0); mScreenDensity=intent.getIntExtra("mScreenDensity",0); mediaProjection=createMediaProjection(); mediaRecorder=createMediaRecorder(); virtualDisplay=createVirtualDisplay(); mediaRecorder.start(); }catch(Exceptione){ e.printStackTrace(); } /** *START_NOT_STICKY: *ConstanttoreturnfromonStartCommand(Intent,int,int):ifthisservice'sprocessis *killedwhileitisstarted(afterreturningfromonStartCommand(Intent,int,int)), *andtherearenonewstartintentstodelivertoit,thentaketheserviceoutofthe *startedstateanddon'trecreateuntilafutureexplicitcalltoContext.startService(Intent). *TheservicewillnotreceiveaonStartCommand(Intent,int,int)callwithanullIntent *becauseitwillnotbere-startediftherearenopendingIntentstodeliver. */ returnService.START_NOT_STICKY; } //createMediaProjection publicMediaProjectioncreateMediaProjection(){ /** *UsewithgetSystemService(Class)toretrieveaMediaProjectionManagerinstancefor *managingmediaprojectionsessions. */ return((MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE)) .getMediaProjection(resultCode,resultData); /** *RetrievetheMediaProjectionobtainedfromasuccesfulscreencapturerequest. *WillbenulliftheresultfromthestartActivityForResult()isanythingotherthanRESULT_OK. */ } privateMediaRecordercreateMediaRecorder(){ SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); StringfilePathName=Environment.getExternalStorageDirectory()+"/"+simpleDateFormat.format(newDate())+".mp4"; //Usedtorecordaudioandvideo.Therecordingcontrolisbasedonasimplestatemachine. MediaRecordermediaRecorder=newMediaRecorder(); //Setthevideosourcetobeusedforrecording. mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); //Settheformatoftheoutputproducedduringrecording. //3GPPmediafileformat mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); //Setsthevideoencodingbitrateforrecording. //param:thevideoencodingbitrateinbitspersecond. mediaRecorder.setVideoEncodingBitRate(5*mScreenWidth*mScreenHeight); //Setsthevideoencodertobeusedforrecording. mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); //Setsthewidthandheightofthevideotobecaptured. mediaRecorder.setVideoSize(mScreenWidth,mScreenHeight); //Setstheframerateofthevideotobecaptured. mediaRecorder.setVideoFrameRate(60); try{ //Passinthefileobjecttobewritten. mediaRecorder.setOutputFile(filePathName); //Preparestherecordertobegincapturingandencodingdata. mediaRecorder.prepare(); }catch(Exceptione){ e.printStackTrace(); } returnmediaRecorder; } privateVirtualDisplaycreateVirtualDisplay(){ /** *nameString:Thenameofthevirtualdisplay,mustbenon-empty.Thisvaluemustneverbenull. widthint:Thewidthofthevirtualdisplayinpixels.Mustbegreaterthan0. heightint:Theheightofthevirtualdisplayinpixels.Mustbegreaterthan0. dpiint:Thedensityofthevirtualdisplayindpi.Mustbegreaterthan0. flagsint:Acombinationofvirtualdisplayflags.SeeDisplayManagerforthefulllistofflags. surfaceSurface:Thesurfacetowhichthecontentofthevirtualdisplayshouldberendered,ornullifthereisnoneinitially. callbackVirtualDisplay.Callback:Callbacktocallwhenthevirtualdisplay'sstatechanges,ornullifnone. handlerHandler:TheHandleronwhichthecallbackshouldbeinvoked,ornullifthecallbackshouldbeinvokedonthecallingthread'smainLooper. */ /** *DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR *Virtualdisplayflag:Allowscontenttobemirroredonprivatedisplayswhennocontentisbeingshown. */ returnmediaProjection.createVirtualDisplay("mediaProjection",mScreenWidth,mScreenHeight,mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mediaRecorder.getSurface(),null,null); } @Override publicvoidonDestroy(){ super.onDestroy(); if(virtualDisplay!=null){ virtualDisplay.release(); virtualDisplay=null; } if(mediaRecorder!=null){ mediaRecorder.stop(); mediaRecorder=null; } if(mediaProjection!=null){ mediaProjection.stop(); mediaProjection=null; } } @Nullable @Override publicIBinderonBind(Intentintent){ returnnull; } }
录屏功能就这么实现了,有什么不妥之处,敬请留言讨论。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。