JSThread.java 1.67 KB
Newer Older
Travis Nuttall's avatar
Travis Nuttall committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
package com.reactlibrary;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.util.Random;

public class JSThread {
    private int id;

    private String jsSlugname;
    private ReactApplicationContext reactContext;

    public JSThread(String jsSlugname) {
        this.id = Math.abs(new Random().nextInt());
        this.jsSlugname = jsSlugname;
    }

    public int getThreadId() {
        return this.id;
    }

    public String getName() {
        return jsSlugname;
    }

    public void runFromContext(ReactApplicationContext context, ReactContextBuilder reactContextBuilder) throws Exception {
        if (reactContext != null) {
            return;
        }

        reactContext = reactContextBuilder.build();

        ThreadSelfModule threadSelfModule = reactContext.getNativeModule(ThreadSelfModule.class);
        threadSelfModule.initialize(id, context);
    }

    public void postMessage(String message) {
        if (reactContext == null) {
            return;
        }

        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("ThreadMessage", message);
    }

    public void onHostResume() {
        if (reactContext == null) {
            return;
        }

        reactContext.onHostResume(null);
    }

    public void onHostPause() {
        if (reactContext == null) {
            return;
        }

        reactContext.onHostPause();
    }

    public void terminate() {
        if (reactContext == null) {
            return;
        }

        reactContext.onHostPause();
        reactContext.destroy();
        reactContext = null;
    }
72
}