Friday, February 22, 2019

Detect user change setting system time

Some app like calendar use system time and date, when user go to Setting change date or time, we need to update app.
We use Broadcast to listen this event.
Declare variables.
static IntentFilter s_intentFilter = new IntentFilter();
     static {
     s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
          s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
          s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
     }
Copy this function in to above last close bracket.
final BroadcastReceiver ti = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
               final String action = intent.getAction();

               if (action.equals(Intent.ACTION_TIME_CHANGED)
                          || action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
          // Update here.
          }
     }
};
Copy to below setContentView();
registerReceiver(ti, s_intentFilter);
Add this line to destroy when exit class.
@Override
     protected void onDestroy() {
          unregisterReceiver(ti);
          super.onDestroy();

     }

No comments:

Post a Comment