Android studio +sd卡地址读取+录像机

 本文主要是介绍录像机功能的实现


                 这里用到了是 MediaRecorder +camera 来实现录像功能,关于MediaRecorder 与camera的原理这里就不多加介绍了,


                 图片源都是在网上找的,这里就不添加了,你们可以随便添

                第三方架包 junit  [直接在stuido中找的,不用刻意去下载junit的jar包]
 
                实现功能:录像
                                sd卡内存判断查询
                                录像视频的分辨率设置

              这里的摄像头我给写死了,摄像头的前置后置没有进行处理

一,在AndroidManifest 中添加权限,这个千万不能忘记


   

    
    
    
    
    
    
    
    



二,xml布局

    activity_main.xml  <RelativeLayout>



    

        

        

        

        

        
    
    


activity_setup.xml    <LinearLayout>

 
  
 
        
            
            
        
        
        
            
            
        
        
        
            
            
        

    

item.xml



    

        

        

        

        

        
    

    

item_shijian.xml >

    

    


三,java类

MainActivity

public class MainActivity extends Activity implements SurfaceHolder.Callback {
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private Button btnStartStop;
    private boolean isRecording = false;//标记是否已经在录制
    private MediaRecorder mediaRecorder;//音视频录制类
    private Camera mCamera = null;//相机
    private Camera.Size mSize = null;//相机的尺寸
    private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_BACK;//默认后置摄像头
    private static final SparseIntArray orientations = new SparseIntArray();//手机旋转对应的调整角度
    private TextView mMinutePrefix;
    private TextView mMinuteText;
    private TextView mSecondPrefix;
    private TextView mSecondText;
    private TextView mTime;
    private DelFile delFile=new DelFile();
    private Handler mHandler = new Handler();
    private Handler handler2 = new Handler();
    private SetupActivity setupActivity=new SetupActivity();

