안 드 로 이 드 미디어 레 코더 가 화면 을 녹음 할 때 녹음 기능 을 실현 합 니 다.

안 드 로 이 드 얘 기 좀 해 볼 게 요.
최근 에 도 수요 에 부 딪 혀 녹음 기능 을 사용 해 야 하 는 것 아 닙 니까?최근 에 도 만 났 습 니 다.지금 정리 하고 기록 하 세 요.
우선,녹음 화면 은 동적 권한 클래스 를 붙 일 수 있 는 권한 이 필요 합 니 다.

public class TalAllow {
  /**
   * RECORD_AUDIO         
   * WRITE_EXTERNAL_STORAGE     
   * CAMERA            
   */
  public static void requestPermissions(Context context,int allowCode) {
    ArrayList<String> ps = new ArrayList<>();
    int per = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO);
    if (per != PackageManager.PERMISSION_GRANTED) {
      ps.add(Manifest.permission.RECORD_AUDIO);
    }
    per = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (per != PackageManager.PERMISSION_GRANTED) {
      ps.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    per = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
    if (per != PackageManager.PERMISSION_GRANTED) {
      ps.add(Manifest.permission.CAMERA);
    }
    per = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
    if (per != PackageManager.PERMISSION_GRANTED) {
      ps.add(Manifest.permission.READ_PHONE_STATE);
    }
    Log.d(TAG, "requestPermissions:ps=" + ps.size());
    if (!ps.isEmpty()) {
      String[] ps3 = new String[ps.size()];
      ps.toArray(ps3);
      ActivityCompat.requestPermissions((Activity) context, ps3, allowCode);
    }
  }
}
판단 권한 이 필요 합 니 다.링크 삽입(위 에 있 는 코드 코드 는 100)
권한 여 부 를 판단 하 다
다음 포인트 가 왔 습 니 다.
우선 이 녹음 과 녹음 은 서비스 에서 하 는 것 이 므 로 서비스 류 를 붙 입 니 다.
이 코드 는 분명히 품질 이 있어 서 많은 처 리 를 했 습 니 다.다음 줄 에서 한 줄 씩 해석 하 겠 습 니 다.

