1.AlertDialog
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("升级提醒");
builder.setMessage(UpdateInfo.getDescripation());
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
pd = new ProgressDialog(SplashActivity.this);
pd.setTitle("升级操作");
pd.setMessage("正在下载");
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
final String apkurl = UpdateInfo.getApkurl();
final File file = new File(Environment.getExternalStorageDirectory(),DownLoadUtil.getFileName(apkurl));
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
new Thread() {
public void run(){
File saveFile = DownLoadUtil.download(apkurl, file.getAbsolutePath(), pd);
Message msg = Message.obtain();
if(saveFile!=null){
msg.what = DOWNLOAD_SUCCESS;
msg.obj = saveFile;
}
else{
msg.what = DOWNLOAD_FAILED;
}
handler.sendMessage(msg);
pd.dismiss();
}
};
}else{
Toast.makeText(SplashActivity.this, "下載失敗", Toast.LENGTH_LONG).show();
}
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
loadMainUI();
}
});
<strong>builder.create().show();</strong>
downloadutils
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.res.Resources.Theme;
public class DownLoadUtil {
public static File download(String serverPath, String savedPath, ProgressDialog pd) {
try {
URL url = new URL(serverPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
pd.setMax(conn.getContentLength());
InputStream is = conn.getInputStream();
File file = new File(savedPath);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
int total = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total +=len;
pd.setProgress(total);
Thread.sleep(20);
}
fos.flush();
fos.close();
is.close();
return file;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getFileName(String serverPath) {
return serverPath.substring(serverPath.lastIndexOf("/") + 1);
}
}