Code example for WebView: Displaying web pages

Methods: addJavascriptInterfacegetSettingsloadUrlsetInitialScalesetLayoutParamssetScrollBarStylesetWebViewClient, requestFocusFromTouch, setOnKeyListener

0
	} 
	 
	private void initWebView() 
	{ 
		WebView localWebView = (WebView)this.mainView.findViewById(R.id.wv1);
		WebSettings localWebSettings = localWebView.getSettings();
		localWebSettings.setJavaScriptEnabled(true);
		localWebSettings.setDomStorageEnabled(true);
		localWebSettings.setLightTouchEnabled(false);
		localWebSettings.setDatabaseEnabled(true);
		localWebSettings.setDatabasePath(getApplicationContext().getDir("database", 0).getPath());
//		localWebSettings.setPluginState(PluginState.ON); 
		localWebView.setScrollBarStyle(0);
		localWebView.setOnKeyListener(new View.OnKeyListener()
		{ 
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{ 
				if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_BACK)) {
					return ingameReturnKeyWithView(v);
				} 
				return false; 
			} 
		}); 
		localWebView.setWebViewClient(new myWebClient(this.getAssets()));
		registerJavascriptObject(localWebView);
		localWebView.requestFocusFromTouch();
		DisplayMetrics localDisplayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
		localWebView.setInitialScale((int)(100.0D * Math.min(localDisplayMetrics.widthPixels / 480.0D, localDisplayMetrics.heightPixels / 320.0D)));
	    if (Build.PRODUCT.equals("blaze"))
	        localWebView.setInitialScale((int)(96.0D * Math.min(localDisplayMetrics.widthPixels / 480.0D, localDisplayMetrics.heightPixels / 320.0D)));
		if (Build.VERSION.SDK_INT > 13) {
			localWebView.setLayoutParams(new LinearLayout.LayoutParams(-1, -1));
		} 
//		localWebView.setOverScrollMode(WebView.OVER_SCROLL_IF_CONTENT_SCROLLS);  
		localWebView.loadUrl("file:///android_asset/build/start.html");
	} 
 
	private WebView getGameClientWebView()
	{ 
		WebView localWebView = null;
		if (this.mainView == null) {
			localWebView = (WebView)this.mainView.findViewById(R.id.wv1);
		} else { 
			localWebView = (WebView) this.mainView;
		} 
		return localWebView;
	} 
 
	private void sendNotification(String tickerText, String contentTitle, String contentText) {
		nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
 
		Intent notiIntent = new Intent(BotActivity.this, NotificationMsg.class);
		notiIntent.putExtra("warinfo", contentText);
		 
		PendingIntent intent = PendingIntent.getActivity(BotActivity.this, 0,
				notiIntent, 0);
 
		// Create Notification Object 
		Notification notification =
				new Notification(android.R.drawable.ic_input_add,
						tickerText, System.currentTimeMillis());
		notification.vibrate = new long[] { 100, 100, 200, 200, 300, 300 };
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.setLatestEventInfo(BotActivity.this,
				contentTitle, contentText, intent);
 
		nm.notify(0x219, notification);
	} 
 
	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub 
		menu.add(Menu.NONE, 1, 1, "Add User");
		menu.add(Menu.NONE, 2, 2, "Login");
		menu.add(Menu.NONE, 3, 3, "Log-Out");		
		return super.onCreateOptionsMenu(menu);
	} 
	 
	@Override 
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub 
		switch(item.getItemId()) {
		case 1: 
			Context mContext = BotActivity.this;
			LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
			View layout = layoutInflater.inflate(R.layout.login_dialog, (ViewGroup) findViewById(R.id.layout_root));
			final EditText userIdText = (EditText) layout.findViewById(R.id.user_id);
			final EditText userPwdText = (EditText) layout.findViewById(R.id.user_password);
			 
			AlertDialog.Builder addUserDlg = new AlertDialog.Builder(mContext);
			 
			addUserDlg.setView(layout);
			addUserDlg.setTitle("Add User");
			addUserDlg.setMessage("Input Id/Pwd");
			addUserDlg.setPositiveButton("Add",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,	int which) {
							String userId = userIdText.getText().toString();							
							String userPwd = userPwdText.getText().toString();
							 
							if (userId.length() != 0 && userPwd.length() !=0) {
								SharedPreferences prefUserInfo = getSharedPreferences("pref_userinfo", Activity.MODE_PRIVATE);
								SharedPreferences.Editor editor = prefUserInfo.edit();
								editor.putString(userId, userPwd);
								editor.commit();
							} else { 
								dialog.dismiss();
							} 
							 
						} 
					})						 
				.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						} 
					}); 
 
			addUserDlg.show();
 
			return true; 
		case 2: 
			final SharedPreferences prefUserInfo = getSharedPreferences("pref_userinfo", Activity.MODE_PRIVATE);
			 
			Map<String, ?> items = prefUserInfo.getAll();
			List<String> userIds = new ArrayList<String>();
			for (String id : items.keySet()) {
				userIds.add(id);
			} 
			Collections.sort(userIds);
			 
			final String[] strItems = userIds.toArray(new String[] {});
			 
			AlertDialog selLogIdDlg = new AlertDialog.Builder(this)
				.setIcon( R.drawable.icon )
				.setTitle( "Select ID" ) 
				.setPositiveButton("Login" , new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						WebView localWebView = null;			
						localWebView = getGameClientWebView();			
						String str = localWebView.getTitle();
						 
						if ((str != null) && (str.equalsIgnoreCase("login"))) {
							String userId = strItems[selectedItemId];
							String userPwd = prefUserInfo.getString(userId, "");
							localWebView.loadUrl("javascript:loginFunc(\"" + userId + "\",\"" + userPwd + "\",0);");
						} 
						dialog.dismiss();
					} 
				}) 
				.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,	int which) {							
						SharedPreferences.Editor editor = prefUserInfo.edit();
						editor.remove(strItems[selectedItemId]);
						editor.commit();
					} 
				}) 
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
 
					} 
				}) 
				.setSingleChoiceItems(strItems , -1, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						selectedItemId = which;
					} 
				}) 
				.show();		 
			 
			return true; 
		case 3:  
			WebView localWebView = null;			
			localWebView = getGameClientWebView();
			String str = localWebView.getTitle();
			localWebView.clearCache(true);
			clearApplicationCache(null); 
			android.webkit.CookieManager.getInstance().removeAllCookie();
			localWebView.loadUrl("file:///android_asset/build/start.html");
		} 
		return super.onOptionsItemSelected(item);
	} 
	 
	private void clearApplicationCache(java.io.File dir){
        if(dir==null)
            dir = getCacheDir();
        else; 
        if(dir==null)
            return; 
        else; 
        java.io.File[] children = dir.listFiles();
        try{ 
            for(int i=0;i<children.length;i++)
                if(children[i].isDirectory())
                    clearApplicationCache(children[i]);
                else children[i].delete();
        } 
        catch(Exception e){}
    } 
	 
	public void registerJavascriptObject(WebView paramWebView)
	{ 
		paramWebView.addJavascriptInterface(new Object()
		{ 
			public void exit() 
			{ 
				exitGame(); 
			} 
Stop searching for code, let great code find you!  Add Codota to your java IDE