//       Handle.Callback                 ,    HandleMessage  ,          {}               
public class TalScreenRecordService extends Service implements Handler.Callback {
//         log
  private static final String TAG = "TalScreenRecordService";
  //                       ,    ,
  //         ,code    data,  ActivityForResult     code
  private MediaProjectionManager mProjectionManager;
 //          
  private MediaProjection mMediaProjection;
  //                 
  private MediaRecorder mMediaRecorder;
  //                ,  ,      
  //          https://blog.csdn.net/qq_16628781/article/details/62038163
  private VirtualDisplay mVirtualDisplay;
 //       false     
  private boolean mIsRunning;
  //                 
  private int mRecordWidth = TalScreenParams.getScreenWidth();
  private int mRecordHeight = TalScreenParams.getScreenWidth();
  private int mScreenDpi = TalScreenParams.getScreenDpi();
 //code data            
  private int mResultCode;
  private Intent mResultData;
  //         
  private String mRecordFilePath;
  private Handler mHandler;
  //        
  private int mRecordSeconds = 0;
  //handle      what
  private static final int MSG_TYPE_COUNT_DOWN = 110;
 //     Service              BindService(        activity  )
  @Override
  public IBinder onBind(Intent intent) {
    return new RecordBinder();
  }
 //            
 // START_STICKY      ,    ,    ,   Intent  
 //       https://blog.csdn.net/github_37663523/article/details/78811539
 @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
  }
  @Override
  public void onCreate() {
    super.onCreate();
    //    
    mIsRunning = false;
    //      create        
    mMediaRecorder = new MediaRecorder();
    //      CallBack  ,         (         ,  )
    mHandler = new Handler(Looper.getMainLooper(), this);
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
  }
 //     
  public boolean isReady() {
    return mMediaProjection != null && mResultData != null;
  }
 //                   
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  public void clearRecordElement() {
    clearAll();
    if (mMediaRecorder != null) {
      mMediaRecorder.reset();
      mMediaRecorder.release();
      mMediaRecorder = null;
    }
    mResultData = null;
    //      false
    mIsRunning = false;
  }
 //               get  
  public boolean ismIsRunning() {
    return mIsRunning;
  }
 //            ActivityForResult     ,        
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  public void setResultData(int resultCode, Intent resultData) {
    mResultCode = resultCode;
    mResultData = resultData;
 //      ,           
    mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    //getMediaProjection(code,data)            
    //   MediaProjectionManager      MediaProjection       ,        
    //      setResultData     ActivityForResult  code,data
    if (mProjectionManager != null) {
      mMediaProjection = mProjectionManager.getMediaProjection(mResultCode, mResultData);
    }
  }
 //     
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  public boolean startRecord() {
  //      (false,     )
    if (mIsRunning) {
      return false;
    }
    //    ,    
    if (mMediaProjection == null) {
      mMediaProjection = mProjectionManager.getMediaProjection(mResultCode, mResultData);
    }
 //                 
    setUpMediaRecorder();
    //           ,  ,      
    createVirtualDisplay();
    //    
    mMediaRecorder.start();
 //           
    TalScreenUtils.startRecord();
    //       
    mHandler.sendEmptyMessageDelayed(MSG_TYPE_COUNT_DOWN, 1000);
    //    true
    mIsRunning = true;
    Log.d(TAG, "startRecord ");
    return true;
  }
 //     
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  public boolean stopRecord(String tip) {
    Log.d(TAG, "stopRecord: first ");
    //mIsRunning     false !mIsRunning   true。。
    if (!mIsRunning) {
      return false;
    }
    mIsRunning = false;
    Log.w(TAG, "stopRecord middle");
    try {
    //      ,      
      mMediaRecorder.stop();
      mMediaRecorder.reset();
      mMediaRecorder = null;
      mVirtualDisplay.release();
      mMediaProjection.stop();
      Log.w(TAG, "stopRecord ");
    } catch (Exception e) {
      e.printStackTrace();
      mMediaRecorder.release();
      mMediaRecorder = null;
      Log.w(TAG, "stopRecord exception");
    }
    mMediaProjection = null;
 //         what 
    mHandler.removeMessages(MSG_TYPE_COUNT_DOWN);
    //      tip                 
    TalScreenUtils.stopRecord(tip);
    Log.i(TAG, "stopRecord: " + mRecordFilePath);
    //               
    if (mRecordSeconds <= 2) {
      TalFileUtils.deleteSDFile(mRecordFilePath);
    } else {
    //      ,         
    //              ,                 ContentResolver
    //    ,                  ,              ,     ,    
    //https://blog.csdn.net/bzlj2912009596/article/details/80248272
      TalFileUtils.fileScanVideo(this, mRecordFilePath, 1280, 720, mRecordSeconds);
    }
//    mRecordFilePath = null;
    mRecordSeconds = 0;
    return true;
  }
 //          activity or fragment        
  public void pauseRecord() {
    if (mMediaRecorder != null) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mMediaRecorder.pause();
      }
    }
  }
  public void resumeRecord() {
    if (mMediaRecorder != null) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mMediaRecorder.resume();
      }
    }
  }
 //                ,dpi   VirtualDisplay
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  private void createVirtualDisplay() {
    mVirtualDisplay = mMediaProjection.createVirtualDisplay("MainScreen", 1280, 720, mScreenDpi,
        DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
  }
 //       ,              separator    ,   
  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  private void setUpMediaRecorder() {
    mRecordFilePath = getSaveDirectory() + File.separator + System.currentTimeMillis() + ".mp4";
    Log.i(TAG, "setUpMediaRecorder: " + mRecordFilePath);
    if (mMediaRecorder == null) {
      mMediaRecorder = new MediaRecorder();
    }
    //     
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 //         
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
 //          
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    if (mRecordFilePath != null) {
      mMediaRecorder.setOutputFile(mRecordFilePath);
    } else if (mRecordFilePath == null) {
      mMediaRecorder.setOutputFile(mRecordFilePath);
    }
    //         ,    mVirtualDisplay         
    //mVirtualDisplay            ,setVideoSize            
    mMediaRecorder.setVideoSize(1280, 720);
     //     H264        
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
  //        
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    //              
    mMediaRecorder.setVideoEncodingBitRate((int) (1280 * 720 * 2.6));
    //    ,           ,    Camera.CameraParameter.getSupportedPreviewFpsRange()           
    mMediaRecorder.setVideoFrameRate(20);
    try {
    //  
      mMediaRecorder.prepare();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  public void clearAll() {
    if (mMediaProjection != null) {
      mMediaProjection.stop();
      mMediaProjection = null;
    }
  }
 //  
  public String getRecordFilePath() {
    return mRecordFilePath;
  }
 //sd     ,   sd     
  public String getSaveDirectory() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      return Environment.getExternalStorageDirectory().getAbsolutePath();
    } else {
      return null;
    }
  }
  //     Handle.CallBack      handleMessage
  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  @Override
  public boolean handleMessage(Message msg) {
    switch (msg.what) {
      case MSG_TYPE_COUNT_DOWN: {
        String str = null;
        //    
        boolean enough = TalFileUtils.getSDFreeMemory() / (1024 * 1024) < 4;
        if (enough) {
          //    ,    
          str = "    ";
          //                ,          
          stopRecord(str);
          mRecordSeconds = 0;
          break;
        }
        mRecordSeconds++;
        int minute = 0, second = 0;
        if (mRecordSeconds >= 60) {
          minute = mRecordSeconds / 60;
          second = mRecordSeconds % 60;
        } else {
          second = mRecordSeconds;
        }
        TalScreenUtils.onRecording("0" + minute + ":" + (second < 10 ? "0" + second : second + ""));
        if (mRecordSeconds < 5 * 60) {
          mHandler.sendEmptyMessageDelayed(MSG_TYPE_COUNT_DOWN, 1000);
        } else if (mRecordSeconds == 5 * 60) {
          str = "        ";
          stopRecord(str);
          mRecordSeconds = 0;
        }
        break;
      }
    }
    return true;
  }
  public class RecordBinder extends Binder {
    public TalScreenRecordService getRecordService() {
      return TalScreenRecordService.this;
    }
  }
}
핸드폰 픽 셀,그리고 dpi 클래스 를 붙 여 볼 게 요.