    //屏幕的四种状态(90 180 270 360)
    static {
        orientations.append(Surface.ROTATION_0, 90);
        orientations.append(Surface.ROTATION_90, 0);
        orientations.append(Surface.ROTATION_180, 270);
        orientations.append(Surface.ROTATION_270, 180);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindow();
        setContentView(R.layout.activity_main);
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        btnStartStop = (Button) findViewById(R.id.bt_StartStop);
        mMinutePrefix = (TextView) findViewById(R.id.tv_prefix);//时(十位)时间
        mMinuteText = (TextView) findViewById(R.id.tv_text);//时(个位)时间
        mSecondPrefix = (TextView) findViewById(R.id.tv_prefix2);//分时间
        mSecondText = (TextView) findViewById(R.id.tv_text2);//秒时间

        initViews();
        wenJian();
        getWindows();
        delFile.del(this);
        intnSetup();
    }
    public void intnSetup(){
        Button bu_setup;
        bu_setup=(Button) findViewById(R.id.bu_setup);
        bu_setup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(MainActivity.this,SetupActivity.class);
                startActivity(intent);
            }
        });
    }

    private void getWindows() {
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                handler2.post(new Runnable() {
                    @Override
                    public void run() {
                        startRecord();
                    }
                });
            }
        });
    }

    //设置主桌面
    private void setWindow() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        // 设置竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 选择支持半透明模式,在有surfaceview的activity中使用。
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
    }

    //点击事件
    private void initViews() {

        Log.d("bbbbb2", "isRecording : " + isRecording);
        btnStartStop.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isRecording) {//isRecording 录像状态
                    Log.d("bbbbb", "isRecording : " + isRecording);
                    startRecord();
                } else {
                    Log.d("ccccc", "isRecording : " + isRecording);
                    stopRecord();
                }
            }
        });
        SurfaceHolder holder = mSurfaceView.getHolder();// 取得holder
        holder.setFormat(PixelFormat.TRANSPARENT);//设置格式
        holder.setKeepScreenOn(true);//保持屏幕长亮
        holder.addCallback(this); // holder加入回调接口
    }

    /**
     * 初始化相机
     */
    public void initCamera() {
        if (Camera.getNumberOfCameras() == 2) {
            mCamera = Camera.open(mCameraFacing);//如果在初始化相机在onCreate中会出现异常
        } else {
            mCamera = Camera.open();
        }
        CameraSizeComparator sizeComparator = new CameraSizeComparator();//相机尺寸
        Camera.Parameters parameters = mCamera.getParameters();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)//相机权限
                == PackageManager.PERMISSION_GRANTED) {
            Log.i("TEST", "Granted");
            //init(barcodeScannerView, getIntent(), null);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 1);//1 can be another integer
        }
        if (mSize == null) {
            List vSizeList = parameters.getSupportedPreviewSizes();
            Collections.sort(vSizeList, sizeComparator);

            for (int num = 0; num < vSizeList.size(); num++) {
                Camera.Size size = vSizeList.get(num);

                if (size.width >= 800 && size.height >= 480) {
                    this.mSize = size;
                    break;
                }
            }
            mSize = vSizeList.get(0);
            List focusModesList = parameters.getSupportedFocusModes();
            //增加对聚焦模式的判断
            if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }
            mCamera.setParameters(parameters);
        }
        //获取窗口信息不同状态(如手机硬件旋转,而摄像方向不变)
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        int orientation = orientations.get(rotation);
        mCamera.setDisplayOrientation(orientation);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Log.d("on", "onResume: 1234565876879");
        initCamera();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Log.d("on", "onPause: 1234565876879");
        releaseCamera();//释放相机信息
    }

    /**
     * 开始录制
     */
    private void startRecord() {
        if (mediaRecorder == null) {
            mediaRecorder = new MediaRecorder(); // 创建MediaRecorder
        }
        if (mCamera != null) {
            mCamera.stopPreview();//获取影像
            mCamera.unlock();//以允许media进程得以访问camera
            mediaRecorder.setCamera(mCamera);
        }
        //开始录像后,每隔1s去更新录像的时间戳
        mHandler.postDelayed(mTimestampRunnable, 1000);
        try {
            isRecording = true;
            // 设置音频采集方式
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            //设置视频的采集方式
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            //设置文件的输出格式
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//aac_adif, aac_adts, output_format_rtp_avp, output_format_mpeg2ts ,webm
            //设置audio的编码格式
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            //设置video的编码格式
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            //设置录制的视频编码比特率
            mediaRecorder.setVideoEncodingBitRate(1024 * 1024);
            //设置录制的视频帧率,注意文档的说明:
            mediaRecorder.setVideoFrameRate(30);
            //设置要捕获的视频的宽度和高度
            mSurfaceHolder.setFixedSize(320, 240);//最高只能设置640x480
            Log.d("startRecord: ", "asdsda");
            //设置视频的大小
            mediaRecorder.setVideoSize(setupActivity.myWidths(), setupActivity.myHeights());//最高只能设置640x480
            //设置录制视频的最大储存空间
            long sdMemory =setupActivity.myNeiCun();
            Log.e("sdMEmory", "startRecord: "+sdMemory);
            mediaRecorder.setMaxFileSize(sdMemory);
            //设置记录会话的最大持续时间(毫秒)
            mediaRecorder.setMaxDuration(20 * 60 * 1000);
            mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            String path = getSDPath();
            if (path != null) {
                File dir = new File(path + "/videos");
                if (!dir.exists()) {
                    dir.mkdir();
                }
                path = dir + "/" + System.currentTimeMillis() + ".mp4";
                //设置输出文件的路径
                mediaRecorder.setOutputFile(path);
                //准备录制
                mediaRecorder.prepare();
                //开始录制
                mediaRecorder.start();
                btnStartStop.setText("停止");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 停止录制
     */
    private void stopRecord() {
        try {
            // 设置后不会崩
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setPreviewDisplay(null);
            //停止录制
            mediaRecorder.stop();
            //重置
            mediaRecorder.reset();
            btnStartStop.setText("开始");

        } catch (Exception e) {
            e.printStackTrace();
        }
        isRecording = false;
        mHandler.removeCallbacks(mTimestampRunnable);
        //将录像时间还原
        mMinutePrefix.setVisibility(View.VISIBLE);
        mMinuteText.setText("0");
        mSecondPrefix.setVisibility(View.VISIBLE);
        mSecondText.setText("0");
    }

    /**
     * 释放MediaRecorder
     */
    private void releaseMediaRecorder() {
        if (mediaRecorder != null) {
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }

    /**
     * 释放相机资源
     */
    private void releaseCamera() {
        try {
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.unlock();
                mCamera.release();
            }
        } catch (RuntimeException e) {
        } finally {
            mCamera = null;
        }
    }

    //文件最后修改时间
    public void wenJian() {
        String path = getSDPath();
        if (path != null) {
            File dir = new File(path + "/videos");
            if (!dir.exists()) {
                dir.mkdir();
            }
            path = dir + "/" + System.currentTimeMillis() + ".mp4";

            /*//设置输出文件的路径
            mediaRecorder.setOutputFile(path);*/

            File f = new File(path);
            //Date time=new Date(f.lastModified());//两种方法都可以
            if (f.exists()) {//喜欢的话可以判断一下。。。
                System.out.println("File Exist.");
            }
            long time = f.lastModified();
            Log.e("time", "wenJian: " + time);
            SimpleDateFormat formatter = new
                    SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String result = formatter.format(time);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder
//        initCamera();
        mSurfaceHolder = holder;
        if (mCamera == null) {
            return;
        }
        try {
            //设置显示
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
            releaseCamera();
            finish();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 将holder,这个holder为开始在onCreate里面取得的holder,将它赋给mSurfaceHolder
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // surfaceDestroyed的时候同时对象设置为null
        if (isRecording && mCamera != null) {
            mCamera.lock();
        }
        mSurfaceView = null;
        mSurfaceHolder = null;
        releaseMediaRecorder();
        releaseCamera();
    }

    private class CameraSizeComparator implements Comparator {
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if (lhs.width == rhs.width) {
                return 0;
            } else if (lhs.width > rhs.width) {
                return 1;
            } else {
                return -1;
            }
        }
    }//相机尺寸

    private Runnable mTimestampRunnable = new Runnable() {
        @Override
        public void run() {
            updateTimestamp();
            mHandler.postDelayed(this, 1000);

        }
    };

    //获取录制时间
    private void updateTimestamp() {
        int second = Integer.parseInt(mSecondText.getText().toString());
        int minute = Integer.parseInt(mMinuteText.getText().toString());
        second++;

        Log.d("qqqqq", "updateTimestamp: " + second);
        if (second < 10 && isRecording==true) {
            mSecondText.setText(String.valueOf(second));
        } else if (second >= 10 && second < 60) {
            mSecondPrefix.setVisibility(View.GONE);
            mSecondText.setText(String.valueOf(second));
        } else if (second >= 60) {
            mSecondPrefix.setVisibility(View.VISIBLE);
            mSecondText.setText("0");
            minute++;
            mMinuteText.setText(String.valueOf(minute));
        } else if (minute >= 60) {
            mMinutePrefix.setVisibility(View.GONE);
        }
    }

    private static String time() {
        Calendar calendar = Calendar.getInstance();
        String i;
        calendar.get(Calendar.YEAR);//年
        calendar.get(Calendar.MONTH);//月
        calendar.get(Calendar.DAY_OF_MONTH);//日
        calendar.get(Calendar.HOUR_OF_DAY);//时
        calendar.get(Calendar.MINUTE);//分
        calendar.get(Calendar.SECOND);//秒
        i = calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH) + "月" +
                calendar.get(Calendar.DAY_OF_MONTH) + "日" + calendar.get(Calendar.HOUR_OF_DAY) + "时" +
                calendar.get(Calendar.MINUTE) + "分" + calendar.get(Calendar.SECOND) + "秒";
        return i;

    }

    // 获取SD path
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        } else {
            return null;
        }
    }
}

