Android : How to run code only first lunch of the day
ในแอปปลิเคชันทั่วไปมักมีการเพิ่มคุณสมบัติในการตรวจโน้น ตรวจนี่ หรือมีการแจ้งเตือนให้กับผู้ใช้งาน แต่ถ้าคุณสมบัติเหล่านี้ทำงานทุกครั้งที่ผู้ใช้งานเปิด บางทีอาจทำให้เกิดความรำคาญ หรือทำให้แอปฯเราช้าตลอดเวลาได้
แต่ถ้าเราสั่งให้ทำงานเพียงแค่วันละครั้งที่เปิดใช้งาน จะทำให้ลดความขัดข้องใจกับผู้ใช้งานลงได้เยอะทีเดียว วิธีการมีดังตัวอย่าง ให้เราเพิ่มโค้ดใน Activity ที่ต้องการรันได้
private static final String PREFS_NAME = null; // Try to run only first lunch of the day SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String currentDate = sdf.format(new Date()); if (!sharedPref.getString("LAST_LAUNCH_DATE","nodate") .contains(currentDate)) { // Date not matches. User has already Launched the app once today. ... Run Anything you want for first lunch ... // set Last Lunch date SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("LAST_LAUNCH_DATE", currentDate); editor.commit(); } |
เพียงเท่านี้ code จะทำงานแค่วันละครั้งที่ผู้ใช้เปิดแอปฯขึ้นมาทำงาน