简体   繁体   English

根据MainActivity执行间隔显示AlertDialog

[英]Show an AlertDialog based on the MainActivity execution intervals

How to display an AlertDialog based on the number of execution of an activity( MainActivity ). 如何根据活动的执行次数( MainActivity )显示AlertDialog For example if MainActivity is opened for 5 times then i need to display an AlertDialog . 例如,如果MainActivity打开5次,那么我需要显示AlertDialog

Dear archana, Please save the varible/flag in SharedPreferences. 亲爱的archana,请在SharedPreferences中保存变量/标志。 Check varialble value (whether 5) then increment on every execution of activity until 5 and save to sharedprefrences and get it from there with every launch of activity. 检查变量值(是否为5),然后在每次执行活动时递增,直到5,并保存到sharedprefrences,并在每次启动活动时从那里获取。 In oncreate method of activity please update the variable with increment+1 and save it and check it in next launch 在oncreate活动方法中,请以增量+ 1更新变量并保存并在下次启动时检查

For more visit: 更多访问:

http://www.tutorialspoint.com/android/android_shared_preferences.htm http://www.tutorialspoint.com/android/android_shared_preferences.htm

Thanks 谢谢

Saving data in Preference: 在首选项中保存数据:

private static void saveCounter(Context context, int value) {
 SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = prefs.edit(); 
 editor.putInt("count", value); 
 editor.commit();
}

Retrieve data from preference: 从首选项中检索数据:

private static int getCounter(Context context) {
 SharedPreferences prefs = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = prefs.edit(); 

 try {
        return prefs.getInt("count", 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

These methods will make your work easy and you just have to pass the incremented value to saveCounter for saving the value and then for getting the value use getCounter 这些方法将使您的工作变得简单,您只需将增加的值传递给saveCounter以保存值,然后获取值使用getCounter

Initialize your counter to 0 and increment it in onCreate() and onResume() methods of your activity. 将计数器初始化为0并在活动的onCreate()onResume()方法中将其递增。 As soon as you increment these values, store these values in Shared Prefrences(as described in above answer). 只要递增这些值,请将这些值存储在共享首选项中(如上面的答案中所述)。 If you have trouble using Shared Preferences, try TinyDB , it is based on Shared Preferences and is much easier to handle. 如果您在使用共享首选项时遇到问题,请尝试使用TinyDB ,它基于共享首选项,并且更容易处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM