async StatusBridge.sendRequest

This commit is contained in:
Roman Volosovskyi
2016-12-29 21:44:57 +02:00
parent 105bb3a524
commit 372e484383
2 changed files with 37 additions and 30 deletions
@@ -3,6 +3,7 @@ package com.github.alinz.reactnativewebviewbridge;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;
import android.app.Activity;
import java.io.IOException;
@@ -12,30 +13,52 @@ import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.StringReader;
import android.util.JsonReader;
import com.facebook.react.uimanager.ThemedReactContext;
class StatusBridge {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static final String URL = "http://localhost:8545";
private WebView webView;
private Context context;
private ThemedReactContext context;
private OkHttpClient client = new OkHttpClient();
public StatusBridge(Context context, WebView webView) {
public StatusBridge(ThemedReactContext context, WebView webView) {
this.context = context;
this.webView = webView;
}
@JavascriptInterface
public String sendRequest(String json) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(URL)
.post(json)
.build();
public void sendRequest(final String callbackId, final String json) {
Thread thread = new Thread() {
@Override
public void run() {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(URL)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
Toast.makeText(context, response.body().string(), Toast.LENGTH_LONG).show();
return response.body().string();
}
try (Response response = client.newCall(request).execute()) {
//Toast.makeText(context, response.body().string(), Toast.LENGTH_LONG).show();
String rpcResponse = response.body().string().trim();
final String script = "httpCallback('" + callbackId + "','" + rpcResponse + "');";
final Activity activity = context.getCurrentActivity();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
webView.evaluateJavascript(script, null);
}
});
} catch (IOException e) {
}
}
};
thread.start();
}
}