实例介绍
【实例截图】
【核心代码】
public class UpdateService extends Service{
private final IBinder binder = new UpdateBinder();
private String filePath;
private NotificationManager nm;
private Notification notification;
private RemoteViews romote;
private int notificationId=1234;
private int downPre=0;
private DownHandler downHandler;
private String appName="android-mvc.apk";
private File tempFile=null;
private boolean canUpdate=false;
@Override
public void onCreate(){
try{
super.onCreate();
//创建client实例
//例sysClient = new SysClient();
//获取配置文件里的数据
filePath = Environment.getExternalStorageDirectory() ReadProperties.getPropertyByStr("");
//创建和服务器交互的实例并执行
//例 new CheckUpdate().execute("");
}catch(Exception e){
e.printStackTrace();
this.stopSelf();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
public class UpdateBinder extends Binder{
public UpdateService getService(){
return UpdateService.this;
}
}
// 和服务器交互的方法
@SuppressWarnings("unused")
private class CheckUpdate extends AsyncTask<String, Integer, Boolean> {
ResponseObject resInfo=null;
@Override
protected Boolean doInBackground(String... params) {
try {
//resInfo=sysClient.checkUpdate(Cache.VERNAME);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
try {
if(result){
if(resInfo!=null && resInfo.getSuccess().equals(Constants.RESPONSE_SUCCESS)){
String isUpdate=resInfo.getString("isUpdate");
String updateInfo=resInfo.getString("updateInfo");
String updateUrl=resInfo.getString("updateUrl");
String verName=resInfo.getString("verName");
// 1可选升级2强制升级
//Intent intent = new Intent(getApplicationContext(),SysUpdateActivity.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent = new Intent();
intent.putExtra("isUpdate", isUpdate);
intent.putExtra("updateInfo", updateInfo);
intent.putExtra("updateUrl", updateUrl);
intent.putExtra("verName", verName);
intent.setAction(Constants.INTENT_FILTER_UPDATE);
getApplicationContext().sendBroadcast(intent);
}
}else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//升级
@SuppressWarnings("deprecation")
public void addUpdate(String downUrl) {
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new Notification();
notification.icon = android.R.drawable.stat_sys_download;
notification.tickerText="掌上医疗-疾控版升级";
notification.when=System.currentTimeMillis();
notification.defaults=Notification.DEFAULT_LIGHTS;
//设置任务栏中下载进程显示的views
romote=new RemoteViews(getPackageName(),R.layout.update);
romote.setTextViewText(R.id.doc_name,"掌上医疗-疾控版升级包");
notification.contentView=romote;
PendingIntent contentIntent=PendingIntent.getActivity(this,0,new Intent(),0);
notification.setLatestEventInfo(this,"","", contentIntent);
//将下载任务添加到任务栏中
nm.notify(notificationId,notification);
downHandler=new DownHandler(Looper.myLooper(),this);
//初始化下载任务内容views
Message message=downHandler.obtainMessage(3,0);
downHandler.sendMessage(message);
//启动线程开始执行下载任务
downFile(downUrl,filePath,appName);
}
// 下载文件
private void downFile(final String url, final String filepath,final String filename) {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
if (is != null) {
File rootFile = new File(filepath);
if (!rootFile.exists()) {
rootFile.mkdirs();
}
tempFile = new File(filepath "/" filename);
System.out.println("****" filepath);
System.out.println("----" url);
System.out.println(" " filename);
if (tempFile.exists()) {
tempFile.delete();
}
tempFile.createNewFile();
// 已读出流作为参数创建一个带有缓冲的输出流
BufferedInputStream bis = new BufferedInputStream(is);
// 创建一个新的写入流,讲读取到的图像数据写入到文件中
FileOutputStream fos = new FileOutputStream(tempFile);
// 已写入流作为参数创建一个带有缓冲的写入流
BufferedOutputStream bos = new BufferedOutputStream(fos);
int read;
long count = 0;
int precent = 0;
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer)) != -1 && !canUpdate) {
bos.write(buffer, 0, read);
count = read;
precent = (int) (((double) count / length) * 100);
// 每下载完成5%就通知任务栏进行修改下载进度
if (precent - downPre >= 5) {
downPre = precent;
Message message = downHandler.obtainMessage(3,precent);
downHandler.sendMessage(message);
}
}
bos.flush();
bos.close();
fos.flush();
fos.close();
is.close();
bis.close();
}
if (!canUpdate) {
Message message = downHandler.obtainMessage(2, tempFile);
downHandler.sendMessage(message);
} else {
tempFile.delete();
}
} catch (ClientProtocolException e) {
Message message = downHandler.obtainMessage(4, "下载文件失败");
downHandler.sendMessage(message);
} catch (IOException e) {
Message message = downHandler.obtainMessage(4, "下载文件失败");
downHandler.sendMessage(message);
} catch (Exception e) {
Message message = downHandler.obtainMessage(4, "下载文件失败");
downHandler.sendMessage(message);
}
}
}.start();
}
@SuppressLint("HandlerLeak")
private class DownHandler extends Handler {
private Context context;
public DownHandler(Looper looper, Context c) {
super(looper);
this.context = c;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg != null) {
switch (msg.what) {
case 0:
Toast.makeText(context, msg.obj.toString(),
Toast.LENGTH_SHORT).show();
break;
case 1:
break;
case 2:
// 下载完成后清除所有下载信息,执行打开提示
downPre = 0;
nm.cancel(notificationId);
// 停止掉当前的服务
stopSelf();
Toast.makeText(context, "下载完毕!", Toast.LENGTH_SHORT).show();
openFile(filePath "/" appName);
break;
case 3:
// 更新状态栏上的下载进度信息
romote.setTextViewText(R.id.doc_progress, "已下载" downPre
"%");
romote.setProgressBar(R.id.doc_progressbar, 100, downPre,
false);
notification.contentView = romote;
nm.notify(notificationId, notification);
break;
case 4:
Toast.makeText(context, "下载失败!", Toast.LENGTH_SHORT).show();
nm.cancel(notificationId);
break;
}
}
}
}
// 下载后打开文件
private void openFile(String path) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(path));
String type = MimeTypeHelper.getMIMEType(path);
intent.setDataAndType(uri, type);
startActivity(intent);
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论