Ticker

6/recent/ticker-posts

Call JavaScript inside WebView from Android activity, with parameter passed.

The last exercise "Run Android Java code from Webpage" show how to call from WebView JavaScript to Android activity. Here will show how to call in reverse direction: Call JavaScript inside WebView from Android activity, with parameter passed.

Call JavaScript inside WebView from Android activity, with parameter passed.

/assets/mypage.html





My HTML


MyHTML


Hello!









main.xml

android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:id="@+id/msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
android:id="@+id/sendmsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Msg to JavaScript"
/>
android:id="@+id/mybrowser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>


main code:
package com.exercise.AndroidHTML;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {

WebView myBrowser;
EditText Msg;
Button btnSendMsg;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);

final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/mypage.html");

Msg = (EditText)findViewById(R.id.msg);
btnSendMsg = (Button)findViewById(R.id.sendmsg);
btnSendMsg.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String msgToSend = Msg.getText().toString();
myBrowser.loadUrl("javascript:callFromActivity(\""+msgToSend+"\")");

}});

}

public class MyJavaScriptInterface {
Context mContext;

MyJavaScriptInterface(Context c) {
mContext = c;
}

public void showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}

public void openAndroidDialog(){
AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidHTMLActivity.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}

}
}


Download the files.

Updated: Read the updated example with @JavascriptInterface.


إرسال تعليق

0 تعليقات