【问题标题】:How can I resume my download by onResume() in android?如何在 android 中通过 onResume() 恢复下载?
【发布时间】:2014-07-06 14:33:27
【问题描述】:

我的应用程序有一个“开始下载”和一个“暂停”按钮。一旦我通过“开始下载”按钮开始下载,当我按下返回或主页按钮时,我的下载开始并在单击“暂停”时停止,onPause() 函数按预期工作,它会暂停我的下载,当我再次打开应用程序并单击start 它从那个进度恢复,

我想要的是,在我按下返回或主页后切换回(不是第一次加载应用程序)到应用程序时,我希望通过 onResume 自动恢复下载,而无需再次单击开始按钮。现在在下面的代码中,由于我的 onResume(),我的下载自动开始而不做任何事情,我是否可以使用 onResume 继续,但在第一次通过它加载应用程序时不能自动开始下载?我知道下面的代码没有它本来可以的效率。对此深表歉意。

再次,我希望我的 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;
        }
    }

【问题讨论】:

  • 您可以尝试在onSaveInstanceState() 的outState Bundle 中存储一个标志,该标志可以在onCreate() 中检索。基于此,您可以决定是否自动开始下载。如果您想要更高的可靠性,请将其永久存储在onPause,而不是onSaveInstanceState()

标签: java android android-activity onresume onpause


【解决方案1】:

您似乎已经为该功能准备了大部分代码。在 onResume 中,您可以调用 ASyncTask,如果文件存在,它应该开始下载(在 onPause() 中暂停下载,文件存在)。我写过类似的代码,你可以在这里找到:https://github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java 在我的代码中,您可以发现我没有使用 onPause 和 onResume,而是在这段时间内使用了唤醒锁。

【讨论】:

  • 如果文件存在,我尝试在 onresume 时调用我的 asynctask,但是程序不会执行并最终给我停止工作错误。对不起,我忘了提到这是我第一次在 android 中编写任何东西。 :|
  • 是否有可以针对错误发布的堆栈跟踪?
猜你喜欢
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
  • 2017-09-07
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多