0

I want to clear my shared preferance field phonenumber exactly at 12 am in broadcast receiver. How will I do that ? Here is my code ...


    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences prefs = context .getSharedPreferences("connect", Context.MODE_PRIVATE);


        String username = prefs.getString("phonenumber", null ) ;  

    }



}```
  
guru
  • 13
  • 3
  • Are you asking how to clear the preference or a logic for clearing at 12 am ? To clear the preference `preferences.edit().clear().apply()` to clear single object `preferences.edit().putString(key, "").apply()` for 12 am logic you could try alarm manager or JobScheduler – Shahnawaz Ansari Jan 04 '22 at 04:44
  • @ShahnawazAnsari please help me help me to do this ? how can i use alarmmanager or jobscheduler ? – guru Jan 04 '22 at 05:17

1 Answers1

0

Alarm Manager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing.

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

           preferences.edit().putString(key, "").apply()
            }

        }, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call the preferences clear logic 
         }
      }, 0, 10, TimeUnit.MINUTES);

EDit:

You can actually save the install time and then do a calculation to see if a week has elapsed. If it has clear the shared preference

//First time
long installed = context
    .getPackageManager()
    .getPackageInfo(context.getPackag‌​eName(), 0)
    .firstInstallTime;

Ref:More on periodic event handling Get install time and clear shared preference

Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31