SetupActivity

 
  
public class SetupActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView dpi,time,RAM;
    private TextView tv_shuju,tv_shijian,tv_neicun;
    private Resolution resonlution=new Resolution();
    private int i=0;
    private int neiCun=0;
    private SDFreeSize sdFreeSize=new SDFreeSize();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);
        initView();
    }

    public void initView(){
        dpi=(TextView) findViewById(R.id.tv_dpi);
        time=(TextView) findViewById(R.id.tv_time);
        RAM=(TextView) findViewById(R.id.tv_RAM);

        tv_shuju=(TextView) findViewById(R.id.tv_shuju);
        tv_shijian=(TextView) findViewById(R.id.tv_shijian);
        tv_neicun=(TextView) findViewById(R.id.tv_neicun);

        dpi.setOnClickListener(this);
        time.setOnClickListener(this);
        RAM.setOnClickListener(this);
        tv_shuju.setOnClickListener(this);
        tv_shijian.setOnClickListener(this);
        tv_neicun.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_dpi:
                AlertDialog.Builder builder = new AlertDialog.Builder(SetupActivity.this);
                builder.setTitle("选择分辨率");
                  final String[] dip={"640*480","320*240","352*288 ","176*144","128*96"};
                builder.setSingleChoiceItems(dip, 1, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        if ( which==0){
                          //   disply();获取屏幕的分辨率
                            i=5;
                            myWidths();
                            myHeights();
                            tv_shuju.setText(resonlution.myWidth5()+"*"+resonlution.myHeight5());

                        }
                        if ( which==1){
                            i=1;
                            myWidths();
                            myHeights();
                            tv_shuju.setText(resonlution.myWidth1()+"*"+resonlution.myHeight1());

                        }
                        if ( which==2){
                            i=2;
                            myWidths();
                            myHeights();
                            tv_shuju.setText(resonlution.myWidth2()+"*"+resonlution.myHeight2());

                        }
                        if ( which==3){
                            i=3;
                            myWidths();
                            myHeights();
                            tv_shuju.setText(resonlution.myWidth3()+"*"+resonlution.myHeight3());

                        }
                        if ( which==4){
                            i=4;
                            myWidths();
                            myHeights();
                            tv_shuju.setText(resonlution.myWidth4()+"*"+resonlution.myHeight4());

                    }
                        Toast.makeText(SetupActivity.this, "分辨率为:" + dip[which].length(), Toast.LENGTH_SHORT).show();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                builder.show();
                break;
            case R.id.tv_time:
                AlertDialog.Builder diaLog=new AlertDialog.Builder(SetupActivity.this);
                diaLog.setTitle("请输入录像时间:");
                View view= LayoutInflater.from(SetupActivity.this).inflate(R.layout.itme_shijian,null);
                diaLog.setView(view);
                final EditText start=(EditText) view.findViewById(R.id.et_start);
                final EditText stop=(EditText) view.findViewById(R.id.et_stop);


                diaLog.setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        String a = start.getText().toString().trim();
                        String b = stop.getText().toString().trim();
                        //    将输入的开始时间和停止时间打印出来
                        tv_shijian.setText(a+"--"+b);
                        Toast.makeText(SetupActivity.this, "开始时间: " + a + ", 结束时间: " + b, Toast.LENGTH_SHORT).show();
                    }
                });
                diaLog.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }
                });
                diaLog.show();
                break;
            case R.id.tv_RAM:
                AlertDialog.Builder alertRAM=new AlertDialog.Builder(SetupActivity.this);
                alertRAM.setTitle("选择可用内存");
                final String [] ram={"没有SD卡","SD卡可用内存的3/4","SD卡可用内存的4/5","SD卡可用内存的5/6"};
                alertRAM.setSingleChoiceItems(ram, 1, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        if (which==0){

                            neiCun=4;
                            myNeiCun();
                            tv_neicun.setText(" "+sdFreeSize.getSDFreeSize()*0+"MB");
                        }
                        if (which==1){
                            neiCun=1;
                            myNeiCun();
                            tv_neicun.setText(" "+sdFreeSize.getSDFreeSize()*3/4/1024/1024+"MB");
                        }
                        if (which==2){
                            neiCun=2;
                            myNeiCun();
                            tv_neicun.setText(" "+sdFreeSize.getSDFreeSize()*4/5/1024/1024+"MB");

                        }
                        if (which==3){
                            neiCun=3;
                            myNeiCun();
                            tv_neicun.setText(" "+sdFreeSize.getSDFreeSize()*5/6/1024/1024+"MB");
                        }
                        Toast.makeText(SetupActivity.this, "可用内存的大小为:" + ram[which], Toast.LENGTH_SHORT).show();
                    }
                });
                alertRAM.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertRAM.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                    }
                });
                alertRAM.show();
                break;
        }
    }
    public int  myWidths(){
        int width = 0;
       if (i==5){
              width= resonlution.myWidth5();
       }else if (i==1){
              width= resonlution.myWidth1();
       }else if (i==2){
              width= resonlution.myWidth2();
       }else if (i==3){
             width= resonlution.myWidth3();
       }else if (i==4){
             width= resonlution.myWidth4();
       }else if(i==0){
           width=resonlution.myWidth1();

       }
        i=0;
      return width;
    }

    public int myHeights(){
        int height=0;
        if (i==5){
              height= resonlution.myHeight5();
        }else if (i==1){
              height= resonlution.myHeight1();
        }else if (i==2){
              height= resonlution.myHeight2();
        }else if (i==3){
              height= resonlution.myHeight3();
        }else if (i==4){
              height= resonlution.myHeight4();
        }else if (i==0){
            height=resonlution.myHeight1();
        }
        i=0;
        return height;
    }
    public long myNeiCun(){
        long neiCuns=0;
        if (neiCun==4){
            neiCuns=sdFreeSize.getSDFreeSize()*0;
        }else if (neiCun==1){
            neiCuns=sdFreeSize.getSDFreeSize()*3/4;
        }else if (neiCun==2){
            neiCuns=sdFreeSize.getSDFreeSize()*4/5;
        }else if (neiCun==3){
            neiCuns=sdFreeSize.getSDFreeSize()*5/6;
        }else if (neiCun==0){
            neiCuns=sdFreeSize.getSDFreeSize()*2/3;
        }
        neiCun=0;
        return neiCuns;
    }
}


