详解Android中App的启动界面Splash的编写方法
一、Splash界面的作用
用来展现产品的Logo
应用程序初始化的操作
检查应用程序的版本
检查当前应用程序是否合法注册
二、界面的xml定义
写一个布局背景设置为产品的logo图片,再添加一个textview显示版本号。
<TextView android:id="@+id/tv_splash_version" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:textStyle="bold" android:shadowDx="1"//阴影的偏移量 android:shadowDy="1" android:shadowRadius="0.2"//阴影的半径 android:shadowColor="#ffff00" android:text="版本:1.0" android:textSize="16sp" android:layout_centerInParent="true"/>
三、动态获取版本号的方法
publicStringgetAppVersion(){
PackageManagerpm=getPackageManager();
try{
PackageInfoinfo=pm.getPackageInfo(getPackageName(),0);
returninfo.versionName;
}catch(NameNotFoundExceptione){
e.printStackTrace();
//不可能发生;
return"";
}
}
四、链接服务器获取更新信息
升级提醒的对话框
protectedvoidshowUpdateDialog(){
AlertDialog.Builderbuild=newBuilder(this);
build.setTitle("发现新版本");
build.setMessage(description);
build.setNegativeButton("立刻升级",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
//升级的代码;
};
});
build.setPositiveButton("下次再说",newOnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.dismiss();
enterHome();
}
});
build.show();
在子线程中请求服务器的代码checkup()方法
privatevoidcheckup(){
newThread(){
publicvoidrun(){
Messagemsg=Message.obtain();
longstartTime=System.currentTimeMillis();//启动该线程的系统时间
try{
//请求网络的代码
URLurl=newURL(getString(R.string.serverurl));
HttpURLConnectionconn=(HttpURLConnection)url
.openConnection();
conn.setRequestMethod("GET");//请求方法
conn.setConnectTimeout(4000);//超时时间
intcode=conn.getResponseCode();//返回码200请求成功
if(code==200){
InputStreamis=conn.getInputStream();
Stringresult=StreamTools.readFromStream(is);
Log.i(TAG,"联网成功"+result);
JSONObjectobj=newJSONObject(result);//解析json字符串
Stringversion=(String)obj.get("version");//版本信息
description=(String)obj.get("description");//描述信息
apkurl=(String)obj.get("apkurl");
if(getAppVersion().equals(version)){
msg.what=ENTER_HOME;
}else{
msg.what=SHOW_UPDATE_DIALOG;
}
}
}catch(MalformedURLExceptione){
e.printStackTrace();
msg.what=URL_ERROR;
}catch(IOExceptione){
e.printStackTrace();
msg.what=NETWORK_ERROR;
}catch(JSONExceptione){
e.printStackTrace();
msg.what=JSON_ERROR;
}finally{
handler.sendMessage(msg);
longendTime=System.currentTimeMillis();//该线程执行完毕的时间
longdTime=endTime-startTime;//该线程的阻塞时间
if(dTime<3000){
try{
Thread.sleep(3000-dTime);//若该线程的阻塞时间小于三秒继续睡眠到三秒
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
}.start();
}
handler
privateHandlerhandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
//TODOAuto-generatedmethodstub
super.handleMessage(msg);
switch(msg.what){
caseSHOW_UPDATE_DIALOG:
showUpdateDialog();
break;
caseENTER_HOME:
Toast.makeText(getApplicationContext(),"",0).show();
enterhome();
break;
caseURL_ERROR:
Toast.makeText(getApplicationContext(),"URL_ERROR",0).show();
enterhome();
break;
caseNETWORK_ERROR:
Toast.makeText(getApplicationContext(),"NETWORK_ERROR",0).show();
enterhome();
break;
caseJSON_ERROR:
Toast.makeText(getApplicationContext(),"JSON_ERROR",0).show();
enterhome();
break;
}
}
};
五、下载文件(使用Afinal框架)并调用系统安装工具安装APK
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
FinalHttpfinalHttp=newFinalHttp();
finalHttp.download(apkurl,Environment.getExternalStorageDirectory().getAbsolutePath()+
"/mobilesafe2.0.apk",newAjaxCallBack<File>(){
@Override
publicvoidonLoading(longcount,longcurrent){
super.onLoading(count,current);
tv_uapdate_info.setVisibility(View.VISIBLE);
intprogress=(int)(current*100/count);
tv_uapdate_info.setText("下载进度:"+progress+"%");
}
@Override
publicvoidonFailure(Throwablet,interrorNo,
StringstrMsg){
t.printStackTrace();
Toast.makeText(getApplicationContext(),"下载失败",0).show();
enterhome();
super.onFailure(t,errorNo,strMsg);
}
@Override
publicvoidonSuccess(Filet){
super.onSuccess(t);
installAPK(t);
}
privatevoidinstallAPK(Filet){
Intentintent=newIntent();//自动安装程序可调用该段代码
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.DEFAULT");
intent.setDataAndType(Uri.fromFile(t),"application/vnd.android.package-archive");
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(),"请插入内存卡再试",0).show();
return;
}
其他:
1、显示4.0的样式:方式是去掉功能清单里的Activity对应的android:theme;
放到application里面;
2、当splash页面弹出升级提示框过滤点击返回的是两种方式:
builder.setCancelable(false);
设置setOnCancelListener当触屏的时候直接进入主页面
对话框是挂载在Activity上面的,如果Activity不存在,对话框就不能被创建。
getApplicationContext();生命周期长,只要应用还存活它就存在;this生命周期短,只要Activity不存在了,系统就会回收
其中:getBaseContext(),getApplication(),getApplicationContext();都不能放在AlertDialog做上下文;
3.Splash用来宣传和隐藏程序启动细节是很有用的。
用Handler的实现方法如下:(也可以用线程实现,不推荐)
定义一个Activity,用来显示你的图片,其中最重要的就是定义一个Handler,用来发送和接收消息:
publicclassWelcomeActivityextendsActivity
{
//定义一个handler,用来接收延迟发送的信息-启动activity
privateHandlerhandler=newHandler()
{
@Override
<spanstyle="color:#ff0000;">publicvoidhandleMessage(Messagemsg)</span>
{
//TODOAuto-generatedmethodstub
super.handleMessage(msg);
switch(msg.what)
{
case0x123:
Intentintent=newIntent(WelcomeActivity.this,
OnlineExamActivity.class);
startActivity(intent);
finish();
}
}
};
在onCreate()方法中,用handler发送消息,延迟3000毫秒:
@Override
protectedvoidonCreate(BundlesavedInstanceState)
{
//TODOAuto-generatedmethodstub
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_activity);
start();
}
privatevoidstart()
{
<spanstyle="color:#ff0000;">handler.sendEmptyMessageDelayed(0x123,3000);</span>
}
把你的图片放到布局文件中作背景即可。