Skip to content

Instantly share code, notes, and snippets.

@ixiyang
Last active August 29, 2015 14:01
Show Gist options
  • Save ixiyang/b80c6019c5d367a08a23 to your computer and use it in GitHub Desktop.
Save ixiyang/b80c6019c5d367a08a23 to your computer and use it in GitHub Desktop.
文件下载
//使用Service实现文件下载
public class NewDownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public static final String DOWNLOAD_DIR=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+"/";
public NewDownloadService() {
super("NewDownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
String fileName=intent.getStringExtra("file_name");
ResultReceiver receiver = (ResultReceiver) intent
.getParcelableExtra("receiver");
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
DOWNLOAD_DIR+fileName);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
//下载用的Activity
public class DownloadActivity extends QMBaseActivity{
private ImageView mIvFileImg;
private TextView mTvFileName;
private ProgressBar mProgressBar;
private Button mBtnOperaio;
private String mFileName;
private String mFileUrl;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
@Override
protected int setLayoutId() {
return R.layout.activity_download;
}
@Override
protected void fillData() {
mTvFileName.setText(mFileName);
}
@Override
protected void initTitleBarContent() {
mTitleHelper.centerStr="附件下载";
mTitleHelper.rightPic=0;
}
@Override
protected void initView() {
mIvFileImg=(ImageView) findViewById(R.id.download_iv_file_img);
mTvFileName=(TextView) findViewById(R.id.download_tv_file_name);
mProgressBar=(ProgressBar) findViewById(R.id.download_pb_status);
mBtnOperaio=(Button) findViewById(R.id.download_btn_opreation);
mFileName=getIntent().getStringExtra("file_name");
mFileUrl=getIntent().getStringExtra("url");
}
@Override
protected void regListener() {
mBtnOperaio.setOnClickListener(this);
Intent intent = new Intent(this, NewDownloadService.class);
intent.putExtra("url", mFileUrl);
intent.putExtra("file_name", mFileName);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
//回调的广播
private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == NewDownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mProgressBar.setProgress(progress);
if (progress == 100) {
mProgressBar.setVisibility(View.GONE);
mBtnOperaio.setVisibility(View.VISIBLE);
mBtnOperaio.setText("打开文件");
}
}
}
}
}
//使用AsyncTask实现文件下载
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
private ProgressBar progressBar;
private Button btnOpreation;
private GridItem item;
private String filePath;
public DownloadTask(Context context, GridItem item,
ProgressBar progressBar, Button btn) {
this.context = context;
this.item = item;
this.progressBar = progressBar;
this.btnOpreation = btn;
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
filePath = IMG_DOWNLOAD_DIR + MD5Util.getMD5(sUrl[0])
+ IMG_EXTENSION;
output = new FileOutputStream(filePath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
progressBar.setVisibility(View.GONE);
progressBar.setProgress(0);
if (result != null || isCancelled()) {
Toast.makeText(context, "主题下载失败: " + result, Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(context, "主题下载成功", Toast.LENGTH_SHORT).show();
SharePerferenceControlor.setString(context, item.getTitle(),
filePath);
btnOpreation.setVisibility(View.INVISIBLE);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment