Android应用程序更新并下载实例
短信预约 -IT技能 免费直播动态提醒
整理文档,搜刮出一个Android应用程序更新并下载实例的代码,稍微整理精简一下做下分享。
创建一个新类,名为UpdateManager,代码如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.af.mobile.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class UpdateManager
{private URL url=null;
private static final int DOWNLOAD = 1;
private static final int DOWNLOAD_FINISH = 2;
//HashMap<String, String> mHashMap;
private String mSavePath;
private int progress;
private boolean cancelUpdate = false;
private Context mContext;
private ProgressBar mProgress;
private Dialog mDownloadDialog;
private Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
// 正在下载
case DOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
break;
case DOWNLOAD_FINISH:
// 安装文件
installApk();
break;
default:
break;
}
};
};
public UpdateManager(Context context)
{
this.mContext = context;
}
public void checkUpdate()
{
if (isUpdate())
{
showNoticeDialog();
} else
{
}
}
private boolean isUpdate()
{
// 获取当前软件版本
Double versionCode = getVersionCode(mContext);
Double serviceCode = 1.2;
// 版本判断
if (serviceCode > versionCode)
{
return true;
}
return false;
}
// 获取软件版本号
private Double getVersionCode(Context context)
{
Double versionCode = 0.0;
try
{
// 获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = (double) context.getPackageManager().getPackageInfo("com.af.mobile", 0).versionCode;
} catch (NameNotFoundException e)
{
e.printStackTrace();
}
return versionCode;
}
//显示软件更新对话框
private void showNoticeDialog()
{
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("软件更新");
String string=download("http://192.168.0.102:9313/daojuserver/uploads/version.xml");//xml的下载地址
builder.setMessage(string);
builder.setPositiveButton("更新", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
// 显示下载对话框
showDownloadDialog();
}
});
// 稍后更新
builder.setNegativeButton("稍后更新", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
// 显示软件下载对话框
private void showDownloadDialog()
{
// 构造软件下载对话框
AlertDialog.Builder builder = new Builder(mContext);
builder.setTitle("djfkjd");//提示信息内容
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消更新
builder.setNegativeButton("取消更新", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 现在文件
downloadApk();
}
private void downloadApk()
{
// 启动新线程下载软件
new downloadApkThread().start();
}
private class downloadApkThread extends Thread
{
@Override
public void run()
{
try
{
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
URL url = new URL("http://192.168.0.102:9313/daojuserver/uploads/SpMobile.apk");//apk下载地址地址
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
if (!file.exists())
{
file.mkdir();
}
File apkFile = new File(mSavePath, "dhfudh");
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do
{
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0)
{
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
fos.write(buf, 0, numread);
} while (!cancelUpdate);
fos.close();
is.close();
}
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
// 取消下载对话框显示
mDownloadDialog.dismiss();
}
};
private void installApk()
{
File apkfile = new File(mSavePath, "dhfudh");
if (!apkfile.exists())
{
return;
}
// 通过Intent安装APK文件
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(i);
}
public String download(String urlString)
{
StringBuffer sbBuffer=new StringBuffer();
String line=null;
BufferedReader buffer=null;
try {
url=new URL(urlString);
HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while((line=buffer.readLine())!=null)
{
sbBuffer.append(line);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally
{
try {
buffer.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
return sbBuffer.toString();
}
}
在Android应用程序Main界面
if(isOpenNetwork())//判断是否有网络
{
UpdateManager manager = new UpdateManager(Main.this);
// 检查软件更新
manager.checkUpdate();
}
判断移动端是否有网络
private boolean isOpenNetwork() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo != null) {
// 2.获取当前网络连接的类型信息
int networkType = networkInfo.getType();
if (ConnectivityManager.TYPE_WIFI == networkType) {
// 当前为wifi网络
} else if (ConnectivityManager.TYPE_MOBILE == networkType) {
// 当前为mobile网络
}
return connManager.getActiveNetworkInfo().isAvailable();
}
return false;
}
您可能感兴趣的文章:android实现通知栏下载更新app示例Android实现检查并下载APK更新、安装APK及获取网络信息的方法Android编程实现应用自动更新、下载、安装的方法Android程序版本更新之通知栏更新下载安装android中DownloadManager实现版本更新,监听下载进度实例Android中使用AsyncTask实现文件下载以及进度更新提示Android 检查更新、下载、安装功能的实现Android Studio下载更新Android SDK网络异常或无法下载Android SDK Manager更新、下载速度慢问题解决办法Android中使用AsyncTask实现下载文件动态更新进度条功能Android编程实现下载时主界面与详细界面一致更新的方法
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341