public class TalScreenParams {
  private static int mScreenWidth;
  private static int mScreenHeight;
  private static int mScreenDpi;

  public static void init(Activity activity){
    Display display = activity.getWindowManager().getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    mScreenWidth = metrics.widthPixels;
    mScreenHeight = metrics.heightPixels;
    mScreenDpi = metrics.densityDpi;
  }

  public static int getScreenWidth(){
    return mScreenWidth;
  }

  public static int getScreenHeight(){
    return mScreenHeight;
  }

  public static int getScreenDpi(){
    return mScreenDpi;
  }
파일 삭제,미디어 라 이브 러 리 에 추 가 된 클래스 를 붙 여 넣 으 면 ContentResolver 에 사 용 됩 니 다.

public class TalFileUtils {
  /**
   *   SD        
   *
   * @param path
   * @return
   */
  public static boolean deleteSDFile(String path) {
    return deleteSDFile(path, false);
  }

  /**
   *   SD        
   *
   * @param path
   * @param deleteParent true      
   * @return
   */
  public static boolean deleteSDFile(String path, boolean deleteParent) {
    if (TextUtils.isEmpty(path)) {
      return false;
    }

    File file = new File(path);
    if (!file.exists()) {
      //   
      return true;
    }
    return deleteFile(file, deleteParent);
  }

  /**
   * @param file
   * @param deleteParent true      
   * @return
   */
  public static boolean deleteFile(File file, boolean deleteParent) {
    boolean flag = false;
    if (file == null) {
      return flag;
    }
    if (file.isDirectory()) {
      //    
      File[] files = file.listFiles();
      if (files.length > 0) {
        for (int i = 0; i < files.length; i++) {
          flag = deleteFile(files[i], true);
          if (!flag) {
            return flag;
          }
        }
      }
      if (deleteParent) {
        flag = file.delete();
      }
    } else {
      flag = file.delete();
    }
    file = null;
    return flag;
  }

