2011-08-18 38 views
5

我使用共享首選項來存儲我的應用程序啓動的次數。僅在第一次啓動時,我會顯示一條歡迎消息,通知用戶有關該版本中的新功能和更改。更新/卸載時的SharedPreferences行爲

但是,當我專注於重新安裝應用程序或升級應用程序時,我無法刪除先前的共享首選項。當我重新安裝軟件或升級軟件時,我想獲得對話框。

AppLauncher

public class AppLauncher { 
    static long launch_count = 0; 
    private static boolean isLaunch = false; 

    public static void app_launched(Context mContext) { 
     System.out.println("I m in AppLauncher"); 
     SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0); 
     if (prefs.getBoolean("dontshowagain", false)) { 
      return; 
     } 

     SharedPreferences.Editor editor = prefs.edit(); 

     // Increment launch counter 

     launch_count = prefs.getLong("launch_count", 0); 
     editor.putLong("launch_count", launch_count); 

     System.out.println("launch_count=" + launch_count); 
     if (launch_count == 0 || launch_count == 1) { 
      // showLaunchDialog(mContext); 
      isLaunch = true; 
     } 
     if (isLaunch == true) { 
      showLaunchDialog(mContext); 
      isLaunch = false; 
     } 
     editor.commit(); 
    } 

    public static void showLaunchDialog(Context mcontext) { 
     final Dialog dialog = new Dialog(mcontext); 
     dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     dialog.setContentView(R.layout.whatsnew); 

     Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom); 
     System.out.println("inside dialog_started"); 
     dismisButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View arg0) { 
       dialog.dismiss(); 
      } 
     }); 
     dialog.show(); 
    } 
} 
+0

你怎麼樣首先創建sharedPreference .. – ngesh

回答

14

在更新的情況下,您可以使用它來清除共享首選項。

Nikolay是正確的,你可以保存你的應用程序的版本號。並將其與當前版本號進行比較。

爲了獲得當前的版本號電話:

this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode 

有關哪些信息是包中的信息可閱讀有關PackageInfoPackageManager文檔的詳細信息。

+0

感謝您詳細說明:)我認爲這是我需要的;) –

1

如果你不設置dontShowagin你會得到默認爲false。所以你要顯示對話框,並在下一次not.So只是優先值更改爲true,這樣下一個它的工作時間。你也增加了計數器沒有實際增加它。使用前一個+1。

SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0); 
      if (prefs.getBoolean("dontshowagain", false)) { 
       return; 
      } 

      SharedPreferences.Editor editor = prefs.edit(); 

      // Increment launch counter 

      editor.putBoolean("dontShowagain",true); 
      launch_count = prefs.getLong("launch_count", 0)+1; 
      editor.putLong("launch_count", launch_count); 
+0

這不會解決再次展示了應用程序更新後的對話框的問題。 – Janusz

11

而不是保存boolean保存應用程序的版本號。如果當前應用程序的版本號更高(更新),則顯示對話框並更新號碼。

+0

爲什麼我沒有想到它之前:P真棒。非常感謝:) –

+0

雖然解決方案很簡單,但我期望Android SDK能夠像DB升級一樣添加一個簡單的鉤子,以避免大量升級錯誤並提高穩健性(例如,可以忘記這個首選項並清除某些首選項點...) –