Intent intent = new Intent(SettingActivity.this, DownloadService.class);
// intent.putExtra("url", "https://www.leorobot.com/leoservice/apk/byjc/SpeechMainActivityUnisound.apk");
intent.putExtra("url", Constant.BASE_URL + "/" + mVersionEntity.getData().getUrl());
startService(intent);
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import org.apache.http.HttpStatus;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadService extends Service {
public static final String DOWNLOAD_PATH =
Environment.getExternalStorageDirectory().getAbsolutePath()+
"/Download/";
public static final String TAG = "download";
private String url;//下载链接
private int length;//文件长度
private String fileName=null;//文件名
private Notification notification;
private RemoteViews contentView;
private NotificationManager notificationManager;
private static final int MSG_INIT = 0;
private static final int URL_ERROR = 1;
private static final int NET_ERROR = 2;
private static final int DOWNLOAD_SUCCESS = 3;
private ProgressDialog progressDialog;
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_INIT:
length = (Integer) msg.obj;
// createNotification();
updateAPPDialog();
break;
case DOWNLOAD_SUCCESS:
//下载完成
// notifyNotification(100, 100);
// progressDialog.setProgress(100);
progressDialog.dismiss();
installApk(DownloadService.this,new File(DOWNLOAD_PATH,fileName));
Toast.makeText(DownloadService.this, "下载完成", Toast.LENGTH_SHORT).show();
break;
case URL_ERROR:
Toast.makeText(DownloadService.this, "下载地址错误", Toast.LENGTH_SHORT).show();
break;
case NET_ERROR:
Toast.makeText(DownloadService.this, "连接失败,请检查网络设置", Toast.LENGTH_SHORT).show();
}
};
};
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
url = intent.getStringExtra("url");
Log.e("wy","获取到的apk下载地址: "+ url);
if(url != null && !TextUtils.isEmpty(url)){
new InitThread(url).start();
}else{
mHandler.sendEmptyMessage(URL_ERROR);
}
}
return super.onStartCommand(intent, flags, startId);
}
/**
* 初始化子线程
* @author dong
*
*/
class InitThread extends Thread{
String url = "";
public InitThread(String url) {
this.url = url;
}
public void run() {
HttpURLConnection conn= null;
RandomAccessFile raf = null;
try {
//连接网络文件
URL url = new URL(this.url);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
int length = -1;
if(conn.getResponseCode() == HttpStatus.SC_OK){
//获得文件长度
length = conn.getContentLength();
}
if(length <= 0){
return;
}
File dir = new File(DOWNLOAD_PATH);
if(!dir.exists()){
dir.mkdir();
}
fileName = this.url.substring(this.url.lastIndexOf("/")+1, this.url.length());
if(fileName==null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")){
fileName = getPackageName()+".apk";
}
File file = new File(dir, fileName);
raf = new RandomAccessFile(file, "rwd");
//设置文件长度
raf.setLength(length);
mHandler.obtainMessage(MSG_INIT,length).sendToTarget();
} catch (Exception e) {
mHandler.sendEmptyMessage(URL_ERROR);
e.printStackTrace();
} finally{
try {
conn.disconnect();
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 下载线程
* @author dong
*
*/
class DownloadThread extends Thread{
String url;
int length;
public DownloadThread(String url, int length) {
this.url = url;
this.length = length;
}
@Override
public void run() {
HttpURLConnection conn = null;
RandomAccessFile raf = null;
InputStream input = null;
try {
URL url = new URL(this.url);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
//设置下载位置
int start =0;
conn.setRequestProperty("Range", "bytes="+0+"-"+length);
//设置文件写入位置
File file = new File(DownloadService.DOWNLOAD_PATH,fileName);
raf = new RandomAccessFile(file, "rwd");
raf.seek(start);
long mFinished = 0;
//开始下载
if(conn.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT){
//LogUtil.i("下载开始了。。。");
Log.e("wy","下载开始了。。。");
//读取数据
input = conn.getInputStream();
byte[] buffer = new byte[1024*4];
int len = -1;
long speed = 0;
long time = System.currentTimeMillis();
while((len = input.read(buffer)) != -1){
//写入文件
raf.write(buffer,0,len);
//把下载进度发送广播给Activity
mFinished += len;
speed += len;
if(System.currentTimeMillis() - time > 1000){
time = System.currentTimeMillis();
// notifyNotification(mFinished,length);
progressDialog.setProgress((int)(mFinished*100/length));
Log.i(TAG, "mFinished=="+mFinished);
Log.i(TAG, "length=="+length);
Log.i(TAG, "speed=="+speed);
speed = 0;
}
}
mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
Log.i(TAG, "下载完成了。。。");
}else{
Log.i(TAG, "下载出错了。。。");
mHandler.sendEmptyMessage(NET_ERROR);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(conn != null){
conn.disconnect();
}
if(raf != null){
raf.close();
}
if(input != null ){
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//更新弹窗
private void updateAPPDialog() {
progressDialog = new ProgressDialog(SettingActivity.mContext);
progressDialog.setCancelable(false);
progressDialog.setMessage("更新中,请勿中断");
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
final AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.mContext)
// .setIcon(R.drawable.ic_launcher)
.setTitle("版本更新")
.setMessage( "发现新版本")
.setCancelable(false)
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
progressDialog.show();
new DownloadThread(url,length).start();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
progressDialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
/**
* 安装apk
*
* @param context 上下文
* @param file APK文件
*/
public static void installApk(Context context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
}