2019独角兽企业重金招聘Python工程师标准>>>
转载请注明原贴地址:http://blog.csdn.net/feifei454498130/archive/2011/06/03/6524183.aspx
有时用java去控制Javascript,可以控制整个WebView,或者是flash播放器。而用Javascript访问java则可以起一个回调的作用或者其它。
以下是一个简单的例子,大家看一下就明白了。
新建一个index.html文件保存到assets/sample文件夹下
Click here~
跳到setting的Activity~
res/layout/main.xml
以下是java代码
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;
public class FlashActivity extends Activity {private WebView mWebView;private String url = "";/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);initWebView ();}private void initWebView () {url = "file:///android_asset/sample/index.html";mWebView = (WebView)findViewById(R.id.web_01);mWebView.clearCache(true);mWebView.setOnKeyListener(new keyListener());WebSettings wSetting = mWebView.getSettings();// support for JavascriptwSetting.setJavascriptEnabled(true);wSetting.setPluginState(PluginState.ON);// these will access by JavascriptmWebView.addJavascriptInterface(new Object() {public void show(String str) {showToast(str);}public void DumpActivity(String packet, String activityName) {Intent intent = new Intent(Intent.ACTION_MAIN,null);intent.addCategory(Intent.CATEGORY_LAUNCHER);ComponentName cn = new ComponentName(packet, activityName);intent.setComponent(cn);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);startActivity(intent);}}, "myfunction");mWebView.loadUrl(url);}/** show toast, just for test**/private void showToast(String str){Toast.makeText(this, str, Toast.LENGTH_SHORT).show();}class keyListener implements OnKeyListener {public boolean onKey(View v, int keyCode, KeyEvent event) {return onKeyDown(keyCode, event);}}// key listenerpublic boolean onKeyDown(int keyCode, KeyEvent event) {switch(keyCode){case KeyEvent.KEYCODE_MENU:mWebView.loadUrl("Javascript:javaWork('参数是来自java的~')");break;case KeyEvent.KEYCODE_BACK:onDestroy();break;}return super.onKeyDown(keyCode, event);}protected void onResume() {super.onResume();}protected void onPause() {super.onPause();}protected void onDestroy() {super.onDestroy();// kill the processandroid.os.Process.killProcess(android.os.Process.myPid());}
}