Resolution 

public class Resolution {
    public int myWidth5(){
        int width=640;
        return  width;
    }
    public int myHeight5(){
        int height=480;
        return height;
    }
    public int myWidth1(){
        int width=320;
        return  width;
    }
    public int myHeight1(){
        int height=240;
        return height;
    }
    public int myWidth2(){
        int width=352;
        return  width;
    }
    public int myHeight2(){
        int height=288;
        return height;
    }
    public int myWidth3(){
        int width=176;
        return  width;
    }
    public int myHeight3(){
        int height=144;
        return height;
    }
    public int myWidth4(){
        int width=128;
        return  width;
    }
    public int myHeight4(){
        int height=96;
        return height;
    }
}

SDFreeSize 
//判断sd卡剩余内存
public class SDFreeSize {
    public long getSDFreeSize(){
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        Log.e("aaaaa", "getSDFreeSize: " + (freeBlocks * blockSize) / 1024);
        return (freeBlocks * blockSize) / 1024; //单位KB
    }
    }

DelFile

public class DelFile {

    public void del(Context context) {
        Log.d("aaaaaa", "del: ");
        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator +"videos";
        File file = new File(path);
        File[] files = file.listFiles();// 读取
        Log.d("aaaaaa", "del: "+files);
        getFileName(files,context);
    }


