0
android studio에서 webview를 만들고 webiview에 textarea 안에 안드로이드 게시물 요청 응답을 배치하려고합니다. 게시물 요청이 올바르게 작동하고 서버에서 데이터를 받지만 내 webview 내부의 JavaScript 함수는 textarea를 채우기 위해 호출되지 않습니다. 전문가가 내 코드를보고 해결 방법을 보여줄 수 있습니까? 미리 감사드립니다. 웹뷰 내부javascript 함수에 Android 게시물 요청 응답을 전달하는 방법은 무엇입니까?
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView= (WebView) findViewById(R.id.activity_main_webview);
mWebView.loadUrl("file:///android_asset/index.html");
mWebView.getSettings().setJavaScriptEnabled(true);
// Force links to open in the WebViewinstead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}
@Override
protected void onResume()
{
super.onResume();
new PostClass().execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
final TextView outputView = (TextView) findViewById(R.id.postOutput);
try {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://myownapi.com/api").openConnection();
myURLConnection.setReadTimeout(60000);
myURLConnection.setConnectTimeout(60000);
myURLConnection.setRequestMethod("POST");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setRequestProperty("API_KEY", "12345_ABC_MNO_12345678_123ABC");
myURLConnection.setRequestProperty("Connection", "Keep-Alive");
myURLConnection.addRequestProperty("Content-length", "");
OutputStream os = myURLConnection.getOutputStream();
os.close();
myURLConnection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
StringBuffer sb = new StringBuffer();
System.out.println(sb);
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
outputView.setText(sb.toString());
//outputView.setText("finished");
mWebView.loadUrl("javascript:MyFunction(" + sb.toString() + ")");
//mWebView.loadUrl("javascript:MyFunction()");
} catch (Exception e) {
}
return null;
}
}
}
html 코드 :이
<html>
<head>
<script>
function MyFunction(myVar)
{
//var myVar = 'test data';
var myTextArea = document.getElementById('myArea');
myTextArea.innerHTML += myVar;
};
</script>
</head>
<body>
<br>
<br>
<textarea id="myArea" rows="30" cols="40"></textarea>
</body>
답장을 보내 주셔서 감사합니다. 시도했지만 아무 것도 텍스트 영역에 배치되지 않았습니다. 나는 심지어 mWebView.loadUrl을 시도했다 ("javascript : MyFunction()"); 자바 스크립트에서 myVar =에 대한 기본값을 사용하고 텍스트 영역에 아무것도 배치하지 마십시오! onCreate 내부에 webview를 배치하는 것이 문제인 것 같습니까? – user1788736