Android 项目开发基础再回顾(一)
1,主activity_splash:
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/launcher_bg"//设置初始背景图片 tools:context=".SplashActivity" > android:id="@+id/tv_version_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"#把这个textview 放到中间 android:shadowDx="1//这个指的是相对于原字体在x方向上的偏移量 android:shadowDy="1" android:shadowColor="#f00"//黑色 android:shadowRadius="1"//表示阴影的模糊程度 android:textSize="16sp" android:text="版本名称" /> android:layout_below="@id/tv_version_name" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
2,副activity_home
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > android:text="HomeActivity" android:textSize="20sp" android:textColor="#000" android:layout_width="wrap_content" android:layout_height="wrap_content" />
3,让第二个活动可以启动
android:name="com.example.moblesafe73.HomeActivity"/>
4,接下来创造两个工具类,
一个是将流转化为字符串
mport java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamUtil {
public static String StreamToString(InputStream is) {
//1.在读取的过程中,将读取的内容存取到缓存中,然后一次性用字符转化成字符串
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//2.读取操作,读到没有为止(循环)
byte[] buffer=new byte[1024];
//3.记录读取内容的临时变量
int temp=-1;
try {
while((temp=is.read(buffer))!=-1){
bos.write(buffer,0,temp);
}
//返回读取的数据
return bos.toString();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
try {
is.close();
bos.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
return null;
}
}
另一个是可以弹出toast
import android.content.Context;
import android.widget.Toast;
public class ToastUtils {
public static void show(Context ctx,String msg){
Toast.makeText(ctx, msg, 0).show();
}
}
5,主营业务的介绍:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去除当前activity头title
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
//初始化ui
initUI();
//初始化方法
initData();
}
6,关于如何初始化ui
private void initUI() {
// TODO 自动生成的方法存根
tv_version_name = (TextView) findViewById(R.id.tv_version_name);
}
找到相应控件
private void initData() {
// TODO 自动生成的方法存根
//应用版本名称
tv_version_name.setText(getVersionName());
//获取本地服务版本号
myLockVersionCode = getVersionCode();
//获取服务器版本号(客户端发请求,服务器给相应(json,xml一般用的是json))
checkVersion();
}
//返回版本号
private int getVersionCode() {
// TODO 自动生成的方法存根
//1,包管理者对象packagemanager
PackageManager pm=getPackageManager();
//2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号,0代表基本信息)
try {
PackageInfo packageinfo=pm.getPackageInfo(getPackageName(), 0);
return packageinfo.versionCode;
} catch (NameNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return 0;
}
这个方法可以
再来看checkVersion();方法
如果上网的话需要用到线程方面的知识
private void checkVersion() {
new Thread(){
public void run(){
//Message message=new Message();
Message msg=Message.obtain();
long startTime=System.currentTimeMillis();//程序开始的时间
try {
//封装url地址
URL url=new URL("http://192.168.1.104:8080/update74.json");
//开启一个地址
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
//3,设置常见的请求参数(请求头)
//请求超时
connection.setConnectTimeout(2000);
//读取超时
connection.setReadTimeout(2000);
//默认是get请求
//connection.setRequestMethod("POST");
//获取请求响应码
if(connection.getResponseCode()==200){
//5.以流的形式,将数据保存起来
InputStream is=connection.getInputStream();
//6.将流换成字符串(工具类封装)
String json=StreamUtil.StreamToString(is);
Log.i(tag, json);//打印日志
//7.json解析
JSONObject jsonObject=new JSONObject(json);
String versionName=jsonObject.getString("versionName");
mversionDes = jsonObject.getString("versionDes");
String versionCode=jsonObject.getString("versionCode");
mdownloadUrl = jsonObject.getString("downloadUrl");
Log.i(tag, versionName);
Log.i(tag, mversionDes);
Log.i(tag, versionCode);
Log.i(tag, mdownloadUrl);
//8,比对版本号(服务器版本号,提示用户更新)
if(myLockVersionCode //提示用户更新,弹出对话框 msg.what=UPDATE_VERSION; }else{ //进入应用程序主界面 msg.what=ENTER_HOME; } } }catch (MalformedURLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); msg.what=URL_ERROR; }catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); msg.what=IO_ERROR; } catch (JSONException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); msg.what=JSON_ERROR; }finally{ //请求网络的时长超过四秒则不做处理 //请求小于四秒,强制让其睡眠四秒 long endTime=System.currentTimeMillis(); if(endTime-startTime<4000) { try { Thread.sleep(4000-(endTime-startTime)); } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } mhandler.sendMessage(msg); } }; }.start(); 对上述信息进行相关的处理: private Handler mhandler=new Handler(){ public void handleMessage(android.os.Message msg){ switch(msg.what){ case UPDATE_VERSION: //弹出对话框,提示用户更新 showUpdateDialog();//弹出一个对话框,让我们进行更新 break; case ENTER_HOME: enterHome(); break; case IO_ERROR: ToastUtils.show(getApplicationContext(), "IO异常"); enterHome(); break; case URL_ERROR: ToastUtils.show(getApplicationContext(), "url异常"); enterHome(); break; case JSON_ERROR: ToastUtils.show(getApplicationContext(), "URL异常");//SplashActivity.this enterHome(); break; } } }; protected void showUpdateDialog() { // TODO 自动生成的方法存根 //对话框是依赖activity存在的 Builder builder = new AlertDialog.Builder(this);//必须用this,而不是getApplicationContext() builder.setIcon(R.drawable.ic_launcher); builder.setTitle("版本更新"); //设置描述内容 builder.setMessage(mversionDes);//这个描述内容见上文是由其发送过来的 //积极按钮,立即更新 builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //下载apk,apk链接地址,downloadUrl downloadApk(); } });//创建两个按钮监听器 builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //取消对话框,进入主界面 enterHome(); } }); builder.show(); } 接下来是对文件进行下载 protected void downloadApk() { //apk下载链接地址,放置apk的所在路径 //1,判断sd卡是否可用,是否挂在上 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //2,获取sd卡路径 String path=Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator+"mobilesafe73.apk"; //发送请求,获取sdk,并且添加到指定路径 HttpUtils httpUtils=new HttpUtils(); //发送请求,传递参数吧(下载应用放置的位置) httpUtils.download(mdownloadUrl, path,new RequestCallBack @Override public void onSuccess(ResponseInfo Log.i(tag, "下载成功"); // TODO 自动生成的方法存根 File file=responseInfo.result; //提示用户安装 installAPK(file); } @Override public void onFailure(HttpException arg0, String arg1) { Log.i(tag, "下载失败"); // TODO 自动生成的方法存根 } @Override public void onStart() { // TODO 自动生成的方法存根 Log.i(tag, "开始下载"); super.onStart(); } @Override public void onLoading(long total, long current, boolean isUploading) { // TODO 自动生成的方法存根 Log.i(tag, "下载中........"); Log.i(tag, "total = "+total); Log.i(tag, "current = "+current); super.onLoading(total, current, isUploading); } }); } } //开始安装 protected void installAPK(File file) { // TODO 自动生成的方法存根 //系统应用界面,源码,安装apk入口 Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); /*//文件作为数据源 intent.setData(Uri.fromFile(file)); //设置安装的类型 intent.setType("application/vnd.android.package-archive");*/ intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); // startActivity(intent); startActivityForResult(intent, 0); } //开启另一个界面 protected void enterHome() { Intent intent = new Intent(this,HomeActivity.class); startActivity(intent); //在开启一个新的界面后将导航界面关闭,因为导航界面只可见一次 finish(); }更多相关文章
随机推荐