如何从android中的sdcard删除捕获的视频

时间:2015-01-22 11:21:10

标签: java android eclipse

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class MainActivity extends Activity {

    // Activity request codes
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 100;
    public static final int MEDIA_TYPE_VIDEO = 1;
    public static TextView output;
    private VideoView videoPreview;
    String[] fileList;
    public static MainActivity ActivityContext =null;
    // directory name to store captured images and videos
    private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

    private Uri fileUri; // file url to store image/video
    private static File mediaStorageDir;

    private ImageButton deletbtn, previewbtn, btnRecordVideo;

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

        btnRecordVideo = (ImageButton) findViewById(R.id.btnRecordVideo);
        videoPreview = (VideoView) findViewById(R.id.videoPreview);
        previewbtn = (ImageButton) findViewById(R.id.previewbtn);
        deletbtn = (ImageButton) findViewById(R.id.deletbtn);

        /*
         * Record video button click event
         */
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                recordVideo();
            }
        });

        previewbtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                previewVideo();
            }
        });

        deletbtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // record video
                deleteVideo();
            }
        });

        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
    }

    /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /*
     * Recording video
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
        // Toast.makeText(getApplicationContext(), fileUri.toString(), Toast.LENGTH_LONG).show();
        // set video quality
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 180);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
        // name

        // start the video capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);

    }


    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // video successfully recorded
                // preview the recorded video
                //previewVideo();
                Toast.makeText(getApplicationContext(),
                        "Video recorded", Toast.LENGTH_SHORT)
                        .show();

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
    /*
     * Previewing recorded video
     */
    private void previewVideo() {
        try {

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(fileUri.getPath());
            // start playing
            videoPreview.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){

        return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){

        // Check that the SDCard is mounted
        mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES),"MyCameraVideo");


        // Create the storage directory(MyCameraVideo) if it does not exist
        if (! mediaStorageDir.exists()){

            if (! mediaStorageDir.mkdirs()){

                output.setText("Failed to create directory MyCameraVideo.");

                Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
                        Toast.LENGTH_LONG).show();

                Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }
        return mediaFile;
    }

    private void deleteVideo( ) {



enter code here

        File videoFiles = new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo");

        if(videoFiles.isDirectory())
        {
            fileList=videoFiles.list();
            Log.d("hello",FileList );
        }

        for(int i=0;i<fileList.length;i++)
        {
            Log.e("Video:"+i+" File name",fileList[i]);
        }

      }
    }

我遇到了这个问题。 请建议我如何做到这一点。

  

8868-8868 / com.example.video.videoapp W / dalvikvm:threadid = 1:线程退出时未捕获异常(group = 0x41016ae0)   01-22 15:19:33.519 8868-8868 / com.example.video.videoapp E / AndroidRuntime:FATAL EXCEPTION:main       显示java.lang.NullPointerException               在com.example.video.videoapp.MainActivity.deleteVideo(MainActivity.java:238)               在com.example.video.videoapp.MainActivity.access $ 200(MainActivity.java:23)               at com.example.video.videoapp.MainActivity $ 3.onClick(MainActivity.java:76)               在android.view.View.performClick(View.java:4278)               在android.view.View $ PerformClick.run(View.java:17429)               在android.os.Handler.handleCallback(Handler.java:725)               在android.os.Handler.dispatchMessage(Handler.java:92)               在android.os.Looper.loop(Looper.java:137)               在android.app.ActivityThread.main(ActivityThread.java:5099)               at java.lang.reflect.Method.invokeNative(Native Method)               在java.lang.reflect.Method.invoke(Method.java:511)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:803)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)               at dalvik.system.NativeStart.main(Native Method)   01-22 15:19:38.454 8868-8868 / com.example.video.videoapp I / Process:发送信号。 PID:8868 SIG:9

4 个答案:

答案 0 :(得分:1)

File videofiles=new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo.mp4");

videofiles.delete();

答案 1 :(得分:1)

使用文件类,你可以做到

File file = new File(path_to_the_file);
boolean deleted = file.delete();

其中path_to_the_file是您要删除的文件的路径 - 例如:

/sdcard/YourDirectoryname/filename.extention

答案 2 :(得分:0)

在您的代码中,您不会删除该文件。您只是将文件放在MyCameraVideo文件夹中。使用以下代码删除文件。

    private void deleteVideo( ) {
    File videoFiles = new File(Environment.getExternalStorageDirectory()+"/MyCameraVideo/");

    if(videoFiles.isDirectory())
    {
        fileList=videoFiles.list();
        Log.d("hello",fileList.toString());
    }

    for(int i=0;i<fileList.length;i++)
    {
        Log.e("Video:"+i+" File name",fileList[i]);
        String path=Environment.getExternalStorageDirectory()+"/MyCameraVideo/"+fileList[i];
        File file = new File(path);
        file.delete();
    }
  }

不要忘记在Manifest中添加这些权限。

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

答案 3 :(得分:0)

当Control在onActivityResult中时,您可以获取文件路径,如果存在,您可以删除该文件。 查看代码,希望它能为您提供帮助。

对摄像机的意图

intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
                MediaRecorder.OutputFormat.MPEG_4);
        long maxVideoSize = 15*1024*1024; // 15 MB
        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, maxVideoSize);
        startActivityForResult(intent, REQUEST_VIDEO_CAMERA);

onActivityResult中的代码:

if (requestCode == REQUEST_VIDEO_CAMERA) {
        if (resultCode == RESULT_OK) {
            Log.d("In video from camera", "In video from camera");
            Uri videoUri = data.getData();

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(videoUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            String mMediaFilePath = filePath;   //File path of Video Recorded.

            cursor.close();

        //Delete File from Location.
         File videoFile = new File(mMediaFilePath);
                    if(videoFile.exists())
                    {
                        videoFile.delete();
                    }
        }
    }