首先是service:
service 自定义返回的IBinder:
/**
* DownloadBinder中定义了一些实用的方法
*/
public class DownloadBinder extends Binder
{
public void start()
{
new Thread()
{
public void run()
{
createNotification(NOTIFY_ID); //创建通知
startDownload(); //下载
};
}.start();
}
/**
* 获取进度
* @return 进度
*/
public int getProgress()
{
return progress;
}
/**
* 设置版本信息对象
* @param vi 版本信息对象
*/
public void setVersionInfo(VersionInfo vi){
versionInfo = vi;
}
}
其中activity通过获取到的IBinder操作这个service的两个耗时但最重要的方法:
/**
* 创建通知
* @param notifyId 通知的ID
*/
private void createNotification(int notifyId) {
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "开始下载";
long when = System.currentTimeMillis();
notification = new Notification(icon, tickerText, when);
// 放置在"正在运行"栏目中
notification.flags = Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
R.layout.downotice);
contentView.setTextViewText(R.id.fileName, "正在下载:" + versionInfo.getApkName());//TODO 文件名
// 指定个性化视图
notification.contentView = contentView;
Intent intent = new Intent(this, LoginActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 指定内容意图
notification.contentIntent = contentIntent;
// 最后别忘了通知一下,否则不会更新
notificationManager.notify(notifyId, notification);
}
/**
* 下载
*/
public void startDownload(){
InputStream is = null;
FileOutputStream fos = null;
try {
//初始化数据
fileSize = 0;
readSize = 0;
downSize = 0;
progress = 0;
HttpClient client = new DefaultHttpClient();
String apkUrl = getApkUrl(versionInfo);
HttpGet get = new HttpGet(apkUrl);