zoukankan      html  css  js  c++  java
  • [置顶] Android问题SharedPreferences来判断程序是不是第一次运行

    SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,比如我们可以通过SharedPreferences来判断程序是不是第一次运行。

    下面的实例将用于介绍怎样通过SharedPreferences来判断程序是否是第一次运行,其实现思路很简单,通过在SharedPreferences中存储键值表示程序是否第一次运行。代码如下:

    public class PreferenceTestMain extends Activity {
            public static final String PREFS_NAME = "MyPrefsFile";
            public static final String FIRST_RUN = "first";
            private boolean first;
    
            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                    // Restore preferences
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    first = settings.getBoolean(FIRST_RUN, true);
                    if (first) {
                            Toast.makeText(this, "The Application is first run",
                                            Toast.LENGTH_LONG).show();
                    } else {
                            Toast.makeText(this, "The Application is not first run",
                                            Toast.LENGTH_LONG).show();
                    }
    
            }
    
            @Override
            protected void onStop() {
                    super.onStop();
    
                    // We need an Editor object to make preference changes.
                    // All objects are from android.context.Context
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    if (first) {
                            editor.putBoolean(FIRST_RUN, false);
                    }
                    // Commit the edits!
                    editor.commit();
            }
    
    }

    其中在 onCreate 方法中读取SharedPreferences 信息,在 onStop 中保存 SharedPreferences信息。注意程序的状态信息一般都在 onStop 保存。


  • 相关阅读:
    bzoj3524: [Poi2014]Couriers(主席树)
    51nod 1275 连续子段的差异(twopointer+单调队列)
    51nod 1274 最长递增路径(DP)
    51nod 1273 旅行计划(思维题)
    51nod 1257 背包问题 V3(分数规划)
    CSS 几款比较常用的翻转特效
    css文字飞入效果
    jQuery使用方法
    数据库
    关系型数据库基本概念及MySQL简述
  • 原文地址:https://www.cnblogs.com/anjon520/p/3249943.html
Copyright © 2011-2022 走看看