2016-03-25 9 views
2

アクティビティが作成されるたびに、特定のOnCreate()メソッドが(アプリケーションセッションごとに)呼び出されるのは初めてです。 Androidでこれを行う方法はありますか?最初にコードを実行するOnCreateのみ

答えて

1

static変数を使用する。

static boolean checkFirstTime; 
2

使用sharedpreferenceは...の値がtrueに設定されている場合、各実行チェックで初めて...に優先して値をtrueに設定し...とcoditionに基づく実施例についてコード

を実行します。

SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE); 
       if (!preferences.getBoolean("isFirstTime", false)) { 
    //your code goes here 
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE); 
        SharedPreferences.Editor editor = pref.edit(); 
        editor.putBoolean("isFirstTime", true); 
        editor.commit(); 
} 
+0

はしかし、その後、あなたはいくつかの点でバックfalseに設定する必要があるか、それはあまりにも、各アプリの再起動で –

+0

本当だろうが、あなたがあなたの記事で言及したように...あなたはそれを一度実行したいです... 。 –

+0

アプリケーションごとのセッション –

2

あなたの活動内で使用静的変数を

private static boolean DpisrunOnce=false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_run_once); 
    if (DpisrunOnce){ 
     Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show(); 
//is already run not run again 
    }else{ 
//not run do yor work here 
     Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show(); 
     DpisrunOnce =true; 
    } 
} 
11

protected void onCreate(Bundle savedInstanceState)あなたが必要なすべてを持っている以下のように。

savedInstanceState == nullの場合は初めてです。

したがって、静的変数を追加する必要はありません。

+0

これを試してみました。何らかの理由でsavedInstanceStateが常にnullなので、うまくいけばタイムコードが常にトリガされる –

関連する問題