下载图片
public void myClick(View view) {
String imgUrl = "http://img4.duitang.com/uploads/item/201604/29/20160429211449_QjMu4.jpeg";
new ImageTask().execute(imgUrl);
}
class ImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
URL url = null;
InputStream is = null;
Bitmap bitmap = null;
try {
url = new URL(params[0]);
is = url.openStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
img.setImageBitmap(bitmap);
}
}
下载文件
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
public void myClick(View view) {
String downUrl = "http://192.168.1.106/MPC-HC.1.7.10.x86.zip";
new DownloadTask().execute(downUrl);
}
/**
* @params String 下载路径
* @params Integer 下载进度
* @params String 下载结果
*/
class DownloadTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
URL url = null;
InputStream is = null;
FileOutputStream fos = null;
String result = "";
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
int totalLength = connection.getContentLength();
is= connection.getInputStream();
int indexOf = params[0].lastIndexOf('/');
String filename = params[0].substring(indexOf);
fos = new FileOutputStream(savePath + filename);
int len = 0;
int sum = 0;
byte[] bytes = new byte[1024];
while (-1!=(len=is.read(bytes))){
fos.write(bytes,0,len);
sum +=len;
publishProgress(sum*100/totalLength);
}
result = "下载成功";
} catch (MalformedURLException e) {
result = "下载失败";
e.printStackTrace();
} catch (IOException e) {
result = "下载失败";
e.printStackTrace();
}
return result;
}
/**
* 在此方法中更新下载进度
* @param values
*/
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mTv.setText("当前进度"+values[0]+"%");
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mTv.setText(s);
}
}
后台应用升级
/**
* 应用升级服务
*/
public class DownloadService extends Service {
private static final String KEY_TAG = "AppDownloadTask";
public String APP_UPDATE_URL;
public static String mAppName;
private static String SAVE_PATH;
private NotificationManager mManager;
private static final int NOTIFICATION_ID = (int) (System.currentTimeMillis() / 2);
private MyTask mTask;
private int mTotalLength;
private URLConnection mConnection;
private URL mUrl;
private InputStream mInputStream;
private FileOutputStream mFileOutputStream;
@Override
public void onCreate() {
super.onCreate();
/**
* 应用保存地址
*/
SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + getPackageName() + "-update.apk";
/**
* 应用更新路径
*/
APP_UPDATE_URL = "https://12.shouji.com.cn/wb/soft/2017/20170830/8895673712.apk";
/**
* 应用名称
*/
mAppName = getResources().getString(R.string.app_name);
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mTask = new MyTask();
mTask.execute(APP_UPDATE_URL);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 结束任务
* @param task 要结束的异步任务
*/
private void cancelTask(AsyncTask task) {
task.cancel(true);
showErrorNotification();
DownloadService.this.stopSelf();
}
/**
* 创建目录
*
* @param filePath 文件的完整路径
*/
private void autoCreatePath(String filePath) {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
class MyTask extends AsyncTask<String, Integer, Boolean> {
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (!MyTask.this.isCancelled()) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(DownloadService.this);
Notification build = mBuilder.setTicker("正在下载")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("已下载" + values[0] + "%")
.setContentTitle(mAppName)
.setProgress(100, values[0], false)
.build();
mManager.notify(NOTIFICATION_ID, build);
} else {
showErrorNotification();
}
}
@Override
protected Boolean doInBackground(String... strings) {
if (!MyTask.this.isCancelled()) {
try {
mUrl = new URL(strings[0]);
mConnection = mUrl.openConnection();
mTotalLength = mConnection.getContentLength();
mInputStream = mConnection.getInputStream();
autoCreatePath(SAVE_PATH);
mFileOutputStream = new FileOutputStream(SAVE_PATH);
int len = 0;
int sum = 0;
byte[] bytes = new byte[1024];
while (-1 != (len = mInputStream.read(bytes))) {
mFileOutputStream.write(bytes, 0, len);
sum += len;
int current = sum * 100 / mTotalLength;
if (current % 4 == 0) {
publishProgress(current);
}
}
} catch (MalformedURLException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
return false;
} catch (FileNotFoundException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
return false;
} catch (SSLException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
return false;
} catch (IOException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
return false;
} finally {
if (mInputStream != null) {
try {
mInputStream.close();
} catch (IOException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
}
}
if (mFileOutputStream != null) {
try {
mFileOutputStream.close();
} catch (IOException e) {
showErrorNotification();
cancelTask(MyTask.this);
e.printStackTrace();
}
}
}
return true;
} else {
showErrorNotification();
cancelTask(MyTask.this);
return false;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
showSuccessNotification();
} else {
showErrorNotification();
}
DownloadService.this.stopSelf();
}
}
/**
* 获取安装的意图
*
* @param apkFilepath 应用的真实保存路径
* @return
*/
private Intent getInstallIntent(String apkFilepath) {
String apkType = "application/vnd.android.package-archive";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File(apkFilepath)), apkType);
return intent;
}
/**
* 删除下载失败的临时文件
*
* @param filePath
*/
private void deleteTmpFile(String filePath) {
if (!TextUtils.isEmpty(filePath)) {
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
}
}
/**
* 显示成功的通知
*/
private void showSuccessNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, getInstallIntent(SAVE_PATH), PendingIntent.FLAG_UPDATE_CURRENT
);
Notification build = mBuilder.setTicker("完成下载")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("点击安装")
.setContentTitle(mAppName + "下载完成")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
mManager.notify(NOTIFICATION_ID, build);
}
/**
* 显示失败的通知
*/
private void showErrorNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
Notification build = mBuilder.setTicker("下载失败")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(mAppName + "下载失败")
.setAutoCancel(true)
.build();
mManager.notify(NOTIFICATION_ID, build);
deleteTmpFile(SAVE_PATH);
}
}