2014-01-17 64 views
1

我正在開發一個應用程序,其中只有第一個它啓動時,我想執行一些操作。現在我考慮使用共享首選項,直到我遇到了我必須初始化Oncreate本身的困境,並且每次啓動應用程序時,共享首選項都會被覆蓋。如何追蹤應用程序首次在Android中啓動?

因此,我正在考慮檢查共享首選項是否存在特定類型變量本身,但我也卡在那裏。現在有一種我可以忽略的簡單方法嗎?任何幫助將不勝感激。

+0

把你的共享偏好的初始化代碼在的if else塊,檢查哪些共享偏好的價值! – Skynet

+0

你是不是想要這個if(!prefs.getBoolean(「firstTime」,false)){//代碼第一次運行} –

回答

5

使用此第一次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(); 
     } 

當第一次啓動應用程序時,該共享首選項只運行一次。 這是我的工作。

1

爲此,您需要檢查這樣的..

/** 
* 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; 
} 

如果該文件存在,它不是第一次了其他明智的第一次..

+0

這是一個非常不錯的方式! – Skynet

+0

還有一件事要添加,如果文件不存在則每創建一個新的代碼,每次都返回true。 – Hulk

0

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" /> 
相關問題