2011-08-18 37 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升级一样添加一个简单的钩子,以避免大量升级错误并提高稳健性(例如,可以忘记这个首选项并清除某些首选项点...) –