您可以创建自己的Application类,并写在onCreate方法SharedPreferences。
public class MyApplication extends Application {
@Override
public void onCreate() {
SharedPreferences settings = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Boolean firstRun = settings.getBoolean("firstRun",true);
if(firstRun){
//insert your data into the shared preferences here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
}
}
AnroidManifest.xml
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name=".MyApplication">
...
</application>
把它写的onCreate –
它非常简单,你可以为此使用许多方法。您必须在应用程序第一次运行时插入数据,因此,首次在数据库中插入该数据,同时在偏好设置中存储一个布尔值var(true)。下次打开应用程序时检查该变量是否为真,则不需要再次插入数据。 –
@RajeshRajaram如果我在onCreate中写它,这将是第一次是正确的。然而,在应用程序的以下启动中,将数据插入到SharedPreferences中的这段代码将再次执行,覆盖之前的值(我将在之前的活动启动中插入)。 –