如何解决Kotlin:如何检查应用程序是否已经打开过一次?
我正在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()
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。