package com.cai.app.ui;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.cai.app.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;
public class UpdateService extends Service{
private
NotificationManager nm;
private
Notification notification;
private File
tempFile=null;
private
boolean cancelUpdate=false;
private
MyHandler myHandler;
private int
download_precent=0;
private
RemoteViews views;
private int
notificationId=1234;
@Override
public
IBinder onBind(Intent intent) {
return null;
}
@Override
public void
onStart(Intent intent,int startId){
super.onStart(intent, startId);
}
@Override
public int
onStartCommand(Intent intent,int flags,int startId){
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification=new Notification();
notification.icon=android.R.drawable.stat_sys_download;
//notification.icon=android.R.drawable.stat_sys_download_done;
notification.tickerText=getString(R.string.app_name)+"更新";
notification.when=System.currentTimeMillis();
notification.defaults=Notification.DEFAULT_LIGHTS;
//设置任务栏中下载进程显示的views
views=new RemoteViews(getPackageName(),R.layout.update);
notification.contentView=views;
PendingIntent contentIntent=PendingIntent.getActivity(this,0,new
Intent(this,Main.class),0);
notification.setLatestEventInfo(this,"","", contentIntent);
//将下载任务添加到任务栏中
nm.notify(notificationId,notification);
myHandler=new MyHandler(Looper.myLooper(),this);
//初始化下载任务内容views
Message message=myHandler.obtainMessage(3,0);
myHandler.sendMessage(message);
//启动线程开始执行下载任务
downFile(intent.getStringExtra("url"));
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy(){
super.onDestroy();
}
//下载更新文件
private void downFile(final String url) {
new Thread() {
public void run(){
try
{ HttpClient client = new
DefaultHttpClient(); //
params[0]代表连接的url 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(Environment.getExternalStorageDirectory(),
"/pinke");
if(!rootFile.exists()&&!rootFile.isDirectory())