简体   繁体   English

如何在 Internet 恢复或重新创建 Activity 时恢复下载

[英]How To Resume Download When Internet is Restored or When Activity is Recreated

I am using AsyncTask to download videos from a URL link using the code below我正在使用 AsyncTask 使用以下代码从 URL 链接下载视频

 public static class DownloadTask extends AsyncTask<String, Void, String> {
    WeakReference<MainActivity>weakReference;

     DownloadTask(MainActivity activity) {
        weakReference = new WeakReference<>(activity);
    }

    int TIMEOUTTIME = 7000;
    int TSOCKET = 30000;
    String TAG = "TAG";

    @Override
    protected String doInBackground(String... strings) {
        MainActivity subActivity = weakReference.get();
        if (!(activity == null || activity.isFinishing())){
            try {
                URL url = new URL(subActivity.videoUrl);
                long beginTime = System.currentTimeMillis();
                Log.i(TAG, "video download starting at: " + subActivity.videoUrl);

                //Open a connection to that URL.
                URLConnection urlCon = url.openConnection();

                urlCon.setReadTimeout(TIMEOUTTIME);
                urlCon.setConnectTimeout(TSOCKET);

                InputStream is = urlCon.getInputStream();
                BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
                activity.fileTitle = "oneTooMuch TYPE.mp4";
                FileOutputStream outStream  = activity.openFileOutput(activity.fileTitle,MODE_PRIVATE);
              
                byte[] buff = new byte[5 * 1024];

                while ((len = inStream.read(buff)) != -1) {
                    outStream.write(buff, 0, len);
                }

                outStream.flush();
                outStream.close();
                inStream.close();

                Log.i(TAG, "download completed in "
                        + ((System.currentTimeMillis() - startTime) / 1000)
                        + " sec");

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "Out Condition";
    }

The code works well for downloading video files, but when there is a disconnection while downloading, maybe because of internet problems or onDestroy of activity, I need a way to resume the download when the internet is restored or when activity is restarted.该代码适用于下载视频文件,但是当下载时断开连接时,可能是由于互联网问题或活动的 onDestroy,我需要一种在互联网恢复或活动重新启动时恢复下载的方法。 Can anyone help with a code snippet or hint on how I can achieve this?任何人都可以提供代码片段或提示我如何实现这一点吗? I would really be grateful if anyone can help.如果有人能提供帮助,我将不胜感激。

Better solution will be to use Service instead of AsyncTask .更好的解决方案是使用Service而不是AsyncTask Services run separately from the application and have higher priority.服务与应用程序分开运行并具有更高的优先级。 You can let user continue downloading even when he closes the app, and provide him with the notification with progress, this is handy because it provides better user experience for example user can download video while watching one he already downloaded.即使用户关闭应用程序,您也可以让用户继续下载,并向他提供进度通知,这很方便,因为它提供了更好的用户体验,例如用户可以在观看他已经下载的视频的同时下载视频。 To do this you will need to return move service into foreground and return START_REDILIVER_INTENT from onStartCommand .为此,您需要将移动服务返回到前台并从onStartCommand返回START_REDILIVER_INTENT Also if you don't want to use Service you can use WorkManager for background operations此外,如果您不想使用 Service,您可以使用 WorkManager 进行后台操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 旋转屏幕时如何重新创建Android Activity? - How is an Android Activity recreated when the screen is rotated? 重新创建活动时的 onActivityResult() 函数? - onActivityResult() function when Activity is recreated? 重新启动活动后,如何还原活动的片段? - How do fragments of an activity get restored when the activity restarts? 用户回来时如何恢复Webview活动 - how to resume webview activity when user comeback 重新创建活动时,可扩展列表视图侦听器不起作用 - Expandable list view listener does not work when activity is recreated 使用viewPager时无法恢复活动 - Unable to resume an activity when using a viewPager 尝试为 imageview 设置图像时无法恢复活动 - Unable to resume activity when try to setImage for imageview 仅在恢复活动时获取 IndexOutOfBoundsException - Getting IndexOutOfBoundsException only when resume Activity 活动恢复时 ExpandableListAdapter getChildrenCount 空指针异常 - ExpandableListAdapter getChildrenCount null pointer exception when activity restored 有互联网时自动刷新活动 - Automatically refresh Activity when Internet is there
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM