android - retain Timer value after I leave and comeback to the fragment -


i have bottom navigation bar , activity hosts 4 fragments. open fragment scratch 1 of fragments has timer feature need retain value unless user explicitly turns off. started savedinstance state takes lot of work maintain time counter in app closed scenario, looking efficient solution. should best strategy ?

here doing call fragments. fragment named f3 1 contains timer.

public class mainactivity() extends appcompatactivity{   bottomnavigation.setontabselectedlistener((position, wasselected) -> {                  if (position == 0) {                     if (!wasselected)                         getfragmentbytag(f1.tag);                 } else if (position == 1) {                     if (!wasselected)                         getfragmentbytag(f2.tag);                 } else if (position == 2) {                     if (!wasselected)                         getfragmentbytag(f3.tag);                 } else if (position == 3) {                     if (!wasselected)                         getfragmentbytag(f4.tag);                 return true;             }     ); } 

method getfragment

private void getfragmentbytag(string tag) {      android.support.v4.app.fragmentmanager fragmentmanager = getsupportfragmentmanager();      backhandledfragment fragment;     if (fragmentmanager.findfragmentbytag(tag) == null) {         switch (tag) {             case f1.tag:                 fragment = new f1();                 break;             case f2.tag:                 fragment = new f2();                 break;             case f3.tag:                 fragment = new f3();                 break;             case f4.tag:                 fragment = new f4();                 break;             default:                 fragment = null;         }     } else {         fragment = (backhandledfragment) getsupportfragmentmanager()                 .findfragmentbytag(tag);     }       new handler().postdelayed(() -> {         getsupportfragmentmanager().popbackstack(null, fragmentmanager.pop_back_stack_inclusive);         fragmenttransaction ft = getsupportfragmentmanager().begintransaction();         ft.setcustomanimations(r.anim.fade_in, r.anim.fade_out, r.anim.fade_in, r.anim.fade_out);         ft.replace(r.id.content_frame, fragment).commitallowingstateloss();     }, 200);  } 

i'm not sure how timer works exactly, looks can use timestamps. when user turns on time, timestamp (with yoda):

datetime timestamp = new datetime();  

and save somewhere in shared prefs/in activity/etc

each time u need show timer user, read timestamp , minus currenttime , start ui timer from/to timestamp (based on logic)


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -