写在前面
下载更新是一个普通到不能再普通,每个app又不得不有的一个功能。本着学习积累的目的,尝试实现了一个简单但实用的Demo。用到了Service,Broadcast,Thread及Notification。
需求
app后台进行下载更新,前台展示下载进度,下载完毕自动跳转安装界面。
思路
由于下载更新这类属于耗时操作,不能在主线程(UI线程)中进行。所以考虑在主线程中开启一个服务(Service),并在服务中开启一个子线程来进行下载任务。前台如何展示下载进度呢?这就涉及到了前台界面Activity与Service的通信。首先想到的是,要不要绑定一个服务?绑定服务会和前台界面共存亡,前台界面销毁,后台服务也会被回收,用户体验不好。所以考虑使用Broadcast来广播下载进度。后台服务为了更长命,考虑将其提升成前台服务startFroground(),启动Notification顺便还能在用户退出应用时展示下载进度。这是需求前半段的思路;下载完成后发送一个隐式广播调起系统的apk安装程序进行新版,这个是需求的后半段思路。
实现
- MainActivity检测下载更新,代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//如果下载的线程正在运行中,启动下载服务时不再启动下载线程
if (downloadThreadAvailed(DownloadAPKService.DOWNLOAD_THREAD_NAME)) {
Intent intent = new Intent(this, UpdateActivity.class);
intent.putExtra(START_DOWNLOAD_EXTRA, true);
intent.putExtra(UPDATE_URL_EXTRA, URL_STR);
startActivity(intent);
finish();
} else {
new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("检测到新版本,是否现在更新应用?")
.setCancelable(false)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent it = new Intent(MainActivity.this, UpdateActivity.class);
it.putExtra(UPDATE_URL_EXTRA, URL_STR);
startActivity(it);
finish();
}
})
.show();
}
}
//判断线程是否处于活动状态
private boolean downloadThreadAvailed(String threadName) {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread thread : threads) {
if (TextUtils.equals(thread.getName(), threadName))
return true;
}
return false;
}
- UpdateActivity开启下载服务,注册广播接收者,接收下载进度,代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
//展示下载进度view控件
mPb = (ProgressBar) findViewById(R.id.pb);
mTextView = (TextView) findViewById(R.id.proText);
//获取下载链接等
Intent it = getIntent();
String mUrl = it.getStringExtra(UPDATE_URL_EXTRA);
//接收下载事件广播
mBroadcast = new UpdateProgressBroadcast();
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_WAITING_ACTION);
filter.addAction(UPDATE_PROGRESS_ACTION);
filter.addAction(UPDATE_COMPLETE_ACTION);
filter.addAction(UPDATE_FAILED_ACTION);
//注册广播接收者,不要忘记在onDestroy方法中解除注册
registerReceiver(mBroadcast, filter);
//开启下载服务,不要忘记在onDestroy方法中停止服务
startDownloadService(mUrl);
}
private void startDownloadService(String url) {
Intent it = new Intent(this, DownloadAPKService.class);
//继续把下载地址带到服务中去
it.putExtra(UPDATE_URL_EXTRA, url);
startService(it);
}
private void stopDownloadService() {
stopService(new Intent(UpdateActivity.this, DownloadAPKService.class));
}
- UpdateProgressBroadcast作为UpdateActivity的内部类被定义,其具体实现如下:
public class UpdateProgressBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case UPDATE_WAITING_ACTION:
//下载前准备动作
mTextView.setText("Waiting..");
break;
case UPDATE_PROGRESS_ACTION:
//更新进度条
int value = ((int) intent.getDoubleExtra(PROGRESS_VALUE_EXTRA, 0));
if (mPb != null) {
mPb.setProgress(value);
}
mTextView.setText(value + "%");
break;
case UPDATE_COMPLETE_ACTION:
//下载完成
mTextView.setText("Download complete!");
break;
case UPDATE_FAILED_ACTION:
//下载失败
mTextView.setText("Download failed!");
break;
}
}
}
千万不要忘记在配置文件中配置自定义广播,值得注意的是,action的格式必须以“com.”开头的字符串。配置文件代码如下:
<receiver android:name="com.miner.UpdateActivity$UpdateProgressBroadcast">
<intent-filter android:priority="1000">
<action android:name="com.update_waiting_action"/>
<action android:name="com.update_progress_action"/>
<action android:name="com.update_complete_action"/>
<action android:name="com.update_failed_action"/>
</intent-filter>
</receiver>
配置文件中配置服务
<service
android:name="com.miner.updatedemo.service.DownloadAPKService"
android:enabled="true"
android:exported="false" />
当然还有相应的权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- 最后是核心类DownloadAPKService的实现:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(LOG_TAG, "onStartCommand");
String url = intent.getStringExtra(MainActivity.UPDATE_URL_EXTRA);
//构建前台Notification,关于Notification的使用,可以参考官方文档
//文档给的例子足够简单明了
Intent notifyIntent = new Intent(this, UpdateActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notifyIntent.putExtra(UPDATE_URL_EXTRA, url);
notifyIntent.putExtra(START_DOWNLOAD_EXTRA, true);
PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Update Download")
.setContentText("下载更新中")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(notifyPendingIntent);
//开启下载线程
mIsStart = true;
DownloadRunnable mRunnable = new DownloadRunnable(url);
new Thread(mRunnable, DOWNLOAD_THREAD_NAME).start();
// 开启前台服务。
startForeground(ID, mBuilder.build());
return super.onStartCommand(intent, flags, startId);
}
- 下载任务类:
private class DownloadRunnable implements Runnable {
private final String url;
DownloadRunnable(String url) {
this.url = url;
}
@Override
public void run() {
if (mIsStart) {
download(url);
}
}
}
-下载方法:
private void download(String url) {
InputStream is = null;
FileOutputStream fos = null;
mHandler.sendMessage(mHandler.obtainMessage(UPDATE_WAITING));
try {
String filename = url.substring(url.lastIndexOf("/") + 1);
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
is = conn.getInputStream();
mTotalSize = conn.getContentLength();
mApkFile = new File("/sdcard/" + filename);
fos = new FileOutputStream(mApkFile);
byte buf[] = new byte[2048];
int len;
long currentSize = 1;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
currentSize += len;
fos.flush();
mHandler.sendMessageDelayed(mHandler.obtainMessage(UPDATE_PROGRESS, currentSize), 0 * 1000);
}
mHandler.sendMessage(mHandler.obtainMessage(DOWNLOAD_COMPLETE));
} catch (Exception e) {
e.printStackTrace();
mHandler.sendMessage(mHandler.obtainMessage(DOWNLOAD_Failed));
} finally {
Log.e(LOG_TAG, "finally block");
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 下载进度可以直接广播么?其实是可以得,但我更习惯先发送至handler由handler来进行广播。那么Handler的实现代码如下:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Intent intent;
switch (msg.what) {
case UPDATE_WAITING:
//更新Notification显示
mBuilder.setContentText("waiting...")
.setProgress(0, 0, false);
mNotifyManager.notify(ID, mBuilder.build());
//发送广播
sendBroadcast(new Intent().setAction(UpdateActivity.UPDATE_WAITING_ACTION));
break;
case UPDATE_PROGRESS:
//更新Notification显示
double result = (((long) msg.obj) / (double) mTotalSize) * 100;
mBuilder.setProgress(100, (int) result, false)
.setContentText((int) result + "%");
mNotifyManager.notify(ID, mBuilder.build());
//带上下载进度发送广播
intent = new Intent(UpdateActivity.UPDATE_PROGRESS_ACTION);
intent.putExtra(PROGRESS_VALUE_EXTRA, result);
sendBroadcast(intent);
break;
case DOWNLOAD_COMPLETE:
mBuilder.setContentText("Download complete")
.setProgress(0, 0, false);
mNotifyManager.notify(ID, mBuilder.build());
mNotifyManager.cancel(ID);
if (mActivity != null && !mActivity.isFinishing())
mActivity.finish();
stopForeground(true);
installApk(getApplicationContext(), Uri.fromFile(mApkFile));
sendBroadcast(new Intent().setAction(UpdateActivity.UPDATE_COMPLETE_ACTION));
mIsStart = false;
break;
case DOWNLOAD_Failed:
mBuilder.setContentText("Download failed")
.setProgress(0, 0, false);
mNotifyManager.notify(ID, mBuilder.build());
mNotifyManager.cancel(ID);
if (mActivity != null && !mActivity.isFinishing())
mActivity.finish();
stopForeground(true);
sendBroadcast(new Intent().setAction(UpdateActivity.UPDATE_FAILED_ACTION));
mIsStart = false;
break;
}
}
};
以上就是核心代码的实现,总体来讲是比较简单的,有不足的地方希望各路大神指指点点,路过的点个赞呗。
完整代码