如何通过android中的onResume()恢复我的下载?

时间:2014-07-06 14:33:28

标签: java android android-activity onresume onpause

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

我想要的是,在我按下或回家后切换回应用程序(不是第一次加载应用程序)到应用程序时,我希望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;
        }
    }

1 个答案:

答案 0 :(得分:0)

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