2017-01-11 3 views
0

Я не знаю, был ли задан этот вопрос, но я не мог его найти. Я хочу, чтобы диалоговое окно с предупреждением показывалось каждые 10 или более раз, когда приложение запускается.Как показывать диалоговое окно предупреждения каждые 10 запусков?

AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this); 
a_builder.setMessage("Please take time and rate our application") 
.setCancelable(false) 
.setPositiveButton("Yes",new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
        Uri uri = Uri.parse("market://details?id=" + getApplicationContext().getPackageName()); 
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); 

        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | 
          Intent.FLAG_ACTIVITY_NEW_DOCUMENT | 
          Intent.FLAG_ACTIVITY_MULTIPLE_TASK); 
        try { 
         startActivity(goToMarket); 
        } catch (ActivityNotFoundException e) { 
         startActivity(new Intent(Intent.ACTION_VIEW, 
         Uri.parse("http://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName()))); 
        } 

       } 
      }).setNegativeButton("Not Now",new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }) ; 
    AlertDialog alert = a_builder.create(); 
    alert.setTitle("Rate Us !"); 
    alert.show(); 
+1

вы можете использовать sharedPreferences для хранения счетчика и проверить значение на каждом запуске приложения – Roljhon

+0

магазин ИНТ числа запуска где-нибудь, а и приращение и проверить его каждый запуск –

ответ

1

Вы можете сохранить целочисленное значение в общем предпочтении, чтобы подсчитывать, сколько раз ваше приложение было запущено.
Вы можете увеличить значение в методе запуска OnCreate() активности запуска или в любом другом действии, которое является точкой входа в ваше приложение (например, извещения).
Вы должны сбросить значение после отображения диалогового окна каждый раз.
Вот небольшой фрагмент кода -

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 
int appLaunchCount = pref.getInt("appLaunchCount",-1); 
    if(appLaunchCount==10){ 
     // code to show dialog 
     // reset 
     appLaunchCount=0; 
    } else { 
     // increment count 
     appLaunchCount = appLaunchCount+1; 
    } 
    SharedPreferences.Editor editor = pref.edit(); 
    editor.putInt("appLaunchCount", appLaunchCount); 
    editor.apply(); 
+0

Выше ответ должен работать. –

+0

да, это действительно сработало, спасибо – Vladimir

+0

Рад мог помочь! :) –

5

Задайте общиеПредложения и увеличивайте счетчик каждый раз на значение, хранящееся в нем. Когда значения достигнут счетчика, просто покажите предупреждение и сбросьте sharedpreferences.

+0

SharedPreferences sharedPreferences; int count; sharedPreferences = getPreferences (0); int launchCount = sharedPreferences.getInt ("numRun", 0); launchCount ++; sharedPreferences.edit(). PutInt ("numRun", launchCount) .commit(); if (lanuchCount% 10 == 0) { // сделать что-то } – Vladimir

+0

Должен ли я сделать так, чтобы это было? – Vladimir

+0

почти правильный. –

1
 int count=0; 
int prefcount; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      count++; 
      SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(this); 
      SharedPreferences.Editor edit=pref.edit(); 
      edit.putInt("Count",count); 
      edit.commit(); 
      prefcount=pref.getInt("Count",-1); 
      if(prefcount>10){ 
       //show dialog 
      } 


     } 
} 
Hope this will help you. 
+0

Мой друг, это не сработает, потому что он отобразит диалог через 10 раз и при каждом запуске – Vladimir

+0

Я отредактировал код. Пройдите его. –

0

Вы можете хранить открытые счета в SharedPreferences

добавить счетчик на OnCreate деятельности.

restoredCount ++ 
editor1.putInt("name", restoredCount); 
editor1.commit(); 

// Получает значение счетчика

SharedPreferences prefs = getSharedPreferences("user_count", MODE_PRIVATE); 
SharedPreferences.Editor editor1 = getSharedPreferences("user_count", MODE_PRIVATE).edit(); 
int restoredCount = prefs.getInt("name", 0); 



if (restoredCount == 10) { 
      editor1.putInt("name", 0); 
      editor1.commit(); 

      // Here Show Alert Dialog. 

     } 

Я надеюсь, что этот пример поможет вам.

Смежные вопросы