  /**
   *         
   *
   * @param context    
   */
  public static Uri fileScanVideo(Context context, String videoPath, int videoWidth, int videoHeight,
                  int videoTime) {
    File file = new File(videoPath);
    if (file.exists()) {
      Uri uri = null;
      long size = file.length();
      String fileName = file.getName();
      long dateTaken = System.currentTimeMillis();
      ContentValues values = new ContentValues(11);
      values.put(MediaStore.Video.Media.DATA, videoPath); //   ;
      values.put(MediaStore.Video.Media.TITLE, fileName); //   ;
      values.put(MediaStore.Video.Media.DURATION, videoTime * 1000); //   
      values.put(MediaStore.Video.Media.WIDTH, videoWidth); //    
      values.put(MediaStore.Video.Media.HEIGHT, videoHeight); //    
      values.put(MediaStore.Video.Media.SIZE, size); //     ;
      values.put(MediaStore.Video.Media.DATE_TAKEN, dateTaken); //     ;
      values.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);//    ;
      values.put(MediaStore.Video.Media.DATE_MODIFIED, dateTaken / 1000);//     ;
      values.put(MediaStore.Video.Media.DATE_ADDED, dateTaken / 1000); //     ;
      values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");

      ContentResolver resolver = context.getContentResolver();

      if (resolver != null) {
        try {
          uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        } catch (Exception e) {
          e.printStackTrace();
          uri = null;
        }
      }

      if (uri == null) {
        MediaScannerConnection.scanFile(context, new String[]{videoPath}, new String[]{"video/*"}, new MediaScannerConnection.OnScanCompletedListener() {
          @Override
          public void onScanCompleted(String path, Uri uri) {

          }
        });
      }

      return uri;
    }

    return null;
  }

  /**
   * SD        
   */
  public static boolean isSDExists() {
    return Environment.getExternalStorageState().equals(
        Environment.MEDIA_MOUNTED);
  }

