我正在开发一个应用程序,其中只有第一个它启动时,我想执行一些操作。现在我考虑使用共享首选项,直到我遇到了我必须初始化Oncreate本身的困境,并且每次启动应用程序时,共享首选项都会被覆盖。如何追踪应用程序首次在Android中启动?
因此,我正在考虑检查共享首选项是否存在特定类型变量本身,但我也卡在那里。现在有一种我可以忽略的简单方法吗?任何帮助将不胜感激。
我正在开发一个应用程序,其中只有第一个它启动时,我想执行一些操作。现在我考虑使用共享首选项,直到我遇到了我必须初始化Oncreate本身的困境,并且每次启动应用程序时,共享首选项都会被覆盖。如何追踪应用程序首次在Android中启动?
因此,我正在考虑检查共享首选项是否存在特定类型变量本身,但我也卡在那里。现在有一种我可以忽略的简单方法吗?任何帮助将不胜感激。
使用此第一次SharePrefrences代码:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("Time", false)) {
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("Time", true);
editor.commit();
}
当第一次启动应用程序时,该共享首选项只运行一次。 这是我的工作。
为此,您需要检查这样的..
/**
* checks for the whether the Application is opened first time or not
*
* @return true if the the Application is opened first time
*/
public boolean isFirstTime() {
File file = getDatabasePath("your file");
if (file.exists()) {
return false;
}
return true;
}
如果该文件存在,它不是第一次了其他明智的第一次..
SharePreferences是一个不错的选择。
public class ShortCutDemoActivity extends Activity {
// Create Preference to check if application is going to be called first
// time.
SharedPreferences appPref;
boolean isFirstTime = true;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get preference value to know that is it first time application is
// being called.
appPref = getSharedPreferences("isFirstTime", 0);
isFirstTime = appPref.getBoolean("isFirstTime", true);
if (isFirstTime) {
// Create explicit intent which will be used to call Our application
// when some one clicked on short cut
Intent shortcutIntent = new Intent(getApplicationContext(),
ShortCutDemoActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent intent = new Intent();
// Create Implicit intent and assign Shortcut Application Name, Icon
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Demo");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(
getApplicationContext(), R.drawable.logo));
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(intent);
// Set preference to inform that we have created shortcut on
// Homescreen
SharedPreferences.Editor editor = appPref.edit();
editor.putBoolean("isFirstTime", false);
editor.commit();
}
}
}
和修改您的AndroidManifest.xml
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
把你的共享偏好的初始化代码在的if else块,检查哪些共享偏好的价值! – Skynet
你是不是想要这个if(!prefs.getBoolean(“firstTime”,false)){//代码第一次运行} –