闪屏页的布局
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 org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
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.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.utils.StreamUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
public class SplashActivity extends Activity {
protected static final int CODE_UPDATE_DIALOG = 0;
protected static final int CODE_URL_ERROR = 1;
protected static final int CODE_NET_ERROR = 2;
protected static final int CODE_JSON_ERROR = 3;
protected static final int CODE_ENTER_HOME = 4;// 进入主页面
private TextView tvVersion;
private TextView tvProgress;// 下载进度展示
// 服务器返回的信息
private String mVersionName;// 版本名
private int mVersionCode;// 版本号
private String mDesc;// 版本描述
private String mDownloadUrl;// 下载地址
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case CODE_UPDATE_DIALOG:
showUpdateDailog();
break;
case CODE_URL_ERROR:
Toast.makeText(SplashActivity.this, "url错误", Toast.LENGTH_SHORT)
.show();
enterHome();
break;
case CODE_NET_ERROR:
Toast.makeText(SplashActivity.this, "网络错误", Toast.LENGTH_SHORT)
.show();
enterHome();
break;
case CODE_JSON_ERROR:
Toast.makeText(SplashActivity.this, "数据解析错误",
Toast.LENGTH_SHORT).show();
enterHome();
break;
case CODE_ENTER_HOME:
enterHome();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
tvVersion = (TextView) findViewById(R.id.tv_version);
tvVersion.setText("版本名:" + getVersionName());
tvProgress = (TextView) findViewById(R.id.tv_progress);// 默认隐藏
checkVerson();
}
/**
* 获取版本名称
*
* @return
*/
private String getVersionName() {
PackageManager packageManager = getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
getPackageName(), 0);// 获取包的信息
int versionCode = packageInfo.versionCode;
String versionName = packageInfo.versionName;
System.out.println("versionName=" + versionName + ";versionCode="
+ versionCode);
return versionName;
} catch (NameNotFoundException e) {
// 没有找到包名的时候会走此异常
e.printStackTrace();
}
return "";
}
/**
* 获取本地app的版本号
*
* @return
*/
private int getVersionCode() {
PackageManager packageManager = getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
getPackageName(), 0);// 获取包的信息
int versionCode = packageInfo.versionCode;
return versionCode;
} catch (NameNotFoundException e) {
// 没有找到包名的时候会走此异常
e.printStackTrace();
}
return -1;
}
/**
* 从服务器获取版本信息进行校验
*/
private void checkVerson() {
final long startTime = System.currentTimeMillis();
// 启动子线程异步加载数据
new Thread() {
@Override
public void run() {
Message msg = Message.obtain();
HttpURLConnection conn = null;
try {
// 本机地址用localhost, 但是如果用模拟器加载本机的地址时,可以用ip(10.0.2.2)来替换
URL url = new URL("http://10.0.2.2:8080/update.json");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");// 设置请求方法
conn.setConnectTimeout(5000);// 设置连接超时
conn.setReadTimeout(5000);// 设置响应超时, 连接上了,但服务器迟迟不给响应
conn.connect();// 连接服务器
int responseCode = conn.getResponseCode();// 获取响应码
if (responseCode == 200) {
InputStream inputStream = conn.getInputStream();
String result = StreamUtils.readFromStream(inputStream);
// System.out.println("网络返回:" + result);
// 解析json
JSONObject jo = new JSONObject(result);
mVersionName = jo.getString("versionName");
mVersionCode = jo.getInt("versionCode");
mDesc = jo.getString("description");
mDownloadUrl = jo.getString("downloadUrl");
// System.out.println("版本描述:" + mDesc);
if (mVersionCode > getVersionCode()) {// 判断是否有更新
// 服务器的VersionCode大于本地的VersionCode
// 说明有更新, 弹出升级对话框
msg.what = CODE_UPDATE_DIALOG;
} else {
// 没有版本更新
msg.what = CODE_ENTER_HOME;
}
}
} catch (MalformedURLException e) {
// url错误的异常
msg.what = CODE_URL_ERROR;
e.printStackTrace();
} catch (IOException e) {
// 网络错误异常
msg.what = CODE_NET_ERROR;
e.printStackTrace();
} catch (JSONException e) {
// json解析失败
msg.what = CODE_JSON_ERROR;
e.printStackTrace();
} finally {
long endTime = System.currentTimeMillis();
long timeUsed = endTime - startTime;// 访问网络花费的时间
if (timeUsed < 2000) {
// 强制休眠一段时间,保证闪屏页展示2秒钟
try {
Thread.sleep(2000 - timeUsed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mHandler.sendMessage(msg);
if (conn != null) {
conn.disconnect();// 关闭网络连接
}
}
}
}.start();
}
/**
* 升级对话框
*/
protected void showUpdateDailog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("最新版本:" + mVersionName);
builder.setMessage(mDesc);
// builder.setCancelable(false);//不让用户取消对话框, 用户体验太差,尽量不要用
builder.setPositiveButton("立即更新", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.out.println("立即更新");
download();
}
});
builder.setNegativeButton("以后再说", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
enterHome();
}
});
// 设置取消的监听, 用户点击返回键时会触发
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
enterHome();
}
});
builder.show();
}
/**
* 下载apk文件
*/
protected void download() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
tvProgress.setVisibility(View.VISIBLE);// 显示进度
String target = Environment.getExternalStorageDirectory()
+ "/update.apk";
// XUtils
HttpUtils utils = new HttpUtils();
utils.download(mDownloadUrl, target, new RequestCallBack<File>() {
// 下载文件的进度
@Override
public void onLoading(long total, long current,
boolean isUploading) {
super.onLoading(total, current, isUploading);
System.out.println("下载进度:" + current + "/" + total);
tvProgress.setText("下载进度:" + current * 100 / total + "%");
}
// 下载成功
@Override
public void onSuccess(ResponseInfo<File> arg0) {
System.out.println("下载成功");
// 跳转到系统下载页面
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(Uri.fromFile(arg0.result),
"application/vnd.android.package-archive");
// startActivity(intent);
startActivityForResult(intent, 0);// 如果用户取消安装的话,
// 会返回结果,回调方法onActivityResult
}
// 下载失败
@Override
public void onFailure(HttpException arg0, String arg1) {
Toast.makeText(SplashActivity.this, "下载失败!",
Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(SplashActivity.this, "没有找到sdcard!",
Toast.LENGTH_SHORT).show();
}
}
// 如果用户取消安装的话,回调此方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
enterHome();
super.onActivityResult(requestCode, resultCode, data);
}
/**
* 进入主页面
*/
private void enterHome() {
Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}
}
主页面的布局 HomeActivity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.itheima52.mobilesafe.R;
/**
* 主页面
*
* @author Kevin
*
*/
public class HomeActivity extends Activity {
private GridView gvHome;
private String[] mItems = new String[] { "手机防盗", "通讯卫士", "软件管理", "进程管理",
"流量统计", "手机杀毒", "缓存清理", "高级工具", "设置中心" };
private int[] mPics = new int[] { R.drawable.home_safe,
R.drawable.home_callmsgsafe, R.drawable.home_apps,
R.drawable.home_taskmanager, R.drawable.home_netmanager,
R.drawable.home_trojan, R.drawable.home_sysoptimize,
R.drawable.home_tools, R.drawable.home_settings };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
gvHome = (GridView) findViewById(R.id.gv_home);
gvHome.setAdapter(new HomeAdapter());
}
class HomeAdapter extends BaseAdapter {
@Override
public int getCount() {
return mItems.length;
}
@Override
public Object getItem(int position) {
return mItems[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(HomeActivity.this,
R.layout.home_list_item, null);
ImageView ivItem = (ImageView) view.findViewById(R.id.iv_item);
TextView tvItem = (TextView) view.findViewById(R.id.tv_item);
tvItem.setText(mItems[position]);
ivItem.setImageResource(mPics[position]);
return view;
}
}
}
对获取服务器数据的
package com.itheima52.mobilesafe.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 读取流的工具
*
* @author Kevin
*
*/
public class StreamUtils {
/**
* 将输入流读取成String后返回
*
* @param in
* @return
* @throws IOException
*/
public static String readFromStream(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
String result = out.toString();
in.close();
out.close();
return result;
}
}
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:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#8866ff00"
android:gravity="center"
android:text="@string/tv_function"
android:textColor="@color/black"
android:textSize="22sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="有了手机卫士, 腰不酸了,腿不疼了,走路也有劲了, 手机卫士太NB了"
android:textColor="@color/black"
android:textSize="18sp" />
<GridView
android:id="@+id/gv_home"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:numColumns="3"
android:verticalSpacing="20dp" >
</GridView>
</LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/launcher_bg" >
<TextView
android:id="@+id/tv_version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:shadowColor="#f00"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1"
android:text="版本号:1.0"
android:textColor="#000"
android:textSize="16sp" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_version"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:text="下载进度"
android:visibility="gone"
android:textColor="#f00"
android:textSize="16sp" />
</RelativeLayout>
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima52.mobilesafe"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima52.mobilesafe.activity.SplashActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activity.HomeActivity" />
</application>
</manifest>
下载链接 http://download.csdn.net/detail/qq_26296197/9497330