Android 开发之 Splash 页面 3 秒跳转

最近公司产品经理说我们需要一个动态替换的闪屏页面,like 京东、直播吧一样,可以动态替换。
产品大大就是厉害,说一句话我们就需要实现好几个功能:

创建一个冷启动后的闪屏页面(Splash 页面)
这个页面默认 3s 倒计时,点击倒计时按钮可以跳转并结束倒计时
点击图片如果有外链,则跳转应用的 web 页面用来作为活动页面(没错这点和某猫很像)

效果图

布局实现

activity_splash.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">
    <ImageView
        android:id="@+id/sp_bg"
        android:src="@drawable/welcome"
        android:layout_marginBottom="80dp"
        android:scaleType="centerCrop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <Button
        android:visibility="invisible"
        android:gravity="center"
        android:textSize="16sp"
        android:textColor="@color/white"
        android:id="@+id/sp_jump_btn"
        android:background="@drawable/btn_splash_shape"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="8dp"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:layout_alignParentBottom="true"
        android:src="@drawable/bottom_bg"
        android:scaleType="center"
        android:layout_width="match_parent"
        android:layout_height="80dp" />

RelativeLayout>

使用 CountDownTimer 实现倒计时

SplashActivity.java

public class SplashActivity extends AppCompatActivity {
    private Button mBtnJump;
    private ImageView mPicAD;

    private CountDownTimer countDownTimer = new CountDownTimer(3200,1000) {
        @Override
        public void onTick(long l) {
            mBtnJump.setText("跳过广告"+ l/1000 + "s" );
        }

        @Override
        public void onFinish() {
            mBtnJump.setText("跳过广告"+0+"s");
            toMainActivity();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        mBtnJump = (Button)findViewById(R.id.sp_jump_btn);
        mPicAD = (ImageView)findViewById(R.id.sp_bg);

        startClock();

        mBtnJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toMainActivity();
            }
        });

        mPicAD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toWebActivity();
            }
        });




    }

    private void startClock() {
        mBtnJump.setVisibility(View.VISIBLE);
        countDownTimer.start();
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}

主界面的实现

界面显示 必应首页 当天背景的图片,利用 OKhttp 网络框架、Glide 图片加载框架,主界面先在 app 文件夹下的 build.gradle 添加:

compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView)findViewById(R.id.iv_image);

        String bingPic = (String)SPUtils.get(this, "bing_pic", null);

        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(imageView);
        }else {
            loadingBingPic();
        }

    }

    /**
     * 加载必应每日一图
     */
    private void loadingBingPic() {
        String requestBing = "http://guolin.tech/api/bing_pic";

        HttpUtil.sendOkHttpRequest(requestBing, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();

                SPUtils.put(MainActivity.this,"bing_pic",bingPic);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(MainActivity.this).load(bingPic).into(imageView);
                    }
                });


            }
        });
    }
}

上述用到的工具类:

HttpUtil.java

package com.gyq.splashdemo.utils;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpUtil {

    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(address).build();
        client.newCall(request).enqueue(callback);
    }

}

SPUtils.java

package com.gyq.splashdemo.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by gyq on 2017/6/23 10:16
 */
public class SPUtils {
    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "share_data";

    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     *
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object)
    {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String)
        {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer)
        {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean)
        {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float)
        {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long)
        {
            editor.putLong(key, (Long) object);
        } else
        {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     *
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String)
        {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer)
        {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean)
        {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float)
        {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long)
        {
            return sp.getLong(key, (Long) defaultObject);
        }

        return null;
    }

    /**
     * 移除某个key值已经对应的值
     * @param context
     * @param key
     */
    public static void remove(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     * @param context
     */
    public static void clear(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map getAll(Context context)
    {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     *
     */
    private static class SharedPreferencesCompat
    {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        private static Method findApplyMethod()
        {
            try
            {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e)
            {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行,否则使用commit
         *
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor)
        {
            try
            {
                if (sApplyMethod != null)
                {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e)
            {
            } catch (IllegalAccessException e)
            {
            } catch (InvocationTargetException e)
            {
            }
            editor.commit();
        }
    }
}

WebView 实现我的 CSDN 博客显示

WebActivity.java

public class WebActivity extends AppCompatActivity {
    private WebView mWebView;
    private TextView mTitle;
    private ProgressBar mPb;
    private String titles;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        mWebView = (WebView)findViewById(R.id.wv);
        mTitle = (TextView)findViewById(R.id.txtTitle);
        mPb = (ProgressBar)findViewById(R.id.loadingProgress);

        //设置webView 属性,能够执行JavaScript脚本
        mWebView.getSettings().setJavaScriptEnabled(true);

        //需要加载的网页
        mWebView.loadUrl("http://blog.csdn.net/duoduo_11011");

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                titles = title;
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mTitle.setText("");
                mPb.setVisibility(View.VISIBLE);
                mPb.setProgress(newProgress * 100);
                if (newProgress == 100) {
                    mPb.setVisibility(View.GONE);
                    mTitle.setText(titles);
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    public void close(View view) {
        toMainActivity();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        }else {
            toMainActivity();
        }
    }



    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null,"","text/html","utf-8",null);
            mWebView.clearHistory();

            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    private void toMainActivity() {
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }
}

你可能感兴趣的:(Android,基础)