簡體   English   中英

如何在Android中通過onResume()恢復下載?

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

我的應用程序有一個“開始下載”和一個“暫停”按鈕。 一旦我通過“開始下載”按鈕開始下載,我的下載就會開始並在單擊“暫停”時停止,現在當我按返回或主頁按鈕時,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;
        }
    }

您似乎已經為該功能准備了大部分代碼。 在onResume中,您可以調用ASyncTask,並且如果文件存在(它在onPause()中已暫停下載,文件存在),它應該開始下載。 我寫了類似的代碼,您可以在這里找到它: 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