我正在Flutter中构建一个应用程序,需要在Kotlin中运行一段代码来检查该应用程序是否处于首次运行状态。
我发现这是Java中的代码,但我该如何在Kotlin中完成它呢?
public class MyActivity extends Activity {
SharedPreferences prefs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
实际上很简单:
class MainActivity : Activity() {
private lateinit var sharedPrefs: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedPrefs = getSharedPreferences(packageName, MODE_PRIVATE)
}
override fun onResume() {
super.onResume()
if (sharedPrefs.getBoolean("firstRun", true)){
sharedPrefs.edit().putBoolean("firstrun", false).commit()
}
}
}