如何在android中下载服务中的文件

时间:2016-11-06 08:37:15

标签: android android-service android-download-manager

我想要server中的下载文件,我想在服务等后台下载。

我的代码是:

public class MainActivity extends AppCompatActivity {

    Button download;
    TextView downloadCount;
    ProgressBar progressBar;

    Future<File> downloading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Enable global Ion logging
        Ion.getDefault(this).configure().setLogging("ion-sample", Log.DEBUG);

        setContentView(R.layout.activity_main);

        download = (Button) findViewById(R.id.download);
        downloadCount = (TextView) findViewById(R.id.download_count);
        progressBar = (ProgressBar) findViewById(R.id.progress);

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/dir1/dir2");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        final File file = new File(dir, "filename.zip");

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (downloading != null && !downloading.isCancelled()) {
                    resetDownload();
                    return;
                }

                download.setText("Cancel");
                // this is a 180MB zip file to test with
                downloading = Ion.with(MainActivity.this)
                        .load("http://cdn.p30download.com/?b=p30dl-software&f=PCWinSoft.1AVMonitor.v1.9.1.50_p30download.com.rar")
                        // attach the percentage report to a progress bar.
                        // can also attach to a ProgressDialog with progressDialog.
                        .progressBar(progressBar)
                        // callbacks on progress can happen on the UI thread
                        // via progressHandler. This is useful if you need to update a TextView.
                        // Updates to TextViews MUST happen on the UI thread.
                        .progressHandler(new ProgressCallback() {
                            @Override
                            public void onProgress(long downloaded, long total) {
                                downloadCount.setText("" + downloaded + " / " + total);
                            }
                        })
                        // write to a file
                        .write(file)
                        // run a callback on completion
                        .setCallback(new FutureCallback<File>() {
                            @Override
                            public void onCompleted(Exception e, File result) {
                                resetDownload();
                                if (e != null) {
                                    Toast.makeText(MainActivity.this, "Error downloading file", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                Toast.makeText(MainActivity.this, "File upload complete", Toast.LENGTH_LONG).show();
                            }
                        });
            }
        });
    }

    void resetDownload() {
        // cancel any pending download
        downloading.cancel();
        downloading = null;

        // reset the ui
        download.setText("Download");
        downloadCount.setText(null);
        progressBar.setProgress(0);
    }
}

我写上面的代码,但我不知道如何将此代码写入service并在后台下载文件。

如何在服务中编写此代码?

1 个答案:

答案 0 :(得分:0)

可以使用context.startService(intent)启动服务。 服务启动后,它的生命周期执行如下(按顺序):

  1. onCreate()
  2. onStartCommand()
  3. 当服务停止或销毁时,会调用onDestroy()方法。

    现在要下载服务中的文件,请按以下方式调用startService()方法(在本例中来自您的活动):

    Intent intent = new Intent(MainActivity.this, ServiceName.class);
    startService(intent);
    

    这将启动该服务。现在开始下载过程,请调用downloadFile()方法,如下所示:

    public class ServiceName extends Service {
        @Override
        public void onCreate() {
            super.onCreate();
            //Start download process
            downloadFile();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // We want this service to continue running until it is explicitly
            // stopped, so return 
            return START_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
        }
    
        private void downloadFile() {
            //Logic to download the file.
            .
            .
            .
        }
    }
    

    此外,您可以将service绑定到activity以传递它们之间的回调,并绑定服务w / activity的生命周期。有关详细信息,请查看此link