关于onCreate(Bundle savedInstanceState, PersistableBundle persistentState)

今天在我写demo的时候遇到一个问题,当我加载Activity界面的时候,打出onCreate随手回车,setContentView之后却始终无法显示界面,找遍一切可能出错的地方,最后在这个onCreate方法上面发现了猫腻。系统自动给我提供了这么一个onCreate()。

@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

第一反应,我并不认识这是一个什么玩意。打开陈旧的api文档,也没有发现PersistableBundle这个类,于是只能求助百度,Google。原来是Api21新加的特性,上一下google,找一下最新api。我们先来看一下PersistableBundle是什么东西。

A mapping from String values to various types that can be saved to persistent and later restored.

显然,这是一个和Bundle差不多的东西,Bundle我们就比较熟悉了。他两都是一个键值对,前者多了这么一段话,can be saved to persistent and later restored,可以持久化保存并且可以恢复。我们再看一下新的onCreate()方法的源码。

/**
     * Same as {@link #onCreate(android.os.Bundle)} but called for those activities created with
     * the attribute {@link android.R.attr#persistableMode} set to
     * persistAcrossReboots.
     *
     * @param savedInstanceState if the activity is being re-initialized after
     *     previously being shut down then this Bundle contains the data it most
     *     recently supplied in {@link #onSaveInstanceState}.
     *     Note: Otherwise it is null.
     * @param persistentState if the activity is being re-initialized after
     *     previously being shut down or powered off then this Bundle contains the data it most
     *     recently supplied to outPersistentState in {@link #onSaveInstanceState}.
     *     Note: Otherwise it is null.

    public void onCreate(@Nullable Bundle savedInstanceState,
            @Nullable PersistableBundle persistentState) {
        onCreate(savedInstanceState);
    }

 从源码中可以看到,依然是调用了原始的onCreate()方法,结合以下两个方法,

@Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onRestoreInstanceState(savedInstanceState, persistentState);
    }

最后记得在配置文件中注册当前Activity的时候加上这个属性,android:persistableMode=”persistAcrossReboots”,这样就可以给你的Activity存储一些持久化数据。当你的手机重启或者发生其他意外情况的时候,也可以给你的页面获取到相关数据。
没有5.0的设备还没有验证过。。有没有试过的朋友说一下。。

【转载说明】
http://blog.csdn.net/sunluyao_/article/details/50395791http://blog.csdn.net/sunluyao_/article/details/50395791

你可能感兴趣的:(Android点滴)