亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android中怎么實現錄屏功能

發布時間:2021-08-09 17:06:04 來源:億速云 閱讀:150 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關android中怎么實現錄屏功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

1、mian.activity

package com.fpt.screenvideo;import android.content.Context;import android.content.Intent;import android.graphics.Color;import android.media.projection.MediaProjectionManager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.DisplayMetrics;import android.util.Log;import android.view.KeyEvent;import android.view.View;import android.widget.Button;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.RadioGroup;import android.widget.Toast;public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Button mTextView,off_btn; private static final String RECORD_STATUS = "record_status"; private static final int REQUEST_CODE = 1000; private int mScreenWidth; private int mScreenHeight; private int mScreenDensity; /** 是否已經開啟視頻錄制 */ private boolean isStarted = false; /** 是否為標清視頻 */ private boolean isVideoSd = true; /** 是否開啟音頻錄制 */ private boolean isAudio = true; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  Log.i(TAG, "onCreate");  if(savedInstanceState != null) {   isStarted = savedInstanceState.getBoolean(RECORD_STATUS);  }  getView() ;  getScreenBaseInfo(); } private void getView() {  mTextView = findViewById(R.id.button_control);  off_btn=findViewById(R.id.button_contro2);  off_btn.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View view) {////    Intent service = new Intent(this, ScreenRecordService.class);//    stopService(service);//    isStarted = !isStarted;   }  });  if(isStarted) {   statusIsStarted();  } else {   statusIsStoped();  }  mTextView.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    if(isStarted) {     stopScreenRecording();//功能     statusIsStoped();//僅僅是狀態     Log.i(TAG, "Stoped screen recording");    } else {     startScreenRecording();//功能    }   }  });  RadioGroup radioGroup = (RadioGroup) findViewById(R.id.redio_group);  radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {   @Override   public void onCheckedChanged(RadioGroup group, int checkedId) {    // TODO Auto-generated method stub    switch (checkedId) {     case R.id.sd_button:      isVideoSd = true;      break;     case R.id.hd_button:      isVideoSd = false;      break;     default:      break;    }   }  });  CheckBox audioBox = (CheckBox) findViewById(R.id.audio_check_box);  audioBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {   @Override   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {    // TODO Auto-generated method stub    isAudio = isChecked;   }  }); } /**  * 開啟屏幕錄制時的UI狀態  */ private void statusIsStarted() {  mTextView.setText("停止錄制");  mTextView.setBackgroundColor(Color.GREEN); } /**  * 結束屏幕錄制后的UI狀態  */ private void statusIsStoped() {  mTextView.setText("開始錄制");  mTextView.setBackgroundColor(Color.RED); } /**  * 獲取屏幕相關數據  */ private void getScreenBaseInfo() {  DisplayMetrics metrics = new DisplayMetrics();  getWindowManager().getDefaultDisplay().getMetrics(metrics);  mScreenWidth = metrics.widthPixels;  mScreenHeight = metrics.heightPixels;  mScreenDensity = metrics.densityDpi; } @Override protected void onSaveInstanceState(Bundle outState) {  // TODO Auto-generated method stub  super.onSaveInstanceState(outState);  outState.putBoolean(RECORD_STATUS, isStarted); } /**  * 獲取屏幕錄制的權限  */ private void startScreenRecording() {  // TODO Auto-generated method stub  MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);  Intent permissionIntent = mediaProjectionManager.createScreenCaptureIntent();  startActivityForResult(permissionIntent, REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {  // TODO Auto-generated method stub  super.onActivityResult(requestCode, resultCode, data);  if(requestCode == REQUEST_CODE) {   if(resultCode == RESULT_OK) {    // 獲得權限,啟動Service開始錄制    Intent service = new Intent(this, ScreenRecordService.class);    service.putExtra("code", resultCode);    service.putExtra("data", data);    service.putExtra("audio", isAudio);    service.putExtra("width", mScreenWidth);    service.putExtra("height", mScreenHeight);    service.putExtra("density", mScreenDensity);    service.putExtra("quality", isVideoSd);    startService(service);    // 已經開始屏幕錄制,修改UI狀態    isStarted = !isStarted;    statusIsStarted();//    simulateHome(); // this.finish(); // 可以直接關閉Activity    Log.i(TAG, "Started screen recording");   } else {    Toast.makeText(this, "跳出提示框", Toast.LENGTH_LONG).show();    Log.i(TAG, "User cancelled");   }  } } /**  * 關閉屏幕錄制,即停止錄制Service  */ private void stopScreenRecording() {  // TODO Auto-generated method stub  Intent service = new Intent(this, ScreenRecordService.class);  stopService(service);  isStarted = !isStarted; } /**  * 模擬HOME鍵返回桌面的功能  */ private void simulateHome() {  Intent intent = new Intent(Intent.ACTION_MAIN);  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  intent.addCategory(Intent.CATEGORY_HOME);  this.startActivity(intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) {  // 在這里將BACK鍵模擬了HOME鍵的返回桌面功能(并無必要)  if(keyCode == KeyEvent.KEYCODE_BACK) {   simulateHome();   return true;  }  return super.onKeyDown(keyCode, event); }}

2、ScreenRecordService

package com.fpt.screenvideo;import android.app.Service;import android.content.Context;import android.content.Intent;import android.hardware.display.DisplayManager;import android.hardware.display.VirtualDisplay;import android.media.MediaRecorder;import android.media.projection.MediaProjection;import android.media.projection.MediaProjectionManager;import android.os.Environment;import android.os.IBinder;import android.util.Log;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;public class ScreenRecordService extends Service { private static final String TAG = "ScreenRecordingService"; private int mScreenWidth; private int mScreenHeight; private int mScreenDensity; private int mResultCode; private Intent mResultData; /** 是否為標清視頻 */ private boolean isVideoSd; /** 是否開啟音頻錄制 */ private boolean isAudio; private MediaProjection mMediaProjection; private MediaRecorder mMediaRecorder; private VirtualDisplay mVirtualDisplay; @Override public void onCreate() {  // TODO Auto-generated method stub  super.onCreate();  Log.i(TAG, "Service onCreate() is called"); } @Override public int onStartCommand(Intent intent, int flags, int startId) {  // TODO Auto-generated method stub  Log.i(TAG, "Service onStartCommand() is called");  mResultCode = intent.getIntExtra("code", -1);  mResultData = intent.getParcelableExtra("data");  mScreenWidth = intent.getIntExtra("width", 720);  mScreenHeight = intent.getIntExtra("height", 1280);  mScreenDensity = intent.getIntExtra("density", 1);  isVideoSd = intent.getBooleanExtra("quality", true);  isAudio = intent.getBooleanExtra("audio", true);  mMediaProjection = createMediaProjection();  mMediaRecorder = createMediaRecorder();  mVirtualDisplay = createVirtualDisplay(); // 必須在mediaRecorder.prepare() 之后調用,否則報錯"fail to get surface"  mMediaRecorder.start();  return Service.START_NOT_STICKY; } private MediaProjection createMediaProjection() {  Log.i(TAG, "Create MediaProjection");  return ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).getMediaProjection(mResultCode, mResultData); } private MediaRecorder createMediaRecorder() {  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");  Date curDate = new Date(System.currentTimeMillis());  String curTime = formatter.format(curDate).replace(" ", "");  String videoQuality = "HD";  if(isVideoSd) videoQuality = "SD";  Log.i(TAG, "Create MediaRecorder");  MediaRecorder mediaRecorder = new MediaRecorder();//  if(isAudio) mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);  mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  mediaRecorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/" + videoQuality + curTime + ".mp4");  mediaRecorder.setVideoSize(mScreenWidth, mScreenHeight); //after setVideoSource(), setOutFormat()  mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); //after setOutputFormat()//  if(isAudio) mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //after setOutputFormat()  int bitRate;  if(isVideoSd) {   mediaRecorder.setVideoEncodingBitRate(mScreenWidth * mScreenHeight);   mediaRecorder.setVideoFrameRate(30);   bitRate = mScreenWidth * mScreenHeight / 1000;  } else {   mediaRecorder.setVideoEncodingBitRate(5 * mScreenWidth * mScreenHeight);   mediaRecorder.setVideoFrameRate(60); //after setVideoSource(), setOutFormat()   bitRate = 5 * mScreenWidth * mScreenHeight / 1000;  }  try {   mediaRecorder.prepare();  } catch (IllegalStateException | IOException e) {   // TODO Auto-generated catch block   e.printStackTrace();  }  Log.i(TAG, "Audio: " + isAudio + ", SD video: " + isVideoSd + ", BitRate: " + bitRate + "kbps");  return mediaRecorder; } private VirtualDisplay createVirtualDisplay() {  Log.i(TAG, "Create VirtualDisplay");  return mMediaProjection.createVirtualDisplay(TAG, mScreenWidth, mScreenHeight, mScreenDensity,    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null); } @Override public void onDestroy() {  // TODO Auto-generated method stub  super.onDestroy();  Log.i(TAG, "Service onDestroy");  if(mVirtualDisplay != null) {   mVirtualDisplay.release();   mVirtualDisplay = null;  }  if(mMediaRecorder != null) {   mMediaRecorder.setOnErrorListener(null);   mMediaProjection.stop();   mMediaRecorder.reset();  }  if(mMediaProjection != null) {   mMediaProjection.stop();   mMediaProjection = null;  } } @Override public IBinder onBind(Intent intent) {  // TODO Auto-generated method stub  return null; }}

3、androidManifest.xml權限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.RECORD_AUDIO" />

4、service的注冊

<service android:name=".ScreenRecordService"/>

看完上述內容,你們對android中怎么實現錄屏功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

郧西县| 汶上县| 青冈县| 清水河县| 龙山县| 汾西县| 旬阳县| 芜湖市| 延川县| 鲁甸县| 个旧市| 左贡县| 定结县| 雷山县| 中牟县| 平果县| 井冈山市| 亳州市| 宜兰县| 改则县| 桃江县| 莲花县| 云龙县| 天峨县| 车致| 自贡市| 泽州县| 苍梧县| 上杭县| 格尔木市| 洛宁县| 青川县| 墨脱县| 民和| 黄平县| 宁河县| 元氏县| 山阴县| 阳高县| 汉中市| 远安县|