    private static void getFileName(File[] files, Context context) {

        if (files != null) {// 先判断目录是否为空,否则会报空指针
            for (File file : files) {
                if (file.isDirectory()) {
                    Log.i("zeng", "若是文件目录。继续读1" + file.getName().toString()
                            + file.getPath().toString());
                    getFileName(file.listFiles(),context);
                    Log.i("zeng", "若是文件目录。继续读2" + file.getName().toString()
                            + file.getPath().toString());
                } else {
                    String fileName = file.getName();
                    if (fileName.endsWith(".mp4")) {
                        Log.e("aaaaaa", "fileName: "+fileName );
                        try {
                            HashMap map = new HashMap();
                            String s = fileName.substring(0,
                                    fileName.lastIndexOf(".")).toString();
                            SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd-HH-mm");
                            String dateString = format.format(new Date(System.currentTimeMillis()));
                            Date date2 = format.parse(dateString);
                            String ph = Environment.getExternalStorageDirectory()
                                    .getAbsolutePath() + File.separator + "videos"+"/"+s.trim()+".mp4";
                            File fe=new File(ph);
                            Log.i("test", ph);
                            Date date1=format.parse(s.trim());
                            if (getBetweenDay(date1, date2)>2) {
                                fe.delete();
                            }

                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }// 当前时间

                    }
                }
            }
        }
    }
    //获取当前系统时间
    public static int getBetweenDay(Date date1, Date date2) {
        Calendar d1 = new GregorianCalendar();
        d1.setTime(date1);
        Calendar d2 = new GregorianCalendar();
        d2.setTime(date2);
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        Log.e("days", "getBetweenDay: "+days );
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }
}
 
  



 

你可能感兴趣的:(Android)