简体   繁体   English

如何在Android中通过onResume()恢复下载?

[英]How can I resume my download by onResume() in android?

My application has a "start download" and a "pause" button. 我的应用程序有一个“开始下载”和一个“暂停”按钮。 Once I start the download through "Start Download" button my download starts and stop upon clicking "pause" now when I press back or home button the onPause() function works as intended it pauses my download and when I open the app again and click start it resumes from that progress, 一旦我通过“开始下载”按钮开始下载,我的下载就会开始并在单击“暂停”时停止,现在当我按返回或主页按钮时,onPause()函数将按预期工作,它会暂停我的下载,当我再次打开该应用程序并单击从这一进展开始,

what I want is that upon switching back(not the first time load of app) to the application once I have pressed back or home I want the download to resume automatically by onResume without clicking start button again. 我想要的是,一旦按回去或回家后,切换回应用程序(不是第一次加载应用程序)后,我希望通过onResume自动恢复下载,而无需再次单击开始按钮。 Right now in below code my download automatically starts without doing anything which is due to my onResume(), is it possible that I can resume with onResume but not start the download automatically upon first time loading of the app thorugh it? 现在在下面的代码中,由于我的onResume()原因,我的下载自动开始而没有执行任何操作,是否有可能我可以继续使用onResume而不在第一次加载应用程序时自动开始下载? I know the below code is not as efficient as it could have been. 我知道以下代码效率不如预期。 Apologies for that. 对此表示歉意。

Again, I want my onResume to only resume my previously downloaded file not start the download unless download was once initiated through the button. 再次,我希望我的onResume仅恢复我以前下载的文件,而不要开始下载,除非曾经通过按钮启动下载。

public class MainActivity extends Activity implements OnClickListener{
    String url = "http://upload.wikimedia.org/wikipedia/commons/1/11/HUP_10MB_1946_obverse.jpg";
    boolean mStopped=false;

     private ProgressBar progressBar2;
     private String filepath = "MyFileStorage";
     private File directory;
     private TextView finished;
        @Override
        protected void onPause() {
         super.onPause();
         mStopped=true;
        }
        @Override
        protected void onResume() {
         super.onResume();
         mStopped=false;
         grabURL(url);
        }

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

            ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
            directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);

            progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
            progressBar2.setVisibility(View.GONE);
            finished = (TextView) findViewById(R.id.textView1);
            finished.setVisibility(View.GONE);


      Button stop = (Button) findViewById(R.id.stop);
      stop.setOnClickListener(this);
      Button download = (Button) findViewById(R.id.download);
      download.setOnClickListener(this);

        }

        public void onClick(View v) {

      switch (v.getId()) {

      case R.id.stop:
            mStopped=true;
       break;

      case R.id.download:
          mStopped=false;
       grabURL(url); 
       break; 



      }
     }

        public void grabURL(String url) {
      new GrabURL().execute(url);
     }

     private class GrabURL extends AsyncTask<String, Integer, String> {


      protected void onPreExecute() {
       progressBar2.setVisibility(View.VISIBLE);
             progressBar2.setProgress(0);
             finished.setVisibility(View.GONE);

         }

      protected String doInBackground(String... urls) {



       String filename = "MySampleFile.png";
       File myFile = new File(directory , filename);

       try {
                 URL url = new URL(urls[0]);
                 URLConnection connection = url.openConnection();
                 if (myFile.exists())
                 {
                     connection.setAllowUserInteraction(true);
                     connection.setRequestProperty("Range", "bytes=" + myFile.length() + "-");
                 }
                 connection.connect();
                 int fileLength = connection.getContentLength(); 
                 fileLength += myFile.length(); 
                 InputStream is = new BufferedInputStream(connection.getInputStream());
                 RandomAccessFile os = new RandomAccessFile(myFile, "rw");


                 os.seek(myFile.length());

                 byte data[] = new byte[1024];
                 int count;
                 int __progress = 0;
                 while ((count = is.read(data)) != -1 && __progress != 100) {
                     if (mStopped) {
                           throw new IOException();
                     }
                     else{
                     __progress = (int) ((myFile.length() * 100) / fileLength);
                     publishProgress((int) (myFile.length() * 100 / fileLength));
                     os.write(data, 0, count);}
                 }
                 os.close();
                 is.close();

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

       return filename;

      }

      protected void onProgressUpdate(Integer... progress) {
       finished.setVisibility(View.VISIBLE);
       finished.setText(String.valueOf(progress[0]) + "%");
       progressBar2.setProgress(progress[0]);
         }

      protected void onCancelled() {
       Toast toast = Toast.makeText(getBaseContext(), 
         "Error connecting to Server", Toast.LENGTH_LONG);
       toast.setGravity(Gravity.TOP, 25, 400);
       toast.show();

      }

      protected void onPostExecute(String filename) {
              progressBar2.setProgress(100);
              finished.setVisibility(View.VISIBLE);
              finished.setText("Download in progress..");
              File myFile = new File(directory , filename);
              ImageView myImage = (ImageView) findViewById(R.id.imageView1);
              myImage.setImageBitmap(BitmapFactory.decodeFile(myFile.getAbsolutePath()));

      }

     }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
    }

You seem to already have most of the code in place for the functionality. 您似乎已经为该功能准备了大部分代码。 In onResume you can call your ASyncTask and it should start download if the file exists (paused download in onPause(), file exists). 在onResume中,您可以调用ASyncTask,并且如果文件存在(它在onPause()中已暂停下载,文件存在),它应该开始下载。 I have written similar code, you can find it here: https://github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java In my code you can find that instead of using onPause and onResume, I just have a wakelock for that period of time. 我写了类似的代码,您可以在这里找到它: https : //github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java在我的代码中,您可以找到它而不是使用onPause在onResume上,我在那段时间里只有一个唤醒锁。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM