花了3个多小时 完成自动更新并安装
package com.aizheke.aizheked.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.RemoteViews;
import com.aizheke.aizheked.MainActivity;
import com.aizheke.aizheked.R;
public class UpdateService extends IntentService {
private final String UPDATE_URL = "http://www.aizheke.com/test.apk";
private final String TAG = "update";
private final int TIMEOUTCONNECTION = 10000;
private final int TIMEOUTSOCKET = 30000;
private final String FOLDER = "Downloads";
private final String FILENAME = "aizheke.apk";
private NotificationManager notificationManager;
private Notification notification;
private final int resourceId = 88888;
private File FILE;
public UpdateService() {
super("AZK_UPDATE");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "开始下载");
try {
startNotification();
HttpParams httpParameters = new BasicHttpParams();
// 设置连接超时
HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUTCONNECTION);
// 读取数据超时
HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUTSOCKET);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet httpGet = new HttpGet(UPDATE_URL);
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
} else {
HttpEntity entity = response.getEntity();
saveToSDCard(entity.getContent(), response.getEntity().getContentLength());
}
} catch (Exception e) {
Log.e(TAG, "UpdateService Exception:" + e.getMessage());
}
}
private void saveToSDCard(InputStream is, long updateTotalSize) throws IOException {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File folder = new File(Environment.getExternalStorageDirectory(),
FOLDER);
if (!folder.exists()) {
folder.mkdirs();
}
FILE = new File(folder, FILENAME);
OutputStream os = new FileOutputStream(FILE);
copyStream(is, os, updateTotalSize);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Log.e(TAG, "SD卡只读");
} else {
Log.e(TAG, "手机没有SD卡");
}
}
private void copyStream(InputStream is, OutputStream os, long updateTotalSize) throws IOException {
int buffer_size = 4096;
byte[] bytes = new byte[buffer_size];
int totalSize = 0;
int downloadCount = 0;
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
totalSize += count;
int progress = (int) (totalSize*100/updateTotalSize);
if((downloadCount == 0) || progress - 10 >= downloadCount) {
downloadCount += 10;
progressNotification(progress);
Log.e(TAG, "下载进度:" + progress + "%");
}
}
is.close();
os.close();
}
private void startNotification() {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(android.R.drawable.stat_sys_download, "下载爱折客", System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.download_notification);
contentView.setProgressBar(R.id.progress_bar, 100, 0, false);
contentView.setTextViewText(R.id.progress_text, "0%");
contentView.setTextViewText(R.id.title, "开始下载应用程序");
contentView.setTextViewText(R.id.description, "爱折客更新");
contentView.setImageViewResource(R.id.appIcon, android.R.drawable.stat_sys_download);
//这符合一般的Notification的运作规范
notification.flags|=Notification.FLAG_ONGOING_EVENT;
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
notification.contentView = contentView;
notification.contentIntent = contentIntent;
notificationManager.notify(resourceId, notification);
}
private void progressNotification(int progress) {
String percent = progress + "%";
if(progress == 0) {
notification.contentView.setTextViewText(R.id.title, "正在下载应用程序");
}
if(progress == 100) {
notification.tickerText = "爱折客下载完成,请安装";
notification.contentView.setTextViewText(R.id.title, "下载完成,请安装");
notification.contentView.setTextColor(R.id.title, Color.GRAY);
Uri uri = Uri.fromFile(FILE);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
PendingIntent contentIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, 0);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.contentIntent = contentIntent;
if(FILE.exists()) {
Log.i(TAG, FILE.getAbsolutePath());
//FILE.delete();
}
}
notification.contentView.setProgressBar(R.id.progress_bar, 100, progress, false);
//notification.tickerText = "下载进度为" + percent;
notification.contentView.setTextViewText(R.id.progress_text, percent);
notificationManager.notify(resourceId, notification);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@android:drawable/status_bar_item_app_background"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<LinearLayout android:id="@+id/app"
android:layout_width="40dp"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="8dp"
android:focusable="true"
android:clickable="true"
>
<ImageView
android:id="@+id/appIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
<TextView android:id="@+id/progress_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff000000"
android:singleLine="true"
android:textSize="14sp"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
<RelativeLayout android:id="@+id/app"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusable="true"
android:clickable="true"
>
<LinearLayout android:id="@+id/notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:focusable="true"
android:clickable="true"
android:layout_alignParentTop="true"
android:paddingTop="10dp"
>
<TextView android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="18sp"
android:textColor="#ff000000"
android:paddingLeft="2dp"
/>
<TextView android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff000000"
android:singleLine="true"
android:textSize="14sp"
android:paddingLeft="5dp"
android:textStyle="italic"
/>
</LinearLayout>
<ProgressBar android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="8dp"
android:paddingRight="25dp"
/>
</RelativeLayout>
</LinearLayout>
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
posted on 2011-07-01 22:00
汪杰 阅读(260)
评论(0) 编辑 收藏 引用 所属分类:
Java