*/
public class SplashActivity extends AppCompatActivity {
//弹出一个更新的提示框
private static final int MSG_SHOW_UPDATE_DIALOG =100 ;
private static final int REQ_CODE_INSTALL =200 ;
private String urlServer = "http://192.168.10.114:8080/version.json";
private TextView mTv_version_name;
private int mLocalVersionCode;
private int mServerVersionCode;
private Handler mHandler;
private String mUpdateDesc;
// 最新版本的下载链接
private String downloadURL;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_SHOW_UPDATE_DIALOG:
alertUpdateDialog();
break;
}
}
//更新提示框
private void alertUpdateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
builder.setTitle(getString(R.string.update_title));
builder.setMessage(mUpdateDesc);
//确定更新
builder.setPositiveButton(getString(R.string.update_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 下载的进度条
ProgressDialog pd =
new ProgressDialog(SplashActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new DownloadRunnable(pd)).start();
}
});
//取消更新
builder.setNegativeButton(getString(R.string.uptate_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoMainActivity();
}
});
AlertDialog dialog = builder.show();
//设置按钮是否可以按返回键取消,false则不可以取消
dialog.setCancelable(false);
//设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getVersionName();
//获取本地版本号
mLocalVersionCode = PkgUtils.getVersionCode(this);
new Thread(new CheckUpdateRunnable()).start();
}
private void getVersionName() {
mTv_version_name = (TextView) findViewById(R.id.act_splash_tv_version_name);
mTv_version_name.setText(getResources().getString(R.string.version_name) + PkgUtils.getVersionName(this));
}
// 跳转到主界面
private void gotoMainActivity() {
// 延时执行
// 第二个参数: 延时时间
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent =
new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 1500);
}
// 下载的Runnable
private class DownloadRunnable implements Runnable{
private ProgressDialog pd;
public DownloadRunnable(ProgressDialog pd) {
this.pd = pd;
}
@Override
public void run() {
FileOutputStream fos = null;
InputStream is = null;
URL url = null;
try {
url = new URL(downloadURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 连接超时
conn.setConnectTimeout(5 * 1000);
// 读取数据超时
conn.setReadTimeout(5 * 1000);
// 连接
conn.connect();
if (conn.getResponseCode()==200){
//获取apk的大小
int max = conn.getContentLength();
// 设置进度条的最大值
pd.setMax(max);
//文件路径
File file = new File(Environment.getExternalStorageDirectory(),"new.apk");
//文件写出流
fos= new FileOutputStream(file);
is= conn.getInputStream();
int len;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//安装
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(
Uri.parse("file:" + file.getAbsolutePath()),
"application/vnd.android.package-archive");
// requestCode :请求码,代表是谁发起的请求
startActivityForResult(intent, REQ_CODE_INSTALL);
}else {
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关流
CloseIOUtils.closeStream(fos);
CloseIOUtils.closeStream(is);
}
}
}
// 检查更新的Runnable
private class CheckUpdateRunnable implements Runnable {
@Override
public void run() {
InputStream is = null;
BufferedReader br = null;
try {
URL url = new URL(urlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//连接超时
conn.setConnectTimeout(5 * 1000);
//读取数据超时
conn.setReadTimeout(5 * 1000);
//连接
conn.connect();
//获取服务器返回码
int code = conn.getResponseCode();
if (code == 200) {//连接成功
//获得一个输入流
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String result = "";
String temp;
while ((temp = br.readLine()) != null) {
//拼接读取的字符
result += temp;
}
//读取完后就可以用jsonobject来接收了
//读取版本号
JSONObject jsonObject = new JSONObject(result);
mServerVersionCode = jsonObject.getInt("versioncode");
//获取message,此message用于弹窗提示用语
mUpdateDesc = jsonObject.getString("desc");
//下载apk地址
downloadURL = jsonObject.getString("url");
LogUtils.d("" + mServerVersionCode);
if (mServerVersionCode > mLocalVersionCode) {
// 弹出更新提示框
handler.sendEmptyMessage(MSG_SHOW_UPDATE_DIALOG);
} else {// 不需要更新
gotoMainActivity();
}
} else {//连接服务器失败
LogUtils.e("连接服务器失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// requestCode: 请求码
// resultCode: 结果码.Activity.RESULT_OK: 处理成功了. Activity.RESULT_CANCELED:处理失败了
// data: 返回值.并不一定要有数据
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch (requestCode) {
case REQ_CODE_INSTALL:
if (resultCode == Activity.RESULT_CANCELED) {
gotoMainActivity();
}
break;
}
}
}
软件更新流程图
*/
public class SplashActivity extends AppCompatActivity {
//弹出一个更新的提示框
private static final int MSG_SHOW_UPDATE_DIALOG =100 ;
private static final int REQ_CODE_INSTALL =200 ;
private String urlServer = "http://192.168.10.114:8080/version.json";
private TextView mTv_version_name;
private int mLocalVersionCode;
private int mServerVersionCode;
private Handler mHandler;
private String mUpdateDesc;
// 最新版本的下载链接
private String downloadURL;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_SHOW_UPDATE_DIALOG:
alertUpdateDialog();
break;
}
}
//更新提示框
private void alertUpdateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
builder.setTitle(getString(R.string.update_title));
builder.setMessage(mUpdateDesc);
//确定更新
builder.setPositiveButton(getString(R.string.update_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 下载的进度条
ProgressDialog pd =
new ProgressDialog(SplashActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new DownloadRunnable(pd)).start();
}
});
//取消更新
builder.setNegativeButton(getString(R.string.uptate_cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
gotoMainActivity();
}
});
AlertDialog dialog = builder.show();
//设置按钮是否可以按返回键取消,false则不可以取消
dialog.setCancelable(false);
//设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getVersionName();
//获取本地版本号
mLocalVersionCode = PkgUtils.getVersionCode(this);
new Thread(new CheckUpdateRunnable()).start();
}
private void getVersionName() {
mTv_version_name = (TextView) findViewById(R.id.act_splash_tv_version_name);
mTv_version_name.setText(getResources().getString(R.string.version_name) + PkgUtils.getVersionName(this));
}
// 跳转到主界面
private void gotoMainActivity() {
// 延时执行
// 第二个参数: 延时时间
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent =
new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 1500);
}
// 下载的Runnable
private class DownloadRunnable implements Runnable{
private ProgressDialog pd;
public DownloadRunnable(ProgressDialog pd) {
this.pd = pd;
}
@Override
public void run() {
FileOutputStream fos = null;
InputStream is = null;
URL url = null;
try {
url = new URL(downloadURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 连接超时
conn.setConnectTimeout(5 * 1000);
// 读取数据超时
conn.setReadTimeout(5 * 1000);
// 连接
conn.connect();
if (conn.getResponseCode()==200){
//获取apk的大小
int max = conn.getContentLength();
// 设置进度条的最大值
pd.setMax(max);
//文件路径
File file = new File(Environment.getExternalStorageDirectory(),"new.apk");
//文件写出流
fos= new FileOutputStream(file);
is= conn.getInputStream();
int len;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//安装
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(
Uri.parse("file:" + file.getAbsolutePath()),
"application/vnd.android.package-archive");
// requestCode :请求码,代表是谁发起的请求
startActivityForResult(intent, REQ_CODE_INSTALL);
}else {
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关流
CloseIOUtils.closeStream(fos);
CloseIOUtils.closeStream(is);
}
}
}
// 检查更新的Runnable
private class CheckUpdateRunnable implements Runnable {
@Override
public void run() {
InputStream is = null;
BufferedReader br = null;
try {
URL url = new URL(urlServer);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//连接超时
conn.setConnectTimeout(5 * 1000);
//读取数据超时
conn.setReadTimeout(5 * 1000);
//连接
conn.connect();
//获取服务器返回码
int code = conn.getResponseCode();
if (code == 200) {//连接成功
//获得一个输入流
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
String result = "";
String temp;
while ((temp = br.readLine()) != null) {
//拼接读取的字符
result += temp;
}
//读取完后就可以用jsonobject来接收了
//读取版本号
JSONObject jsonObject = new JSONObject(result);
mServerVersionCode = jsonObject.getInt("versioncode");
//获取message,此message用于弹窗提示用语
mUpdateDesc = jsonObject.getString("desc");
//下载apk地址
downloadURL = jsonObject.getString("url");
LogUtils.d("" + mServerVersionCode);
if (mServerVersionCode > mLocalVersionCode) {
// 弹出更新提示框
handler.sendEmptyMessage(MSG_SHOW_UPDATE_DIALOG);
} else {// 不需要更新
gotoMainActivity();
}
} else {//连接服务器失败
LogUtils.e("连接服务器失败");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// requestCode: 请求码
// resultCode: 结果码.Activity.RESULT_OK: 处理成功了. Activity.RESULT_CANCELED:处理失败了
// data: 返回值.并不一定要有数据
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
switch (requestCode) {
case REQ_CODE_INSTALL:
if (resultCode == Activity.RESULT_CANCELED) {
gotoMainActivity();
}
break;
}
}
}
上面已经获取了本地的versionCode现在就要从服务器那获取versionCode,要从服务器那获取versionCode就要知道服务器地址(urlSever)和在检查更新的Runnable对象,也就是一个任务,用于在SplashActivity加载时执行,从服务器获取versionCode.
假如version.json是这样的
{"versioncode":"2","desc":"新版本,新功能","url":"http://192.168.10.114:8080/safeguard/360.apk"}
定义服务器地址(urlSever)
private String urlServer = "http://192.168.10.114:8080/xxx/version.json";
检查更新的Runnable对象,网络请求成功怎么做,失败怎么做?
成功:获取版本比对,比对后需不需要更新,需要该怎么做?不需要又怎么做?
需要更新:弹出更新提示框.确定和取消.点击了确定后,代码怎么处理,取消呢?
不需要更新:是不是要跳到主界面.
别忘了关流
比较本地和服务器versionCode不需要更新,跳转到主界面
比较本地和服务器versionCode需要更新,弹出提示框部分代码如下
注意这段代码要放在主线程,因为是UI
点击更新按钮下载apk并且显示下载进度
用于下载的Runnable对象
下载完成后条用系统的安装
用户取消安装的监听和处理