Android 版本自动更新

之前做过版本更新的功能 弹出一个对话框进行下载,感觉不太美观用户体验不好  后来看别人都直接在通知栏进行下载 今天刚好做这个功能 就想练练手

public class DownloadService extends Service {
protected static final int DOWNLOAD = 0;
protected static final String TAG = null;
protected static final int INSTALL_NEW_APK = 1;
protected static final int ERROR_CONNECTION = 2;
private int isUpDataNmu = 0;
private NotificationManager notificationManager;
private Notification notification;
/*** 进度条的总长度 ****/
private int length;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case ERROR_CONNECTION:// 联网失败
Toast.makeText(getApplicationContext(), "更新版本失败!!",
Toast.LENGTH_SHORT).show();
stopSelf();
break;
case INSTALL_NEW_APK:// 安装最新的apk
Log.i(TAG, "wzgfafdj");
installNewApk();
Log.i("xzwc", "下载完成2222222");
//下载完成后关掉服务
stopSelf();
Log.i("xzwc", "下载完成");
break;
default:
break;
}
};
};


@SuppressWarnings("deprecation")
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.hspd, "开始下载",
System.currentTimeMillis());
RemoteViews view = new RemoteViews(getPackageName(),
R.layout.activity_noti);
notification.contentView = view;
PendingIntent contentIntent = PendingIntent.getActivity(this,
R.string.app_name, new Intent(),
PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentIntent = contentIntent;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
downloadNewApk();
return super.onStartCommand(intent, flags, startId);


}


@Override
public IBinder onBind(Intent arg0) {
return null;
}


@Override
public void onDestroy() {
super.onDestroy();
notificationManager.cancelAll();
stopSelf();
}


// 下载服务器上最新版本
public void downloadNewApk() {
if (NetUtil.checkNet(DownloadService.this)) {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
HttpGet request = new HttpGet("http://"
+ IP.getIPclass().getNetIp()
+ DownLoadUrl.getUrl());
Log.i("ssss", "http://" + IP.getIPclass().getNetIp()
+ DownLoadUrl.getUrl());
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
length = (int) response.getEntity()
.getContentLength();
InputStream inputStream = response.getEntity()
.getContent();
// 把流变为文件 存储在sdcard
String name = getFileName("http://"
+ IP.getIPclass().getNetIp()
+ DownLoadUrl.getUrl());
File file = new File(
Environment.getExternalStorageDirectory(),
name);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
int count = 0;
while ((len = inputStream.read(buffer)) != -1) {
count += len;
Log.i(TAG, "count:" + count);
// 计算进度条位置
int progress = (int) (((float) count / (float) length) * 100);
Log.i("WZGS", "显示的位置::" + progress);
Log.i("ssdd", "总长度===" + length);
fos.write(buffer, 0, len);
if (progress - isUpDataNmu >= 5) {
isUpDataNmu = progress;
notification.contentView.setTextViewText(
R.id.noti_tv, progress + "%");
// 设置进度条位置
notification.contentView.setProgressBar(
R.id.noti_pd, 100, progress, false);
// 发送消息
notificationManager.notify(0, notification);
Log.i(TAG, "当前进度123  :" + progress);
SystemClock.sleep(100);
}
}
fos.close();
inputStream.close();
// apk下载完成
Log.i(TAG, "apk下载完成");
Message msg = Message.obtain();
msg.what = INSTALL_NEW_APK;
mHandler.sendMessage(msg);
Log.i(TAG, "下载更新");


} else {
Message msg = Message.obtain();
msg.what = ERROR_CONNECTION;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what = ERROR_CONNECTION;
mHandler.sendMessage(msg);
}
};
}.start();
} else {
Toast.makeText(DownloadService.this, "当前没有网络,请检查设备!!!",
Toast.LENGTH_SHORT).show();
}
}


/**
* 截取url 最后的文件名

* @param url
* @return
*/
public String getFileName(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}


/**
* 安装最新的apk 思考: 在系统里面已经存在一个应用安装器(Activity) 隐士意图激活Activity //
*/
public void installNewApk() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String name = getFileName("http://" + IP.getIPclass().getNetIp()
+ DownLoadUrl.getUrl());
File file = new File(Environment.getExternalStorageDirectory(), name);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);


}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值