簡體   English   中英

如何在sdcard中檢查視頻文件是否已損壞或在android中沒有?

[英]How Can i check the video file in sdcard is corrupted or not in android?

我正在從服務器下載文件並存儲在sdcard中,但有時網絡連接文件未完全下載,因此我想檢查視頻文件是否已損壞,如果它已損壞,則要刪除該文件並從服務器重新下載,我如何檢查sdcard中的視頻文件已損壞

檢查圖像代碼損壞

Bitmap bmp =loadResizedBitmap(path, imageWidth, imageHeight, false);
if(bmp!=null)
{   
    imageview.setImageDrawable(null);
    imageview.setImageBitmap(bmp);
}
else
{
  // file is corrupt
}

MyDownload.java

public class FirstDownloadFileFromURL extends AsyncTask<String, String, String> 
{


        @Override
        protected void onPreExecute() 
        {
            progressbar.setMax(100);

        }


        @Override
        protected String doInBackground(String... f_url) 
        {

            try 
            {   

                String spaceurl=f_url[0];
                String newurl=spaceurl.replaceAll(" ", "%20");
                BufferedOutputStream out = null;
                Uri u = Uri.parse(newurl);
                File f1 = new File("" + u);
                String originalurl=f_url[0];
                Uri cu = Uri.parse(originalurl);
                File f2= new File("" + cu);
                filename=f2.getName();
                Log.i("DownloadFile", "DownloadURL:" +newurl.replaceAll(" ", "%20"));
                Log.i("DownloadFile", "filename: " + filename);
                File SmartAR;
                if(ssdcard.equals("true"))
                {
                    root = Environment.getExternalStorageDirectory().getAbsolutePath();
                    new File(root + "/montorwerbung").mkdirs(); 
                    SmartAR = new File(root + "/montorwerbung", "");
                }
                else
                {
                    File direct = new File(Environment.getDataDirectory()+"/montorwerbung");
                    if(!direct.exists()) 
                    {
                         if(direct.mkdir()); //directory is created;
                    }
                    SmartAR = new File(direct + "/montorwerbung", "");
                }
                Log.i("smart ar", "filename: " +SmartAR);
                // have the object build the directory structure, if needed.
                SmartAR.mkdirs();
                // create a File object for the output file
                File outputFile = new File(SmartAR, filename);
                // now attach the OutputStream to the file object, instead
                // of a String representation
                FileOutputStream fos = new FileOutputStream(outputFile);
                String url1 = newurl;
                HttpURLConnection conn = (HttpURLConnection) new URL(url1).openConnection();
                conn.setDoInput(true);
                conn.connect();
                int lenghtOfFile = conn.getContentLength();
                final InputStream in = new BufferedInputStream(conn.getInputStream(), 1024); // buffer size
                // 1KB
                out = new BufferedOutputStream(fos, 1024);
                int b;
                long total = 0;
                byte data[] = new byte[1024];
                while ((b = in.read(data)) != -1) 
                {
                    total += b;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                     out.write(data,0,b);
                }
                out.close();
                in.close();
                conn.disconnect();

            } catch (final MalformedURLException e) {
                showError("Error : MalformedURLException " + e);        
                e.printStackTrace();
            } catch (final IOException e) {
                showError("Error : IOException " + e);          
                e.printStackTrace();
            }
            catch (final Exception e) {
                showError("Error : Please Check Your Wifi connection " + e);
            }       
            return null;
        }

        @Override
        protected void onProgressUpdate(String... progress) 
        {

             progressbar.setProgress(Integer.parseInt(progress[0]));
             textprogressbar.setText(String.valueOf(Integer.parseInt(progress[0])+"%"));
        }

        @SuppressWarnings("deprecation")
        @Override
        protected void onPostExecute(String file_url) 
        {


        }
}

這是我所做的

class DownloadAsyncTask extends AsyncTask<String, Integer, String> {

    private final String url;
    private final String absolutePath;
    private int totalSize;
    private int downloadedSize;
    private ProgressDialog dialog;

    public DownloadAsyncTask(String url, String absolutePath) {

        this.url = url;
        this.absolutePath = absolutePath;
    }

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(ParentPageActivity.this );
        dialog.setMessage("Downloading Video");
        dialog.setTitle("Downloading...");
        dialog.setCancelable(true);
        dialog.setIndeterminate(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cancel(true);
            }
        });
        dialog.show();

        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Constants.ROOT_DIR + File.separator + Constants.VIDEO_DIRECTORY_NAME, absolutePath);
         try {

            URL url = new URL(this.url);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //connect
            urlConnection.connect();

            //this is the total size of the file which we are downloading
            totalSize = urlConnection.getContentLength();
            if(file.exists()){

                long length = file.length();
                if(totalSize > length){
                    file.delete();
                }
                else{
                    return file.getAbsolutePath();
                }
            }
            //create a new file, to save the downloaded file
            new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Constants.ROOT_DIR + File.separator + Constants.VIDEO_DIRECTORY_NAME).mkdirs();
            file.createNewFile();

            FileOutputStream fileOutput = new FileOutputStream(file);

            //Stream used for reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

             //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength;
            downloadedSize = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                if(isCancelled()) {
                    return null;
                }
                downloadedSize += bufferLength;
                publishProgress((int) (downloadedSize * 100) /totalSize);
            }

            //close the output stream when complete //
            fileOutput.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            return null;
        }
        return  file.getAbsolutePath();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        dialog.setProgress(values[0]);
    }

    @Override
    protected void onCancelled(String s) {
        super.onCancelled(s);
        if( s!=null){
            File file = new File(s);
            if(file.exists()) file.delete();
            dialog.dismiss();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        dialog.dismiss();
        if(result == null){
            dialog.dismiss();
        }
        else{
            if(new File(result).exists()){
                try{
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(result)), "video/mp4");
                    startActivity(intent);
                }catch (ActivityNotFoundException exception){
                    Toast.makeText(ParentPageActivity.this, "Unable to Open File.", Toast.LENGTH_SHORT).show();
                }
                return;

            }
        }
        Toast.makeText(ParentPageActivity.this, "Unable to Download Video File.", Toast.LENGTH_SHORT).show();


    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM