手机安全卫士学习第一课 闪屏页面Splash

学习完了四大组件 然后按照黑马课程就是安全卫士了 

四大组件学习之后感觉印象不是很深刻,所以趁着这个项目好好练习练习。

个人喜欢在注释中描述所以就只姐连着注释代码和注释一起贴上先!

首先是onCreate中


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_layout);
//        初始化控件
        tvVersion= (TextView) findViewById(R.id.splash_version);
        tvVersion.setText("版本号: "+getVersionName());
//        方法:检查版本
        checkVerson();
    }

在闪屏页的开始就需要进行版本号的比对

所有下面是checkVersion()方法

   /*
    * 网络访问是不可以在主线程中进行的*/
    private void checkVerson(){
        //获取开始时间
        final long startTime=System.currentTimeMillis();

     /*开启子线程*/
        new Thread(new Runnable() {
            @Override
            public void run() {
//                创建网络连接
                HttpURLConnection conn=null;
//                创建一个信息
                Message message=Message.obtain();
                try {
                    //本机地址用localhost,但是如果用模拟器加载本机的地址时,
                    // 可以用ip10.0.2.2)来替换
                    //这里的URL是乱写的~~
                    URL url=new URL("http://www.baidu.com");
                    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.readFormStream(inputStream);
                        System.out.print(result);
                        
                        //上面是一个标准的网络连接然后获取数据的模式 背下来好了
                        
                        
                        //因为实际是没有接收到JSON数据所以就没法真正的解析JSON
                        //不过JSON在之前的老黄历项目中已经研究过了所以还好
                        /*
                        * 解析JSON*/
                       /* JSONObject jo=new JSONObject(result);
                        mVersionName=jo.getString("versionName");
                        mVersionCode=jo.getInt("versionCode");
                        mDesc=jo.getString("Desc");*/
                        //JSON传回的版本号和此应用的版本号进行比对
                        //这里模拟JSON传回版本号是2 所以肯定会提示更新
                        if(mVersionCode>getVersionCode()){
                            //判断是否有更新
                            message.what=CODE_UPDATE_DIALOG;
                        }else{
                            message.what=CODE_ENTER_HOME;
                        }
                    }
                } catch (MalformedURLException e) {
                    //URL错误异常
                    message.what=CODE_URL_ERROR;
                    e.printStackTrace();
                } catch (IOException e) {
                    //网络错误异常
                    message.what=CODE_NET_ERROR;
                    enterHome();
                    e.printStackTrace();
                }finally {
                    long endTime=System.currentTimeMillis();
                    //访问网络发挥的时间
                    long timeUsed=endTime-startTime;
                    if(timeUsed<2000){
                        //强制休眠一段时间,保证闪屏页展示两秒钟
                        try {
                            Thread.sleep(2000-timeUsed);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendMessage(message);
                    if(conn!=null){
                        conn.disconnect();
                    }
                }
            }
        }).start();

    }
这里使用了一个工具类

StreamUtils

/**
 * Created by admin on 2016/5/9.
 */
public class StreamUtils {
    /*
    * 将输入流读取成String后返回*/
    public static String readFormStream(InputStream in) throws IOException {
        //1 创建输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        
        int len = 0;
        byte[] buffer = new byte[1023];
        //2 读取输入流并写入输出流
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        String result = out.toString();
        //3 关闭输入流与输出流
        in.close();
        out.close();
        return result;
    }
}

还有就是获取版本号的方法

    /*
* 获取版本号*/
    private int getVersionCode(){
        PackageManager packageManager=getPackageManager();
        try {
            PackageInfo packageInfo=packageManager.getPackageInfo(getPackageName(),
                    0);//获取包的信息
            int versionCode=packageInfo.versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }
对于子线程中传回的消息有对应的处理

这里贴上Handler

//    Handler来接收子线程中返回的信息然后做出相应的反应
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CODE_UPDATE_DIALOG:
                    showUpdateDailog();
                    break;
                case CODE_URL_ERROR:
                    Toast.makeText(SplashActivity.this, "URL异常", Toast.LENGTH_SHORT).show();
                    break;
                case CODE_NET_ERROR:
                    Toast.makeText(SplashActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
                case CODE_ENTER_HOME:
                    enterHome();
                    break;
            }
        }
    };

如果发现有更新 就弹出对话框提示更新

/*
弹出更新对话框
* */
private void showUpdateDailog() {
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setTitle("最新版本"+mVersionName);
    builder.setMessage(mDesc);
    builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(SplashActivity.this, "更新", Toast.LENGTH_SHORT).show();
            download();
        }
    });
    builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            enterHome();
        }
    });
    builder.show();
}
对话框的实现已经做了好几次了所以就还好啦

然后这里如果选择更新  会调用 download方法

这里使用了一个开源框架 xUtils

代码如下

/*
* 下载APK文件*/
private void download() {

    //判断SD卡的状态 判断是否挂载

    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String target =Environment.getExternalStorageDirectory() + "/upfate.apk";
        //XUtils开源框架
        HttpUtils utils = new HttpUtils();
        utils.download("", target, new RequestCallBack<File>() {

            //下载文件的进度
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
                System.out.print("下载进度:" + current + "/" + total);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                System.out.print("下载失败");
            }

            @Override
            public void onFailure(HttpException e, String s) {
                System.out.print("下载成功");
            }
        });
    }

}
非常方便有木有!!~~~

其实这个框架提供了好多功能 在后面好好学习一下~


当然弹窗如果选择不care就直接跳转到主页面啦 intent搞定就可以

