2013-07-18 64 views
-2

我想在安装后第一次运行应用程序后运行代码。再也怎么办呢在第一次运行时运行一次特定的代码Android

以下是代码这里是我怎么想

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    SecurityPrefs.setAutoSavePattern(this, true); 

    String settingsTAG = "AppNameSettings"; 
    SharedPreferences prefs = getSharedPreferences(settingsTAG, 0); 
    boolean run = prefs.getBoolean("run", false); 

    if (run == false) 
    { 
     run = true; 
    Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, 
      this, LockPatternActivity.class); 
    startActivityForResult(intent, REQ_CREATE_PATTERN); 


    } 
    else 
    { Intent intent1 = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN,null,this,LockPatternActivity.class); 

    startActivityForResult(intent1, REQ_ENTER_PATTERN); 
    } 


} 
+0

你在哪里保存布尔值? –

+0

我认为在sharedpreferences –

+0

不,我的意思是你必须把东西放在sharedpreferences之前,你可以得到它,检查vigbyor回答它是正确的 –

回答

2

那么,什么是您所面临的问题?

String settingsTAG = "AppNameSettings"; 
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0); 
boolean run = prefs.getBoolean("run", false); 

您的代码应该运行,如果是第一次在更新共享偏好和储存“运行”真正的工作后。

+0

它不起作用。它只会在每次运行 –

+0

时将其视为假,只有在第一次运行后更新“运行”的值时它才会起作用。 Vibgyor的代码将起作用。去做。 'SharedPreferences.Editor editPrefs = prefs.edit(); editPrefs.putBoolean(“run”,true); editPrefs.commit();' – Rajeev

+0

让我来做hangon :-p –

0

编辑您的代码如下所示,

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     SecurityPrefs.setAutoSavePattern(this, true); 

     String settingsTAG = "AppNameSettings"; 
     SharedPreferences prefs = getSharedPreferences(settingsTAG, 0); 
     boolean run = prefs.getBoolean("run", false); 

     if (run == true) 
     { 

     Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN, null, 
       this, LockPatternActivity.class); 
     startActivityForResult(intent, REQ_CREATE_PATTERN); 
     } 
     else 
     { 
      SharedPreferences.Editor editPrefs = prefs.edit(); 
      editPrefs.putBoolean ("run", true); 
      editPrefs.commit();   
      Intent intent1 = new  Intent(LockPatternActivity.ACTION_COMPARE_PATTERN,null,this,LockPatternActivity.class); 

     startActivityForResult(intent1, REQ_ENTER_PATTERN); 
     } 
    } 

首次运行后,你需要运行的值设置为true在sharedpreference中的其他部分。