实现功能:
1 启动界面定时2秒后跳转。
2 获取服务器版本信息,检查版本,判断是否需要更新应用。
3 更新版本。弹出更新对话框,下载apk
4 签名要一致,一个应用的更新安装,需要包名一致,签名一致,才能覆盖安装,达到更新应用目的。
SplashActivity.java
package com.itheima.mobilesafe;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;
import com.itheima.streamtool.StreamTool;
public class SplashActivity extends Activity {
protected static final String TAG = "SplashActivity";
protected static final int ENTER_HOME = 0;
protected static final int UPDATE = 1;
protected static final int JSON_ERROR = 2;
protected static final int NETWORK_ERROR = 3;
protected static final int URL_ERROR = 4;
private TextView tv_splash_version;
private TextView tv_splash_update;
private String description;
private String apkurl;
/**
* 处理检查版本
*/
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ENTER_HOME:
enterHome();
break;
case UPDATE:
Log.i(TAG, "显示更新对话框");
showUpdateDialog();
break;
case JSON_ERROR:
Toast.makeText(getApplicationContext(), "json解析出错",
Toast.LENGTH_SHORT).show();
enterHome();
break;
case NETWORK_ERROR:
Toast.makeText(getApplicationContext(), "网络异常",
Toast.LENGTH_SHORT).show();
enterHome();
break;
case URL_ERROR:
Toast.makeText(SplashActivity.this, "URL错误", Toast.LENGTH_SHORT)
.show();
enterHome();
break;
default:
break;
}
}
};
/**
* 升级提示对话框
*/
private void showUpdateDialog() {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("升级提示");
builder.setMessage(description);
builder.setPositiveButton("马上升级", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(getApplicationContext(), "找不到SD卡,请安装后再试",
Toast.LENGTH_LONG).show();
return;
}
FinalHttp finalHttp = new FinalHttp();
finalHttp.download(apkurl,
Environment.getExternalStorageDirectory()
+ "/mobilesafe2.0.apk",
new AjaxCallBack<File>() {
@Override
public void onFailure(Throwable t, int errorNo,
String strMsg) {
super.onFailure(t, errorNo, strMsg);
Toast.makeText(getApplicationContext(), "下载失败",
Toast.LENGTH_LONG).show();
}
@Override
public void onLoading(long count, long current) {
super.onLoading(count, current);
int progress = (int) (current * 100 / count);
tv_splash_update.setText("下载进度:" + progress
+ "%");
}
@Override
public void onSuccess(File t) {
super.onSuccess(t);
installApk(t);
}
private void installApk(File t) {
// Intent intent =new
// Intent(Intent.ACTION_VIEW);
// intent.setDataAndType(Uri.fromFile(t),
// "application/vnd.android.package-archive");
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.fromFile(t),
"application/vnd.android.package-archive");
startActivity(intent);
}
});
}
});
builder.setNegativeButton("下次再说", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
enterHome();
}
});
builder.show();
}
/**
* 进入主页
*/
private void enterHome() {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
tv_splash_update = (TextView) findViewById(R.id.tv_splash_update);
tv_splash_version.setText("版本号" + getVersionName());
// 检查版本
checkUpdate();
// 渐变显示界面
AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);
aa.setDuration(1400);
findViewById(R.id.rl_root_splash).startAnimation(aa);
}
/**
* 检查是否有新版本
*/
private void checkUpdate() {
new Thread() {
public void run() {
Message msg = Message.obtain();
long startTime = System.currentTimeMillis();
try {
URL url = new URL(getString(R.string.serverurl));
try {
// 联网
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(4000);
InputStream is = conn.getInputStream();
String result = StreamTool.readFromStream(is);
Log.i(TAG, "联网成功了: " + result);
try {
JSONObject obj = new JSONObject(result);
String version = (String) obj.get("version");
description = (String) obj.get("description");
apkurl = (String) obj.get("apkurl");
// 检查版本
if (getVersionName().equals(version)) {
// 版本一致
msg.what = ENTER_HOME;
} else {
// 版本更新
msg.what = UPDATE;
}
} catch (JSONException e) {
msg.what = JSON_ERROR;
e.printStackTrace();
}
} catch (IOException e) {
msg.what = NETWORK_ERROR;
e.printStackTrace();
}
} catch (MalformedURLException e) {
msg.what = URL_ERROR;
e.printStackTrace();
} finally {
long endTime = System.currentTimeMillis();
long dTime = endTime - startTime;
if (dTime < 2000) {
try {
Thread.sleep(2000 - dTime);
} catch (InterruptedException e) {
Log.i(TAG, "显示超时异常");
e.printStackTrace();
}
}
handler.sendMessage(msg);
}
};
}.start();
}
/**
* 得到应用程序的版本名称
*
* @return 版本名称
*/
private String getVersionName() {
// apk管理者
PackageManager pm = getPackageManager();
try {
// apk功能清单文件信息
PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
return info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return "";
}
}
}
HomeActivity.java
package com.itheima.mobilesafe;
import android.app.Activity;
import android.os.Bundle;
public class HomeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
}
activity_splash.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_root_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/luncher_bg"
tools:context="com.itheima.mobilesafe.SplashActivity" >
<TextView
android:id="@+id/tv_splash_version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:shadowColor="#ff0000"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1"
android:text="版本号1.0"
android:textColor="#000000"
android:textSize="20sp" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_splash_version"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tv_splash_update"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载进度:0%"
android:textSize="20sp"
android:textColor="#000000"
/>
</RelativeLayout>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is home"
android:textSize="25sp" />
</LinearLayout>
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.mobilesafe"
android:versionCode="2"
android:versionName="2.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".SplashActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.itheima.mobilesafe.HomeActivity"/>
</application>
</manifest>
源码下载:http://yunpan.cn/cyBAqbr3zyxKw 访问密码 a32b