How do I put a capped maximum directory storage sp

2019-08-29 05:26发布

问题:

Presumingly i wanted to allocate only 1GB of space to store my videos in a particular file directory where how is it going to auto-delete the oldest video file in that directory once its about to reach/hit 1GB?

Sorry i'm kinna new in java/android and currently creating an car blackbox app can someone help me... Thanks

This is what I have tried so far can someone tell me how should i implement the above mention function into my CameraTest Activity:

public class CameraTest extends Activity implements SurfaceHolder.Callback, OnClickListener {

    public static SurfaceView surfaceView;
    public static SurfaceHolder surfaceHolder;
    public static Camera MainCamera;
    private static boolean previewRunning;
    private static boolean serviceRunning = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
        surfaceView.setOnClickListener(this);

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        Button btnSetting = (Button) findViewById(R.id.button2);
        btnSetting.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v)
            {
                startActivity(new Intent(getApplicationContext(), SettingActivity.class));
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (serviceRunning) 
        {  
            serviceRunning = false;
            startService(new Intent(getApplicationContext(), ServiceRecording.class));
        }
        else 
        {  
            serviceRunning = true;  
            stopService(new Intent(getApplicationContext(), ServiceRecording.class));
        }   
    }  

    public static boolean ServiceStatus;
    public static String resParams;

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        if(ServiceRecording.recordingStatus)
        {
            stopService(new Intent(getApplicationContext(), ServiceRecording.class));

            try {
                Thread.sleep(4000);
            } 
            catch (InterruptedException e) {
                e.printStackTrace();
            }

            MainCamera = ServiceRecording.ServiceCamera;

            startService(new Intent(getApplicationContext(), ServiceRecording.class));              
        }

        else{

            MainCamera = Camera.open();

            if (MainCamera != null) {

                resParams = MainCamera.getParameters().get("preview-size-values");

                Camera.Parameters params = MainCamera.getParameters();
                params.setPreviewSize(320, 240);
                params.setPreviewFormat(PixelFormat.JPEG);
                MainCamera.setParameters(params);

                try {
                    MainCamera.setPreviewDisplay(holder);
                } 

                catch (IOException e) 
                {
                    e.printStackTrace();
                }
                MainCamera.startPreview();
                previewRunning = true;  
            }
            else {
                Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
                finish();
            }   
        }

        if (previewRunning) {
            MainCamera.stopPreview();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder){
        MainCamera.stopPreview();
        previewRunning = false;
        MainCamera.release();
    }
}

my serviceRecording.java file public class ServiceRecording extends Service {

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
public static Camera ServiceCamera;
public static boolean recordingStatus;

@Override
public void onCreate() {
    super.onCreate();

    recordingStatus = false;
    ServiceCamera = CameraTest.MainCamera;
    surfaceView = CameraTest.surfaceView;
    surfaceHolder = CameraTest.surfaceHolder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (recordingStatus == false)
    {
        //new Timer().scheduleAtFixedRate(task, after, interval);
        startRecording();
    }

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    stopRecording();
    //camera.stopPreview();
    recordingStatus = false;
    //camera.release();
}   

private MediaRecorder mediaRecorder;

private static int encodingType;
private static String videoResolution;
private static String fileFormat;

private static boolean audioStatus;
private static int timeInterval;

private static final String TAG = "Exception";

public boolean startRecording(){
    try {
            if(Tab1Activity.encodingPref == null)   
            {   
                encodingType = 1;
            }
            else
            {
                encodingType = Integer.parseInt(Tab1Activity.encodingPref);
            }
            //******************************************************************
            if(Tab1Activity.videoResPref == null)   
            {   
                String stringRes = CameraTest.resParams;
                String[] entriesValues = stringRes.split(",");
                videoResolution = entriesValues[0];
            }
            else
            {
                videoResolution = Tab1Activity.videoResPref;
            }
            //******************************************************************
            if(Tab1Activity.fileFormatPref == null) 
            {   
                fileFormat = ".mp4";
            }
            else
            {
                fileFormat = Tab1Activity.fileFormatPref;
            }
            //******************************************************************
            if(Tab2Activity.audioPref == false) 
            {   
                audioStatus = false;
                //PreferenceManager.setDefaultValues(this, R.xml.tab2, true);
            }
            else
            {
                audioStatus = Tab2Activity.audioPref; 
            }       
            //******************************************************************

            Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
            try{
                ServiceCamera.reconnect();
                ServiceCamera.unlock();
            }
            catch(Exception e){

            }

            mediaRecorder = new MediaRecorder();

            mediaRecorder.setCamera(ServiceCamera);

            if(audioStatus != true)
            {
                mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            }

            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

            if(audioStatus != true)
            {
                mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            }

                mediaRecorder.setVideoEncoder(encodingType);

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
                Date date = new Date();
                File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");

                if(!(dirlist.exists()))
                    dirlist.mkdir();

                File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
                mediaRecorder.setOutputFile(TempFile.getPath());

                String[] separatedRes = videoResolution.split("x");
                mediaRecorder.setVideoSize(Integer.parseInt(separatedRes[0]),Integer.parseInt(separatedRes[1]));

                mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());

                mediaRecorder.prepare();
                mediaRecorder.start();  

                recordingStatus = true;

                return true;                        
    } 

    catch (IllegalStateException e) {
        Log.d(TAG,e.getMessage());
        e.printStackTrace();
        return false;
    } 
    catch (IOException e) {
        Log.d(TAG,e.getMessage());
        e.printStackTrace();
        return false;
    }
}

public void stopRecording() {
    Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();   
    mediaRecorder.reset();
    mediaRecorder.release();

    recordingStatus = false;
}
}

回答1:

To get the current size of a directory, you need add up the sizes of each individual file in a directory using the length() method. This article is what you're looking for in that respect. You can then check if the size has exceeded 1 GB.

In terms of auto-deleting the oldest file you can do the following:

File directory = new File(*String for absolute path to directory*);
File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>() {

    @Override
    public int compare(File f1, File f2) {

        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    }
});

file[0].delete();

This code gets all your files in an array, and sorts them depending on their modified/created date. Then the first file in your array is your oldest file, therefore you can just simply delete it.

The best place to put this in your code is when you're about to write something to a directory. Perform this check and deletion first, and then if the size is less than 1 GB, write to directory, otherwise delete another file.