贴上源码  很多地方有模拟 但是也能表现一些知识点了

注意一下 在选择下载新版本的时候为了防止网速太快导致闪屏页太快跳转所以让子线程睡了一会儿 

long endTime=System.currentTimeMillis();
//访问网络发挥的时间
long timeUsed=endTime-startTime;
if(timeUsed<2000){
    //强制休眠一段时间,保证闪屏页展示两秒钟
    try {
        Thread.sleep(2000-timeUsed);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
mHandler.sendMessage(message);
总之是要看两秒我的闪屏页就是了 哈哈哈

源码如下:

package skkk.admin.com.newgoal.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

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 skkk.admin.com.newgoal.R;
import skkk.admin.com.newgoal.utils.StreamUtils;

public class SplashActivity extends AppCompatActivity {
    private static final int CODE_UPDATE_DIALOG =0;
    private static final int CODE_URL_ERROR = 1;
    private static final int CODE_NET_ERROR = 2;
    private static final int CODE_ENTER_HOME = 4;
    private TextView tvVersion;
    String mVersionName;
    private int mVersionCode=2;
    private String mDesc;
//    用Handler来接收子线程中返回的信息然后做出相应的反应
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CODE_UPDATE_DIALOG:
                    showUpdateDailog();
                    break;
                case CODE_URL_ERROR:
                    Toast.makeText(SplashActivity.this, "URL异常", Toast.LENGTH_SHORT).show();
                    break;
                case CODE_NET_ERROR:
                    Toast.makeText(SplashActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
                case CODE_ENTER_HOME:
                    enterHome();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_layout);
//        初始化控件
        tvVersion= (TextView) findViewById(R.id.splash_version);
        tvVersion.setText("版本号: "+getVersionName());
//        方法:检查版本
        checkVerson();
    }

    /*
    * 获取版本名字*/
    private String getVersionName(){
        PackageManager packageManager=getPackageManager();
        try {
            PackageInfo packageInfo=packageManager.getPackageInfo(getPackageName(),
                    0);//获取包的信息
            String versionName=packageInfo.versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /*
* 获取版本号*/
    private int getVersionCode(){
        PackageManager packageManager=getPackageManager();
        try {
            PackageInfo packageInfo=packageManager.getPackageInfo(getPackageName(),
                    0);//获取包的信息
            int versionCode=packageInfo.versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /*
    * 网络访问是不可以在主线程中进行的*/
    private void checkVerson(){
        //获取开始时间
        final long startTime=System.currentTimeMillis();

     /*开启子线程*/
        new Thread(new Runnable() {
            @Override
            public void run() {
//                创建网络连接
                HttpURLConnection conn=null;
//                创建一个信息
                Message message=Message.obtain();
                try {
                    //本机地址用localhost,但是如果用模拟器加载本机的地址时,
                    // 可以用ip(10.0.2.2)来替换
                    //这里的URL是乱写的~~
                    URL url=new URL("http://www.baidu.com");
                    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.readFormStream(inputStream);
                        System.out.print(result);

                        //上面是一个标准的网络连接然后获取数据的模式 背下来好了


                        //因为实际是没有接收到JSON数据所以就没法真正的解析JSON
                        //不过JSON在之前的老黄历项目中已经研究过了所以还好
                        /*
                        * 解析JSON*/
                       /* JSONObject jo=new JSONObject(result);
                        mVersionName=jo.getString("versionName");
                        mVersionCode=jo.getInt("versionCode");
                        mDesc=jo.getString("Desc");*/
                        //对JSON传回的版本号和此应用的版本号进行比对
                        //这里模拟JSON传回版本号是2 所以肯定会提示更新
                        if(mVersionCode>getVersionCode()){
                            //判断是否有更新
                            message.what=CODE_UPDATE_DIALOG;
                        }else{
                            message.what=CODE_ENTER_HOME;
                        }
                    }
                } catch (MalformedURLException e) {
                    //URL错误异常
                    message.what=CODE_URL_ERROR;
                    e.printStackTrace();
                } catch (IOException e) {
                    //网络错误异常
                    message.what=CODE_NET_ERROR;
                    enterHome();
                    e.printStackTrace();
                }finally {
                    long endTime=System.currentTimeMillis();
                    //访问网络发挥的时间
                    long timeUsed=endTime-startTime;
                    if(timeUsed<2000){
                        //强制休眠一段时间,保证闪屏页展示两秒钟
                        try {
                            Thread.sleep(2000-timeUsed);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendMessage(message);
                    if(conn!=null){
                        conn.disconnect();
                    }
                }
            }
        }).start();

    }

    /*
    弹出更新对话框
    * */
    private void showUpdateDailog() {
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("最新版本"+mVersionName);
        builder.setMessage(mDesc);
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(SplashActivity.this, "更新", Toast.LENGTH_SHORT).show();
                download();
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
            }
        });
        builder.show();
    }

    /*
    * 下载APK文件*/
    private void download() {

        //判断SD卡的状态 判断是否挂载

        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String target =Environment.getExternalStorageDirectory() + "/upfate.apk";
            //XUtils开源框架
            HttpUtils utils = new HttpUtils();
            utils.download("", target, new RequestCallBack<File>() {

                //下载文件的进度
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    System.out.print("下载进度:" + current + "/" + total);
                }

                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    System.out.print("下载失败");
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    System.out.print("下载成功");
                }
            });
        }

    }


    private  void enterHome(){
        Intent intent=new Intent(SplashActivity.this,HomeActivity.class);
        startActivity(intent);
        finish();
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值