[英]How to track if an app is launching for the first time in Android?
我正在开发一个应用程序,该应用程序仅在第一次启动时要执行一些操作。 现在,我考虑使用共享首选项,直到遇到必须在Oncreate本身上对其进行初始化的难题,并且每次启动该应用程序时,共享首选项都会被覆盖。
因此,我正在考虑检查共享首选项上是否存在特定类型变量本身,但我也被卡在那儿。 现在有没有一种我可以忽略的简单方法? 任何帮助将不胜感激。
首次使用此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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.