/** * download file * @param url * @param path * @throws IOException */ private void down_file(String url, File apkfile) throws IOException { // 获取文件名 URL myURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) myURL.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("Referer", myURL.toString()); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Connection", "Keep-Alive"); // 设置范围,格式为Range:bytes x-y; conn.connect(); this.fileSize = conn.getContentLength();// 根据响应获取文件大小 // conn.setRequestProperty("RANGE", "bytes=0-"+fileSize); InputStream is = conn.getInputStream(); if (this.fileSize <= 0){ Log_E("无法获取文件大小");return; } if (is == null){ Log_E("输入流为空"); return; } FileOutputStream fos = new FileOutputStream(apkfile); BufferedInputStream bis = null; BufferedOutputStream bos = null; bis = new BufferedInputStream(is); bos = new BufferedOutputStream(fos); // 把数据存入路径+文件名 byte buf[] = new byte[16348]; downLoadFileSize = 0; sendMsg(0); do { // 循环读取 int numread = bis.read(buf); // if(!JFQService.downflag)return; if (numread == -1) { break; } bos.write(buf, 0, numread); downLoadFileSize += numread; sendMsg(1);// 更新进度条 } while (true&&JFQService.downflag); sendMsg(2);// 通知下载完成 is.close(); bis.close(); bos.close(); fos.close(); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯 try { if (!Thread.currentThread().isInterrupted()) { // msg.what is flag.if flag is 0 means start download,flag // is 1 means update process,flag is 2 is means switch (msg.what) { case 0: Log_D("start download app file"); case 1: progress = (int) ((downLoadFileSize * 100l) / (fileSize)); if (progress < 0) { Log_D("this occur a misktake"); } break; case 2: downloadAPPFileComplete(); break; case -1: downloadOccurError(msg.getData().getString("error")); break; } } super.handleMessage(msg); } catch (Exception e) { Log_E("handler error"); } } };
/** * The following method for the call */ public int getProgress(){ return progress; } /** * get info about down file size for MB,for example 2.10MB */ public String getFileSizeByMB() { double size = (fileSize / 1024.0) / 1024.0; DecimalFormat df = new DecimalFormat("#####0.00 "); String sizestr = df.format(size); return sizestr; }
/** * The download is complete */ public void downloadAPPFileComplete(){ progress=100; //update the apk name if(updateApkName()){ Log_D("修改文件"+apkname+".tmp成功"); }else{ Log_E("修改文件"+apkname+".tmp失败"); } }
new出来这个对象,调用startdown方法就可以下载了,public class DownLoadOneApp {
Context context;
private String packageName;
private String apkname;
private String downloadurl;
private String outfilepath;
//the progress is displayed.
public int progress=0;
//the app file
private File apkfile;
//the app file size
private long fileSize;
//means download size
private long downLoadFileSize; public DownLoadOneApp(Context context,String packageName,String outfilepath,String apkname,String downloadurl) {
this.context = context;
this.packageName=packageName;
this.downloadurl=downloadurl;
this.outfilepath=outfilepath;
this.apkname=apkname;
}
/**
* @param outpath
* @param url
*/
public boolean startdownfile() {
final String downurl=downloadurl;
final String outpath=outfilepath+apkname+".tmp";
apkfile=new File(outpath);
File pathfile=new File(outfilepath);
if(!pathfile.exists()){
Log_D("the path "+outfilepath+" is not exists,so we mkdirs it");
if(pathfile.mkdirs()){
Log_D("mkdirs "+outfilepath+" success!");
}else{
Log_D("mkdirs "+outfilepath+" occur error!");
return false;
}
}
new Thread() {
@Override
public void run() {
try {
// 下载文件,参数:第一个URL,第二个存放路径
down_file(downurl,apkfile);
} catch (ClientProtocolException e) {
downloadOccurError("ClientProtocolException");
Log_E("ClientProtocolException");
} catch (IOException e) {
downloadOccurError("IOException");
Log_E("IOException");
}
}
}.start();
return true;
}
/**
* download file
* @param url
* @param path
* @throws IOException
*/
private void down_file(String url, File apkfile) throws IOException {
// 获取文件名
URL myURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("Referer", myURL.toString());
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置范围,格式为Range:bytes x-y;
conn.connect();
this.fileSize = conn.getContentLength();// 根据响应获取文件大小
// conn.setRequestProperty("RANGE", "bytes=0-"+fileSize);
InputStream is = conn.getInputStream();
if (this.fileSize <= 0){
Log_E("无法获取文件大小");return;
}
if (is == null){
Log_E("输入流为空");
return;
}
FileOutputStream fos = new FileOutputStream(apkfile); BufferedInputStream bis = null;
BufferedOutputStream bos = null;
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(fos); // 把数据存入路径+文件名
byte buf[] = new byte[16348];
downLoadFileSize = 0;
sendMsg(0);
do {
// 循环读取
int numread = bis.read(buf);
// if(!JFQService.downflag)return;
if (numread == -1) {
break;
}
bos.write(buf, 0, numread);
downLoadFileSize += numread;
sendMsg(1);// 更新进度条
} while (true&&JFQService.downflag);
sendMsg(2);// 通知下载完成
is.close();
bis.close();
bos.close();
fos.close();
} private Handler handler = new Handler() { @Override
public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
try {
if (!Thread.currentThread().isInterrupted()) { // msg.what is flag.if flag is 0 means start download,flag
// is 1 means update process,flag is 2 is means
switch (msg.what) {
case 0:
Log_D("start download app file");
case 1:
progress = (int) ((downLoadFileSize * 100l) / (fileSize));
if (progress < 0) {
Log_D("this occur a misktake");
}
break;
case 2:
downloadAPPFileComplete();
break;
case -1:
downloadOccurError(msg.getData().getString("error"));
break;
}
}
super.handleMessage(msg); } catch (Exception e) {
Log_E("handler error");
}
}
};
/**
* The following method for the call
*/
public int getProgress(){
return progress;
} /**
* get info about down file size for MB,for example 2.10MB
*/
public String getFileSizeByMB() {
double size = (fileSize / 1024.0) / 1024.0;
DecimalFormat df = new DecimalFormat("#####0.00 ");
String sizestr = df.format(size);
return sizestr;
}
/**
* The download is complete
*/
public void downloadAPPFileComplete(){
progress=100;
//update the apk name
if(updateApkName()){
Log_D("修改文件"+apkname+".tmp成功");
}else{
Log_E("修改文件"+apkname+".tmp失败");
}
}
private boolean updateApkName(){
String apkfilepath = apkfile.getAbsolutePath();
if(apkfilepath.endsWith(".tmp")){
apkfilepath=apkfilepath.substring(0, apkfilepath.length()-4)+".apk";
}
File file=new File(apkfilepath);
if(apkfile.exists()){
return apkfile.renameTo(file);
}
return false;
}
/**
* The download process is abnormal
*/
public void downloadOccurError(String error){
progress=-1;
}
private void sendMsg(int flag) {
Message msg = new Message();
msg.what = flag;
handler.sendMessage(msg);
}
public String getOutfilepath() {
return outfilepath;
}
public void setOutfilepath(String outfilepath) {
this.outfilepath = outfilepath;
} public String getApkname() {
return apkname;
}
public void setApkname(String apkname) {
this.apkname = apkname;
} private void Log_D(String log) {
LogHelper.Log_D(this.getClass().getSimpleName(), log);
}
private void Log_E(String log) {
LogHelper.Log_E(this.getClass().getSimpleName(), log);
}
}
boolean reuslt = downoneapp.startdownfile();//开始下载
&&JFQService.downflag);private void Log_D(String log) {
LogHelper.Log_D(this.getClass().getSimpleName(), log);
}
private void Log_E(String log) {
LogHelper.Log_E(this.getClass().getSimpleName(), log);
}
/**
*
* @param apkPath apk安装路径
* @param url apk下载地址
* @param handler 下载成功后会send 一个带有路径的apk名称
*/
public void downloadApk(final String apkPath,final String url) {
new Thread(){
@Override
public void run() {
int notifyId = Math.abs((int) System.currentTimeMillis());
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
boolean downloadSuccess=false;
String fileName=apkPath+"/";
String apkName="";
File file=new File(apkPath);
if(!file.exists()){
file.mkdirs();
}
URL urls;
HttpURLConnection conn=null;
FileOutputStream output=null;
InputStream istream = null;
try {
urls = new URL(url);
conn = (HttpURLConnection) urls.openConnection();
conn.setConnectTimeout(30*1000);
conn.connect();
istream=conn.getInputStream();
int totalSize=conn.getContentLength();
int currentSize=0;
apkName=url.substring(url.lastIndexOf("/")+1);
fileName+= apkName;
output=new FileOutputStream(new File(fileName));
byte []bi=new byte[1024];
int b=0;
while((b=istream.read(bi))!=-1){
currentSize+=b;
output.write(bi,0,b);
output.flush();
} } catch (MalformedURLException e) {
} catch (IOException e) {
}catch(Exception e){} finally{
}
}
}.start();
}
apk的下载地址 和apk的安装路径 都放在那里 路径咋写 给个举例吧 真不会呀
.getPath()+ "/apps";String url="http://dl.wandoujia.com/files/phoenix/latest/wandoujia-c5_sf.apk"apkPath一般是你sd卡的路径
url就是下载的apk的路径
@Override
public void onClick(DialogInterface dialog, int which) {
//which.s
Intent intent = new Intent();
intent.setClass(main.this, SettingsActivity.class);
startActivity(intent); }
});public class SettingsActivity extends Activity implements View.OnClickListener{
private Button playBtn,settingBtn,aboutBtn,exitBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
setUpView();
setUpListener();
}
private void setUpView() {
playBtn = (Button)findViewById(R.id.playBtn);
settingBtn = (Button)findViewById(R.id.AdLinearLayout);
aboutBtn = (Button)findViewById(R.id.aboutBtn);
exitBtn = (Button)findViewById(R.id.exitBtn);
} private void setUpListener() {
playBtn.setOnClickListener(this);
settingBtn.setOnClickListener(this);
aboutBtn.setOnClickListener(this);
exitBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.playBtn: {
Intent intent = new Intent();
//intent.setClass(SettingsActivity.this, MainActivity.class);
startActivity(intent);
}
break;
case R.id.exitBtn: {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setMessage("你确定退出程序吗?");
builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
SettingsActivity.this.finish();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
break;
}
} @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:{
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setMessage("你确定退出程序吗?");
builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
SettingsActivity.this.finish();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}