代码之家  ›  专栏  ›  技术社区  ›  ibad ur rahman

从Kotlin Android的url下载视频?

  •  0
  • ibad ur rahman  · 技术社区  · 6 年前

    我想从url下载视频。但它给出了一个错误:

    E/ContentProvidernative:来自P:12600的合同错误;U:11003 2019-01-14 11:54:35.423 3518-22398/?e/databaseutils:向包写入异常 java.lang.illegalargumentException:未知的uri:content://downloads/public_downloads/6796 在COM.Android。提供者。下载。 在Android .Cyt.CaltServices .Qu查询(Cordon提供程序.java:1138) 在Android .Cyt.CaltServices .Qu查询(Cordon提供程序.java:1230) 在Android中.CytServices $ Talp.Qu查询(Cordon提供程序.java:251) 在Android中.CytPosivRealErr.NoTrACT(CopeToePrimeStudio .java:112) 在Android .Obj.Base. Exchange TraseACT(Boop.java:752) enter image description here

    下载视频文件的代码如下: 私有var下载参考:long=0 private lateinit var downloadmanager:下载管理器

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
                val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                if (downloadId != downloadReference) {
                    context.unregisterReceiver(this)
                    return
                }
                val query = DownloadManager.Query()
                query.setFilterById(downloadReference)
                val cursor = downloadManager.query(query)
                cursor?.let {
                    if (cursor.moveToFirst()) {
                        val columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
                        if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                            var localFile = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
    
                            if (localFile.contains("file:///")) {
                                localFile = localFile.removePrefix("file:///").substringBeforeLast(File.separator)
                            }
                            //context.toast(context.resources.getString(R.string.saved, localFile), Toast.LENGTH_LONG)
    
                        } else if (DownloadManager.STATUS_FAILED == cursor.getInt(columnIndex)) {
                          //  val message = context.resources.getString("error : ", cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_REASON)))
                            //context.toast(message, Toast.LENGTH_LONG)
                        }
                    }
                    cursor.close()
                }
    
                context.unregisterReceiver(this)
    
            }
        }
    }
    
    /////////// New Testing........
    fun downloadFile(url: String, mimeType: String? = null) {
    
        val guessFileName = URLUtil.guessFileName(url, null, mimeType)
        System.out.println("LLLLLLLLLLLLLLLLLLL2 ");
       // Timber.d("mimeType -> $mimeType guessFileName -> $guessFileName created by url -> $url")
    
        val context = this
    
        downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
    
        val downloadUri = Uri.parse(url)
    
        val request = DownloadManager.Request(downloadUri)
        request.apply {
            setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI)
            //setAllowedOverRoaming(true)
            setTitle(guessFileName)
            setDescription(guessFileName)
            setVisibleInDownloadsUi(true)
            allowScanningByMediaScanner()
            setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    
            //request.setDestinationUri(Uri.fromFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)))
            setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, guessFileName)
    
            context.registerReceiver(receiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))
    
            downloadReference = downloadManager.enqueue(this)
        }
        System.out.println("LLLLLLLLLLLLLLLLLLL23 ");
    }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Bhargav Rao rlgjr    6 年前

    1)下载管理器

    android下载管理器在android 2.3中作为一项优化长期下载处理的服务引入。

    下载管理器处理HTTP连接并监视连接更改。使用下载是一个很好的实践。

    管理器在大多数情况下,特别是在用户会话之间的后台可能继续下载的情况下。

    此类的实例应通过传递download_service通过getsystemservice(string)获取。

    通过此API请求下载的应用程序应注册一个广播接收器,以便用户在通知中或从下载用户界面单击正在运行的下载时,单击“操作通知”以适当处理。

    2)在前台运行服务

    前台服务是一种被认为是用户主动意识到的服务,因此当内存不足时,它不是系统要终止的候选服务。前台服务必须为状态栏提供通知,该状态栏位于“正在进行”标题下,这意味着除非服务停止或从前台删除,否则无法取消通知。

    例如,从服务下载视频应设置为在前台运行,因为用户明确知道其操作。状态栏中的通知可能指示当前下载,并允许用户启动活动以与下载过程交互。

    若要请求您的服务在前台运行,请调用StartForeground()。此方法接受两个参数:一个唯一标识通知和状态栏通知的整数。

    我有一个视频文件(.mp4格式),我希望允许用户将视频下载到他们的SD卡。我目前使用此代码,但它不起作用。

    String PATHSdcard = "/sdcard/Video/";  
    
    public void DownloadFromUrl(String VideoURL, String fileName)         
    
    
    try { URL url = new URL("https://javmed-prod.s3.amazonaws.com/666034cbe81045f2a2da50e5205e376b.mp4");
             File file = new File(fileName);
    
             long sTime = System.currentTimeMillis();
             URLConnection URLcon = url.openConnection();
    
             InputStream is = URLcon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);
    
             ByteArrayBuffer baf = new ByteArrayBuffer(50);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }
    
             FileOutputStream fos = new FileOutputStream(PATHSdcard+file);
             fos.write(baf.toByteArray());
             fos.close();
    
     } catch (IOException e) {
             Log.d("ERROR.......",e+"");
     }
    

        import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.util.Log;
    
    
    public class VideoSaveSDCARD extends Activity{
    
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            ProgressBack PB = new ProgressBack();
            PB.execute("");
        }
    
        private class ProgressBack extends AsyncTask<String,String,String> {
             ProgressDialog PD;
            @Override
            protected void onPreExecute() {
                PD= ProgressDialog.show(LoginPage.this,null, "Please Wait ...", true);
                PD.setCancelable(true);
            }
    
            @Override
            protected void doInBackground(String... arg0) {
            downloadFile("http://beta-vidizmo.com/hilton.mp4","Sample.mp4");            
    
            }
            protected void onPostExecute(Boolean result) {
                PD.dismiss();
    
            }
    
        }
    
    
    
        private void downloadFile(String fileURL, String fileName) {
            try {
            String rootDir = Environment.getExternalStorageDirectory()
                    + File.separator + "Video";
               File rootFile = new File(rootDir);
               rootFile.mkdir();
                URL url = new URL(fileURL);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                FileOutputStream f = new FileOutputStream(new File(rootFile,
                        fileName));
                InputStream in = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = in.read(buffer)) > 0) {
                    f.write(buffer, 0, len1);
                }
                f.close();
        } catch (IOException e) {
            Log.d("Error....", e.toString());
        }
    
    }
    
        2
  •  0
  •   ibad ur rahman    6 年前

    使用以下库:

      implementation 'com.mindorks.android:prdownloader:0.5.0'
    

    从给定URL下载视频的代码如下:

     fun downfile(urll:String,fileName:String){
    
    
    
        if(!isFilePresent(fileName)) {
            var mFile2: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")
            System.out.println("File Foond " + mFile2!!.absolutePath)
            var mFile3: File? = File(Environment.getExternalStorageDirectory(), "WallpapersBillionaire")
    
            var downloadId = PRDownloader.download(urll, mFile2!!.absolutePath, fileName)
                    .build()
                    .setOnStartOrResumeListener(object : OnStartOrResumeListener {
                        override fun onStartOrResume() {
                            System.out.println("??????????????????? start")
                        }
                    })
                    .setOnPauseListener(object : OnPauseListener {
                        override fun onPause() {
                        }
                    })
                    .setOnCancelListener(object : OnCancelListener {
                        override fun onCancel() {
                        }
                    })
                    .setOnProgressListener(object : OnProgressListener {
                        override fun onProgress(progress: Progress) {
                            circlePeView.visibility = View.VISIBLE
    
                            var per = (progress.currentBytes.toFloat() / progress.totalBytes.toFloat()) * 100.00
                            //var perint = per*100
                            System.out.println("::??????????????????? Per : " + per + " ?? : " + progress.currentBytes + " ?? : " + progress.totalBytes)
    
                            circlePeView.setProgress(per.toInt())
                        }
                    })
                    .start(object : OnDownloadListener {
                        override fun onDownloadComplete() {
    
                            circlePeView.visibility = View.GONE
                            circlePeView.setProgress(0)
                            prefs = getSharedPreferences(PREFS_FILENAME, 0)
    
                            val editor = prefs!!.edit()
                            editor.putString(wall, "WallpapersBillionaire/" + fileName)
                            editor.apply()
    
                            try {
                                val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
                                try {
                                    myWallpaperManager.setResource(R.raw.wallp)
                                } catch (e: IOException) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace()
                                }
    
                                val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                                        ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
                                startActivity(intent)
                            } catch (e: Exception) {
                                val intent = Intent()
                                intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
                                try {
                                    startActivity(intent)
                                }catch (e2: java.lang.Exception){
                                    Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
                                }
    
                            }
                            System.out.println("??????????????????? complete")
                        }
    
                        override fun onError(error: Error) {
                            System.out.println("??????????????????? error " + error)
                        }
                    })
            System.out.println("??????????????????? called")
        }else{
            System.out.println("File Foond ")
            circlePeView.visibility = View.GONE
            circlePeView.setProgress(0)
            prefs = getSharedPreferences(PREFS_FILENAME, 0)
    
            val editor = prefs!!.edit()
            editor.putString(wall, "WallpapersBillionaire/" + fileName)
            editor.apply()
    
            try {
                val myWallpaperManager = WallpaperManager.getInstance(applicationContext)
                try {
                    myWallpaperManager.setResource(R.raw.wallp)
                } catch (e: IOException) {
                    // TODO Auto-generated catch block
                    e.printStackTrace()
                }
    
                val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                        ComponentName(this@AnimattedViewpagerActivity, VideoLiveWallpaperService::class.java))
                startActivity(intent)
            } catch (e: Exception) {
                val intent = Intent()
                intent.setAction(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
    
                try {
                    startActivity(intent)
                }catch (e2: java.lang.Exception){
                    Toast.makeText(applicationContext,"Please long click on your home screen. Select Video Live Wallpapers form thier. Thanks",Toast.LENGTH_LONG).show()
                }
    
            }
            System.out.println("??????????????????? complete")
        }
    }