Skip to content

Instantly share code, notes, and snippets.

@Salakar
Last active October 11, 2017 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Salakar/d7b727ffaa5c2a9c04be6710974aecf6 to your computer and use it in GitHub Desktop.
Save Salakar/d7b727ffaa5c2a9c04be6710974aecf6 to your computer and use it in GitHub Desktop.
A rough untested device time watching react native android module.
package io.invertase.firebase;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
@SuppressWarnings("WeakerAccess")
public class RNTimeWatcher extends ReactContextBaseJavaModule implements LifecycleEventListener {
private BroadcastReceiver broadcastReceiver;
private static final String TAG = "RNTimeWatcher";
public RNTimeWatcher(ReactApplicationContext reactContext) {
super(reactContext);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK); // TODO not sure on this one
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
broadcastReceiver = 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)) {
if (getReactApplicationContext() != null) {
WritableMap event = Arguments.createMap();
if (action.equals(Intent.ACTION_TIME_CHANGED)) {
event.putString("type", "time_changed");
}
if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
event.putString("type", "timezone_changed");
}
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("time_watcher", event);
}
}
}
};
Activity activity = getCurrentActivity();
if (activity != null) {
getCurrentActivity().registerReceiver(broadcastReceiver, intentFilter);
}
}
@Override
public String getName() {
return TAG;
}
@Override
public void onHostResume() {
// do nothing
}
@Override
public void onHostPause() {
// do nothing
}
@Override
public void onHostDestroy() {
Activity activity = getCurrentActivity();
if (activity != null) {
getCurrentActivity().unregisterReceiver(broadcastReceiver);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment