从Kotlin Android中的网址下载视频?

时间:2019-01-14 07:14:18

标签: android kotlin

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

  

E / ContentProviderNative:来自{P:12600; U:11003}的onTransact错误   2019-01-14 11:54:35.423 3518-22398 /? E / DatabaseUtils:将异常写入宗地       java.lang.IllegalArgumentException:未知URI:content:// downloads / public_downloads / 6796           在com.android.providers.downloads.DownloadProvider.query(DownloadProvider.java:914)           在android.content.ContentProvider.query(ContentProvider.java:1138)           在android.content.ContentProvider.query(ContentProvider.java:1230)           在android.content.ContentProvider $ Transport.query(ContentProvider.java:251)           在android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)           在android.os.Binder.execTransact(Binder.java:752)   enter image description here

视频文件下移的

代码如下:     private var download参考:Long = 0     私人lateinit var downloadManager: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 个答案:

答案 0 :(得分:1)

使用以下库:

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

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

 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")
    }
}

答案 1 :(得分:0)

1)下载管理器

Android 2.3中引入了Android下载管理器,以优化长时间运行的下载的处理。

下载管理器处理HTTP连接并监视连接更改。使用下载是一个好习惯。

在大多数情况下为管理员,尤其是在用户会话之间可能在后台继续下载的情况下。

此类的实例应通过传递DOWNLOAD_SERVICE的getSystemService(String)获取。

通过此API请求下载的应用应为ACTION_NOTIFICATION_CLICKED注册一个广播接收器,以便在用户单击通知或下载用户界面中正在运行的下载时正确处理。

2)在前台运行服务

前台服务是一种被认为是用户积极了解的服务,因此不是内存不足时系统被杀死的候选对象。前台服务必须为状态栏提供一个通知,该通知位于“正在进行”标题下,这意味着除非该服务已停止或从前台中删除,否则无法取消该通知。

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

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

我有一个视频文件(.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());
    }

}