  /**
   *   SD      ,   Byte
   *
   * @return
   */
  public static long getSDFreeMemory() {
    try {
      if (isSDExists()) {
        File pathFile = Environment.getExternalStorageDirectory();
        // Retrieve overall information about the space on a filesystem.
        // This is a Wrapper for Unix statfs().
        StatFs statfs = new StatFs(pathFile.getPath());
        //   SDCard    block SIZE
        long nBlockSize = statfs.getBlockSize();
        //          Block   
        // long nAvailBlock = statfs.getAvailableBlocksLong();
        long nAvailBlock = statfs.getAvailableBlocks();
        //   SDCard    Byte
        long nSDFreeSize = nAvailBlock * nBlockSize;
        return nSDFreeSize;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return 0;
  }
  public static long getFreeMem(Context context) {
    ActivityManager manager = (ActivityManager) context.getApplicationContext().getSystemService(Activity.ACTIVITY_SERVICE);
    if (manager != null) {
      ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
      if (info != null) {
        manager.getMemoryInfo(info);
        //   Byte
        return info.availMem / 1024 / 1024;
      }
    }
    return 0;
  }
}
또 하 나 는 전체 서비스 에 편리 한 방문 을 제공 하 는 유형 으로 감청 서비스 중의 변 화 를 집합 에 넣 어 하 는 것 이다.

public class TalScreenUtils {
  private static TalScreenRecordService s_ScreenRecordService;
  private static List<RecordListener> s_RecordListener = new ArrayList<>();
  private static List<OnPageRecordListener> s_PageRecordListener = new ArrayList<>();
  //true,            
  public static boolean s_IsRecordingTipShowing = false;
  /**
   *      5.0+        
   * @return
   */
  public static boolean isScreenRecordEnable(){
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ;
  }
  public static void setScreenService(TalScreenRecordService screenService){
    s_ScreenRecordService = screenService;
  }
  public static void clear(){
    if ( isScreenRecordEnable() && s_ScreenRecordService != null){
      s_ScreenRecordService.clearAll();
      s_ScreenRecordService = null;
    }
    if (s_RecordListener != null && s_RecordListener.size() > 0){
      s_RecordListener.clear();
    }
    if (s_PageRecordListener != null && s_PageRecordListener.size() > 0 ){
      s_PageRecordListener.clear();
    }
  }
  /**
   *     
   */
  public static void startScreenRecord(Activity activity, int requestCode) {
    if (isScreenRecordEnable()){
      if (s_ScreenRecordService != null && !s_ScreenRecordService.ismIsRunning()){
        if (!s_ScreenRecordService.isReady()){
          MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) activity.
              getSystemService(Context.MEDIA_PROJECTION_SERVICE);
          if (mediaProjectionManager != null){
            Intent intent = mediaProjectionManager.createScreenCaptureIntent();
            PackageManager packageManager = activity.getPackageManager();
            if (packageManager.resolveActivity(intent,PackageManager.MATCH_DEFAULT_ONLY) != null){
              //       Activity
              activity.startActivityForResult(intent,requestCode);
            }else {
              Toast.makeText(activity, "    ", Toast.LENGTH_SHORT).show();
            }
          }
        } else {
          s_ScreenRecordService.startRecord();
        }
      }
    }
  }
  /**
   *          ,       
   * @param resultCode
   * @param resultData
   */
  public static void setUpData(int resultCode,Intent resultData) throws Exception{
    if (isScreenRecordEnable()){
      if (s_ScreenRecordService != null && !s_ScreenRecordService.ismIsRunning()){
        s_ScreenRecordService.setResultData(resultCode,resultData);
        s_ScreenRecordService.startRecord();
      }
    }
  }
  /**
   *     
   */
  public static void stopScreenRecord(Context context){
    if (isScreenRecordEnable()){
      if (s_ScreenRecordService != null && s_ScreenRecordService.ismIsRunning()){
        String str = "    ";
        s_ScreenRecordService.stopRecord(str);
      }
    }
  }
  /**
   *           
   * @return
   */
  public static String getScreenRecordFilePath(){
    if (isScreenRecordEnable() && s_ScreenRecordService!= null) {
      return s_ScreenRecordService.getRecordFilePath();
    }
    return null;
  }
  /**
   *          
   * @return
   */
  public static boolean isCurrentRecording(){
    if (isScreenRecordEnable() && s_ScreenRecordService!= null) {
      return s_ScreenRecordService.ismIsRunning();
    }
    return false;
  }
  /**
   * true,            
   * @return
   */
  public static boolean isRecodingTipShow(){
    return s_IsRecordingTipShowing;
  }
  public static void setRecordingStatus(boolean isShow){
    s_IsRecordingTipShowing = isShow;
  }
  /**
   *       ,app       ,       
   */
  public static void clearRecordElement(){
    if (isScreenRecordEnable()){
      if (s_ScreenRecordService != null ){
        s_ScreenRecordService.clearRecordElement();
      }
    }
  }
  public static void addRecordListener(RecordListener listener){
    if (listener != null && !s_RecordListener.contains(listener)){
      s_RecordListener.add(listener);
    }
  }
  public static void removeRecordListener(RecordListener listener){
    if (listener != null && s_RecordListener.contains(listener)){
      s_RecordListener.remove(listener);
    }
  }
  public static void addPageRecordListener( OnPageRecordListener listener){
    if (listener != null && !s_PageRecordListener.contains(listener)){
      s_PageRecordListener.add(listener);
    }
  }
  public static void removePageRecordListener( OnPageRecordListener listener){
    if (listener != null && s_PageRecordListener.contains(listener)){
      s_PageRecordListener.remove(listener);
    }
  }
  public static void onPageRecordStart(){
    if (s_PageRecordListener!= null && s_PageRecordListener.size() > 0 ){
      for (OnPageRecordListener listener : s_PageRecordListener){
        listener.onStartRecord();
      }
    }
  }
  public static void onPageRecordStop(){
    if (s_PageRecordListener!= null && s_PageRecordListener.size() > 0 ){
      for (OnPageRecordListener listener : s_PageRecordListener){
        listener.onStopRecord();
      }
    }
  }
  public static void onPageBeforeShowAnim(){
    if (s_PageRecordListener!= null && s_PageRecordListener.size() > 0 ){
      for (OnPageRecordListener listener : s_PageRecordListener){
        listener.onBeforeShowAnim();
      }
    }
  }
  public static void onPageAfterHideAnim(){
    if (s_PageRecordListener!= null && s_PageRecordListener.size() > 0 ){
      for (OnPageRecordListener listener : s_PageRecordListener){
        listener.onAfterHideAnim();
      }
    }
  }
  public static void startRecord(){
    if (s_RecordListener.size() > 0 ){
      for (RecordListener listener : s_RecordListener){
        listener.onStartRecord();
        Log.i("xxx", "startRecord: ");
      }
    }
  }
  public static void pauseRecord(){
    if (s_RecordListener.size() > 0 ){
      for (RecordListener listener : s_RecordListener){
        listener.onPauseRecord();
      }
    }
  }
  public static void resumeRecord(){
    if (s_RecordListener.size() > 0 ){
      for (RecordListener listener : s_RecordListener){
        listener.onResumeRecord();
      }
    }
  }
  public static void onRecording(String timeTip){
    if (s_RecordListener.size() > 0 ){
      for (RecordListener listener : s_RecordListener){
        listener.onRecording(timeTip);
      }
    }
  }
  public static void stopRecord(String stopTip){
    if (s_RecordListener.size() > 0 ){
      for (RecordListener listener : s_RecordListener){
        listener.onStopRecord( stopTip);
      }
    }
  }
  public interface RecordListener{
    void onStartRecord();
    void onPauseRecord();
    void onResumeRecord();
    void onStopRecord(String stopTip);
    void onRecording(String timeTip);
  }
  public interface OnPageRecordListener {
    void onStartRecord();
    void onStopRecord();
    void onBeforeShowAnim();
    void onAfterHideAnim();
  }
}
마지막 이 되 었 습 니 다.호출 된 내용 입 니 다.

public class MainActivity extends AppCompatActivity {
  private static final String TAG = MainActivity.class.getSimpleName();
  private Button mBtn;
  private final int REQUEST_ALLOW = 100;
  private Button mButton;
  //bindService      
  private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
      //  service
      TalScreenRecordService.RecordBinder recordBinder = (TalScreenRecordService.RecordBinder) service;
      TalScreenRecordService recordService = recordBinder.getRecordService();
      //           activity   Service
      TalScreenUtils.setScreenService(recordService);
    }
    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
  };
 //  service,     service,   AndroidManifest        service 
  private void startService() {
    Intent intent = new Intent(MainActivity.this, TalScreenRecordService.class);
    bindService(intent, mConnection, BIND_AUTO_CREATE);
  }
  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBtn = findViewById(R.id.btn);
    mButton = findViewById(R.id.button2);
    initView();
    //               xml   
    mBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (TalFileUtils.getFreeMem(MainActivity.this) < 100) {
          Toast.makeText(MainActivity.this, "      ,         ", Toast.LENGTH_SHORT).show();
          return;
        }
        //      
        TalScreenUtils.startScreenRecord(MainActivity.this, REQUEST_ALLOW);
      }
    });
    mButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        stop();
        Log.i(TAG, "onClick: " + stop());
      }
  //          
      private String stop() {
        TalScreenUtils.stopScreenRecord(MainActivity.this);//  
        return TalScreenUtils.getScreenRecordFilePath();
      }
    });
  }
  @Override
  protected void onStart() {
    super.onStart();

  }

  private void initView() {
    //    
    TalAllow.requestPermissions(this, REQUEST_ALLOW);
    //        onCreate          
    TalScreenParams.init(this);
    startService();
  }

  @Override
  protected void onStop() {
    super.onStop();
    //                 
    TalScreenUtils.clear();
  }
 //          
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Toast.makeText(this, permissions[0] + "
" + grantResults[0], Toast.LENGTH_SHORT).show(); super.onRequestPermissionsResult(requestCode, permissions, grantResults); } // code data @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_ALLOW && data != null) { try { // , TalScreenUtils.setUpData(resultCode, data); // String screenRecordFilePath = TalScreenUtils.getScreenRecordFilePath(); if (screenRecordFilePath == null) { Toast.makeText(this, " ", Toast.LENGTH_SHORT).show(); } Toast.makeText(MainActivity.this, "" + screenRecordFilePath, Toast.LENGTH_SHORT).show(); Log.i("zlq", "onClick: " + screenRecordFilePath); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, " ", Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { super.onDestroy(); unbindService(mConnection); } }
이로써 비교적 완전한 녹음 기능 이 실 현 될 수 있 으 니 부족 한 점 은 지적 하여 바로잡아 주 십시오.
총결산
안 드 로 이 드 미디어 레 코더 녹음 시 녹음 기능 이 실 현 된 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 안 드 로 이 드 미디어 레 코더 녹음 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 바 랍 니 다!

좋은 웹페이지 즐겨찾기