Example usage for android.view KeyEvent ACTION_DOWN

List of usage examples for android.view KeyEvent ACTION_DOWN

Introduction

In this page you can find the example usage for android.view KeyEvent ACTION_DOWN.

Prototype

int ACTION_DOWN

To view the source code for android.view KeyEvent ACTION_DOWN.

Click Source Link

Document

#getAction value: the key has been pressed down.

Usage

From source file:org.apache.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from   www.jav  a 2s  . c  o m
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    showZoomControls = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean zoom = features.get(ZOOM);
        if (zoom != null) {
            showZoomControls = zoom.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
        if (hardwareBack != null) {
            hadwareBackButton = hardwareBack.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                close.setBackgroundDrawable(closeIcon);
            } else {
                close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(getShowZoomControls());
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.fishstix.dosboxfree.DBGLSurfaceView.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private void processJoystickInput(MotionEvent event, int historyPos) {
    float hatX = 0.0f;
    InputDevice.MotionRange range = event.getDevice().getMotionRange(MotionEvent.AXIS_HAT_X, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            hatX = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_X, historyPos));
        } else {/*  w ww  . ja va2 s. c  om*/
            hatX = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_HAT_X));
        }
    }

    float hatY = 0.0f;
    range = event.getDevice().getMotionRange(MotionEvent.AXIS_HAT_Y, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            hatY = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_Y, historyPos));
        } else {
            hatY = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_HAT_Y));
        }
    }

    float joyX = 0.0f;
    range = event.getDevice().getMotionRange(MotionEvent.AXIS_X, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            joyX = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_X, historyPos));
        } else {
            joyX = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_X));
        }
    }

    float joyY = 0.0f;
    range = event.getDevice().getMotionRange(MotionEvent.AXIS_Y, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            joyY = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_Y, historyPos));
        } else {
            joyY = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_Y));
        }
    }

    float joy2X = 0.0f;
    range = event.getDevice().getMotionRange(MotionEvent.AXIS_Z, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            joy2X = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_Z, historyPos));
        } else {
            joy2X = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_Z));
        }
    }

    float joy2Y = 0.0f;
    range = event.getDevice().getMotionRange(MotionEvent.AXIS_RZ, event.getSource());
    if (range != null) {
        if (historyPos >= 0) {
            joy2Y = InputDeviceState.ProcessAxis(range,
                    event.getHistoricalAxisValue(MotionEvent.AXIS_RZ, historyPos));
        } else {
            joy2Y = InputDeviceState.ProcessAxis(range, event.getAxisValue(MotionEvent.AXIS_RZ));
        }
    }

    if (mAnalogStickPref == 0) {
        mMouseThread.setCoord(
                (int) ((Math.abs(joyX * 32.0f) > DEADZONE) ? (-joyX * 32.0f * mMouseSensitivityX) : 0),
                (int) ((Math.abs(joyY * 32.0f) > DEADZONE) ? (-joyY * 32.0f * mMouseSensitivityY) : 0));
        DosBoxControl.nativeJoystick((int) ((joy2X * 256.0f) + mJoyCenterX),
                (int) ((joy2Y * 256.0f) + mJoyCenterY), ACTION_MOVE, -1);
    } else {
        mMouseThread.setCoord(
                (int) ((Math.abs(joy2X * 32.0f) > DEADZONE) ? (-joy2X * 32.0f * mMouseSensitivityX) : 0),
                (int) ((Math.abs(joy2Y * 32.0f) > DEADZONE) ? (-joy2Y * 32.0f * mMouseSensitivityY) : 0));
        DosBoxControl.nativeJoystick((int) ((joyX * 256.0f) + mJoyCenterX),
                (int) ((joyY * 256.0f) + mJoyCenterY), ACTION_MOVE, -1);
    }

    // Handle all other keyevents
    int value = 0;
    int tKeyCode = MAP_NONE;

    if (hatX < 0) {
        value = customMap.get(KeyEvent.KEYCODE_DPAD_LEFT);
        if (value > 0) {
            // found a valid mapping
            tKeyCode = getMappedKeyCode(value, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
            if (tKeyCode > MAP_NONE) {
                DosBoxControl.sendNativeKey(tKeyCode, true, mModifierCtrl, mModifierAlt, mModifierShift);
            }
        }
        hatXlast = hatX;
    } else if (hatX > 0) {
        value = customMap.get(KeyEvent.KEYCODE_DPAD_RIGHT);
        if (value > 0) {
            // found a valid mapping
            tKeyCode = getMappedKeyCode(value, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT));
            if (tKeyCode > MAP_NONE) {
                DosBoxControl.sendNativeKey(tKeyCode, true, mModifierCtrl, mModifierAlt, mModifierShift);
            }
        }
        hatXlast = hatX;
    } else {
        // released
        if (hatX != hatXlast) {
            if (hatXlast < 0) {
                value = customMap.get(KeyEvent.KEYCODE_DPAD_LEFT);
                if (value > 0) {
                    // found a valid mapping
                    tKeyCode = getMappedKeyCode(value,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT));
                    if (tKeyCode > MAP_NONE) {
                        DosBoxControl.sendNativeKey(tKeyCode, false, mModifierCtrl, mModifierAlt,
                                mModifierShift);
                    }
                }
            } else if (hatXlast > 0) {
                value = customMap.get(KeyEvent.KEYCODE_DPAD_RIGHT);
                if (value > 0) {
                    // found a valid mapping
                    tKeyCode = getMappedKeyCode(value,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT));
                    if (tKeyCode > MAP_NONE) {
                        DosBoxControl.sendNativeKey(tKeyCode, false, mModifierCtrl, mModifierAlt,
                                mModifierShift);
                    }
                }
            }
        }
        hatXlast = hatX;
    }
    if (hatY < 0) {
        value = customMap.get(KeyEvent.KEYCODE_DPAD_UP);
        if (value > 0) {
            // found a valid mapping
            tKeyCode = getMappedKeyCode(value, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP));
            if (tKeyCode > MAP_NONE) {
                DosBoxControl.sendNativeKey(tKeyCode, true, mModifierCtrl, mModifierAlt, mModifierShift);
            }
        }
        hatYlast = hatY;
    } else if (hatY > 0) {
        value = customMap.get(KeyEvent.KEYCODE_DPAD_DOWN);
        if (value > 0) {
            // found a valid mapping
            tKeyCode = getMappedKeyCode(value, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN));
            if (tKeyCode > MAP_NONE) {
                DosBoxControl.sendNativeKey(tKeyCode, true, mModifierCtrl, mModifierAlt, mModifierShift);
            }
        }
        hatYlast = hatY;
    } else {
        // released
        if (hatY != hatYlast) {
            if (hatYlast < 0) {
                value = customMap.get(KeyEvent.KEYCODE_DPAD_UP);
                if (value > 0) {
                    // found a valid mapping
                    tKeyCode = getMappedKeyCode(value,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_UP));
                    if (tKeyCode > MAP_NONE) {
                        DosBoxControl.sendNativeKey(tKeyCode, false, mModifierCtrl, mModifierAlt,
                                mModifierShift);
                    }
                }
            } else if (hatYlast > 0) {
                value = customMap.get(KeyEvent.KEYCODE_DPAD_DOWN);
                if (value > 0) {
                    // found a valid mapping
                    tKeyCode = getMappedKeyCode(value,
                            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_DOWN));
                    if (tKeyCode > MAP_NONE) {
                        DosBoxControl.sendNativeKey(tKeyCode, false, mModifierCtrl, mModifierAlt,
                                mModifierShift);
                    }
                }
            }
        }
        hatYlast = hatY;
    }
}

From source file:com.github.akinaru.rfdroid.activity.BtDevicesActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {

        if (scanningListView.getVisibility() == View.VISIBLE) {
            onBackPressed();/*from w  ww.j a  v  a 2 s . co  m*/
        } else {
            if (currentService.isScanning()) {
                hideProgressBar();
                currentService.stopScan();
            }
            mScanIntervalSeekbar.setVisibility(View.GONE);
            mWindowIntervalSeekbar.setVisibility(View.GONE);
            scanningListView.setVisibility(View.VISIBLE);
            if (deviceNameTv != null)
                deviceNameTv.setVisibility(View.GONE);
        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/* ww w  . ja va2 s. co  m*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.WHITE);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setText(getPostName());
            close.setTextSize(20.0f);
            close.setTextColor(android.graphics.Color.GRAY);
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(backResId);
            closeIcon.setBounds(0, 0, 40, 40);
            close.setPadding(0, 0, 0, 0);
            close.setBackgroundDrawable(null);
            close.setCompoundDrawables(closeIcon, null, null, null);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                //close.setBackgroundDrawable(closeIcon);
            } else {
                //close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            //toolbar.addView(actionButtonContainer);
            //toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.mobiroller.tools.inappbrowser.MobirollerInAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from w ww .j  av a  2s  . c om*/
 */
public String showWebPage(final String url, final HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    showZoomControls = false;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean zoom = features.get(ZOOM);
        if (zoom != null) {
            showZoomControls = zoom.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
        if (hardwareBack != null) {
            hadwareBackButton = hardwareBack.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new MobirollerInAppBrowserDialog(cordova.getActivity(),
                    android.R.style.Theme_Translucent_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setBackgroundColor(Color.TRANSPARENT);
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black!
            toolbar.setBackgroundColor(Color.TRANSPARENT);
            toolbar.setLayoutParams(new RelativeLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                    this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(closeResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                close.setBackgroundDrawable(closeIcon);
            } else {
                close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new MobirollerInAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(showZoomControls);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            //                toolbar.addView(actionButtonContainer);
            //                toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            //Mobiroller Needs
            DisplayMetrics metrics = cordova.getActivity().getResources().getDisplayMetrics();
            Rect windowRect = new Rect();
            webView.getView().getWindowVisibleDisplayFrame(windowRect);

            int bottomGap = 0;
            if (features.containsKey("hasTabs")) {
                if (features.get("hasTabs")) {
                    bottomGap += Math.ceil(44 * metrics.density);
                }
            }
            lp.height = (windowRect.bottom - windowRect.top) - (bottomGap);
            lp.gravity = Gravity.TOP;
            lp.format = PixelFormat.TRANSPARENT;
            close.setAlpha(0);
            //Mobiroller Needs

            dialog.setContentView(main);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.show();
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.msopentech.applicationgateway.EnterpriseBrowserActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    try {//from w w w . j av  a 2s.  com
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);

        String preferredRouter = AuthPreferences.loadPreferredRouter();
        if (preferredRouter != null && !preferredRouter.isEmpty()) {
            CLOUD_CONNECTION_HOST_PREFIX = preferredRouter;
        }

        Boolean useSmartBrowser = AuthPreferences.loadUseSmartBrowser();
        if (useSmartBrowser) {
            CLOUD_BROWSER_URL = CLOUD_CONNECTION_HOST_PREFIX + CLOUD_CONNECTION_HOST_SMARTBROWSER_POSTFIX;
        } else {
            CLOUD_BROWSER_URL = CLOUD_CONNECTION_HOST_PREFIX + CLOUD_CONNECTION_HOST_BROWSER_POSTFIX;
        }

        mWebViewClient = new MyWebViewClient();

        mBackButtonView = (ImageButton) findViewById(R.id.main_back);
        mForwardButtonView = (ImageButton) findViewById(R.id.main_go);
        mAddButtonView = (ImageButton) findViewById(R.id.main_add_tab);
        mStatusButtonView = (ImageButton) findViewById(R.id.main_status);
        mProgressBarView = (ProgressBar) findViewById(R.id.main_progress_bar);
        mReloadButtonView = (ImageButton) findViewById(R.id.main_reload);
        mUrlEditTextView = (AutoCompleteTextView) findViewById(R.id.main_url);

        // The following is present to fix a bug found on devices with hard keyboards,
        // not soft keyboards.  Hard keyboards have physical keys versus a soft
        // keyboard which uses a displayed keyboard.  With hard keyboards and EditText boxes 
        // on activities with TabHosts, entering certain keys on the hard keyboard 
        // causes the focus to shift from an EditText to another item on the activity.
        // This manifested itself when running the browser on an oDriod device and no
        // text could be entered into mUrlEditTextView.  
        //
        // The following work-around appears to solve this problem (found on forums) 
        // without causing any regressions.
        View.OnTouchListener focusHandler = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.requestFocusFromTouch();
                return false;
            }
        };
        mUrlEditTextView.setOnTouchListener(focusHandler);

        mCustomTabHost = new CustomTabHost();

        PersistenceManager.registerObserver(this);

        mAutoCompleteAdapter = new UrlAutoCompleteAdapter(this, android.R.layout.simple_list_item_1,
                PersistenceManager.getAllMergedRecords(), mCustomTabHost);
        mUrlEditTextView.setAdapter(mAutoCompleteAdapter);

        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View view) {
                switch (view.getId()) {
                case R.id.main_go: {
                    if (mActiveWebView.canGoForward())
                        mActiveWebView.goForward();
                    break;
                }
                case R.id.main_back: {
                    if (mActiveWebView.canGoBack())
                        mActiveWebView.goBack();
                    break;
                }
                case R.id.main_reload: {
                    TabInfo tab = mCustomTabHost.getTabInfoForWebView(mActiveWebView);
                    if (tab.isPageLoadingInProgress()) {
                        mActiveWebView.stopLoading();
                    } else {
                        String url = mActiveWebView.getUrl();
                        if (url != null && !mIsSigninRequired) {
                            //The user could have got a new session. 
                            //We can neither clear the current url in WebView, 
                            //nor use its reload() function since the url inside it is "cloudified" using the previous SessionID.
                            //However, we can safely extract it from the WebView, normalize it, and then "cloudify" it with the right SessionID.
                            //This implementation allows us to keep the reload button always enabled during the lifetime of a tab after the first URL has been entered.
                            goToUrl(convertCloudUrlToNormal(url));
                        }
                    }
                    break;
                }
                case R.id.main_add_tab: {
                    mCustomTabHost.createNewTab();
                    break;
                }
                }
            }
        };

        mAddButtonView.setOnClickListener(listener);
        mForwardButtonView.setOnClickListener(listener);
        mBackButtonView.setOnClickListener(listener);
        mReloadButtonView.setOnClickListener(listener);

        mForwardButtonView.setEnabled(false);
        mBackButtonView.setEnabled(false);

        mUrlEditTextView.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    if (mUrlEditTextView.isPopupShowing()) {
                        mUrlEditTextView.dismissDropDown();
                    }

                    String uri = mUrlEditTextView.getText().toString();

                    if (!uri.startsWith(HTTP_TOKEN_ATTRIBUTE) && !uri.startsWith(HTTPS_TOKEN_ATTRIBUTE)) {
                        uri = HTTP_PREFIX_ATTRIBUTE + uri;
                        mUrlEditTextView.setText(uri);
                    }
                    mUserOriginalURI = uri;
                    if (goToUrl(mUserOriginalURI))
                        return true;
                }
                return false;
            }
        });

        mTraits = null;
        showSignIn(null, false);
    } catch (final Exception e) {
        Utility.showAlertDialog(
                EnterpriseBrowserActivity.class.getSimpleName() + ".onCreate(): Failed. " + e.toString(),
                EnterpriseBrowserActivity.this);
    }
}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (AndroidGamepadManager.handleKeyEvent(event)) {
        return true;
    }/*from   w w w  .j a va2s.  c o  m*/

    // Global onKey handler. This is called if the focused UI doesn't
    // handle the key event, and before Gecko swallows the events.
    if (event.getAction() != KeyEvent.ACTION_DOWN) {
        return false;
    }

    if ((event.getSource() & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BUTTON_Y:
            // Toggle/focus the address bar on gamepad-y button.
            if (mBrowserChrome.getVisibility() == View.VISIBLE) {
                if (mDynamicToolbar.isEnabled() && !isHomePagerVisible()) {
                    mDynamicToolbar.setVisible(false, VisibilityTransition.ANIMATE);
                    if (mLayerView != null) {
                        mLayerView.requestFocus();
                    }
                } else {
                    // Just focus the address bar when about:home is visible
                    // or when the dynamic toolbar isn't enabled.
                    mBrowserToolbar.requestFocusFromTouch();
                }
            } else {
                mDynamicToolbar.setVisible(true, VisibilityTransition.ANIMATE);
                mBrowserToolbar.requestFocusFromTouch();
            }
            return true;
        case KeyEvent.KEYCODE_BUTTON_L1:
            // Go back on L1
            Tabs.getInstance().getSelectedTab().doBack();
            return true;
        case KeyEvent.KEYCODE_BUTTON_R1:
            // Go forward on R1
            Tabs.getInstance().getSelectedTab().doForward();
            return true;
        }
    }

    // Check if this was a shortcut. Meta keys exists only on 11+.
    final Tab tab = Tabs.getInstance().getSelectedTab();
    if (Versions.feature11Plus && tab != null && event.isCtrlPressed()) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_LEFT_BRACKET:
            tab.doBack();
            return true;

        case KeyEvent.KEYCODE_RIGHT_BRACKET:
            tab.doForward();
            return true;

        case KeyEvent.KEYCODE_R:
            tab.doReload();
            return true;

        case KeyEvent.KEYCODE_PERIOD:
            tab.doStop();
            return true;

        case KeyEvent.KEYCODE_T:
            addTab();
            return true;

        case KeyEvent.KEYCODE_W:
            Tabs.getInstance().closeTab(tab);
            return true;

        case KeyEvent.KEYCODE_F:
            mFindInPageBar.show();
            return true;
        }
    }

    return false;
}

From source file:com.mplayer_remote.ServerList.java

/**
  * Metoda odpowiedzialna za tworzenie okien dialogowych wywietlanych przez aktywno.
  * @see android.app.Activity#onCreateDialog(int, android.os.Bundle)
  *//* w  w w.  ja v a 2 s  .  co m*/
protected Dialog onCreateDialog(int id, final Bundle retrievedBundle) {

    // przypisanie kontekstu do dialog
    final Context mContext = this; // wane w oficjalnej dokumentacji jest bd
    Dialog dialog = new Dialog(mContext);
    dialog_FIRST_TIME_RUNING = new Dialog(mContext);
    dialog_GIVE_ME_A_APP_PASSWORD = new Dialog(mContext);
    dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE = new Dialog(
            mContext);
    dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST = new Dialog(
            mContext);
    dialog_GIVE_ME_A_SERVER_PASSWORD = new Dialog(mContext);
    dialog_ADD_NEW_SERVER_CRYPTO_ENABLED = new Dialog(mContext);
    dialog_ADD_NEW_SERVER_CRYPTO_DISABLED = new Dialog(mContext);
    dialog_DELETE_SERVER = new Dialog(mContext);
    dialog_CHOSE_SERVER_TO_EDIT = new Dialog(mContext);
    dialog_EDIT_SERVER_CRYPTO_ENABLED = new Dialog(mContext);
    dialog_EDIT_SERVER_CRYPTO_DISABLED = new Dialog(mContext);
    dialog_DO_DELATE = new Dialog(mContext);
    dialog_LICENSE = new Dialog(mContext);

    switch (id) {
    case DIALOG_FIRST_TIME_RUNING:

        //dialog_FIRST_TIME_RUNING.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog_FIRST_TIME_RUNING.setContentView(R.layout.layout_for_dialog_first_time_runing);
        dialog_FIRST_TIME_RUNING.setTitle(R.string.tile_for_dialog_FIRST_TIME_RUNING);
        dialog_FIRST_TIME_RUNING.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();

            }
        });

        if (appPasswordcharArray != null) { //appPasswordcharArray == null on first start for example
            try {
                serverListArrayList = aXMLReaderWriter
                        .decryptFileWithXMLAndParseItToServerList(appPasswordcharArray);

            } catch (WrongPasswordException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        final EditText set_app_passwordEditText = (EditText) dialog_FIRST_TIME_RUNING
                .findViewById(R.id.set_app_passswordEditText);
        set_app_passwordEditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });

        final TextView explanation_set_a_password_for_this_appTextView = (TextView) dialog_FIRST_TIME_RUNING
                .findViewById(R.id.explanation_set_a_password_for_this_app);
        final ColorStateList explanation_set_a_password_for_this_appTextViewColorStateList = explanation_set_a_password_for_this_appTextView
                .getTextColors();
        final CheckBox use_encryption_checkBox = (CheckBox) dialog_FIRST_TIME_RUNING
                .findViewById(R.id.use_encryption_checkBox);
        use_encryption_checkBox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (use_encryption_checkBox.isChecked() == true) {
                    set_app_passwordEditText.setVisibility(View.VISIBLE);
                    explanation_set_a_password_for_this_appTextView.setVisibility(View.VISIBLE);
                    /*
                    //explanation_set_a_password_for_this_appTextView.setTextColor(explanation_set_a_password_for_this_appTextViewColorStateList);
                    set_app_passwordEditText.setClickable(true);
                    set_app_passwordEditText.setFocusable(true);
                    set_app_passwordEditText.setFocusableInTouchMode(true);
                    set_app_passwordEditText.setCursorVisible(true);
                    set_app_passwordEditText.setLongClickable(true);
                    set_app_passwordEditText.setBackgroundResource(android.R.drawable.edit_text);
                    set_app_passwordEditText.setTextColor(android.graphics.Color.BLACK);
                    */
                } else {
                    set_app_passwordEditText.setVisibility(View.INVISIBLE);
                    explanation_set_a_password_for_this_appTextView.setVisibility(View.INVISIBLE);
                    /*
                    //explanation_set_a_password_for_this_appTextView.setTextColor(0);
                    set_app_passwordEditText.setClickable(false);
                    set_app_passwordEditText.setFocusable(false);
                    set_app_passwordEditText.setFocusableInTouchMode(false);
                    set_app_passwordEditText.setCursorVisible(false);
                    set_app_passwordEditText.setLongClickable(false);
                    set_app_passwordEditText.setBackgroundColor(android.graphics.Color.GRAY);
                    set_app_passwordEditText.setTextColor(android.graphics.Color.GRAY);
                    */
                }

            }

        });

        final Button exit_dialog_first_time_runing_button = (Button) dialog_FIRST_TIME_RUNING
                .findViewById(R.id.exit_dialog_first_time_runing_button);
        exit_dialog_first_time_runing_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (set_app_passwordEditText.getText().length() == 0
                        && use_encryption_checkBox.isChecked() == true) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();

                } else {

                    if (use_encryption_checkBox.isChecked() == true) {
                        isCryptoEnabledboolean = true;
                    } else {
                        isCryptoEnabledboolean = false;
                    }

                    SharedPreferences settings_for_APP = getSharedPreferences("settings_for_APP", 0);
                    SharedPreferences.Editor editor = settings_for_APP.edit();
                    editor.putBoolean("is_this_first_run", false);
                    editor.putBoolean("is_crypto_enabled", isCryptoEnabledboolean);
                    // Commit the edits!
                    editor.commit();

                    //a new salt should be created for every new app passwort. Watch a XMLReaderWriter.createKey and SettingsForAPP.
                    File file = mContext.getFileStreamPath("salt");
                    if (file.exists()) {
                        file.delete(); //Usuwanie salt dla poprzedniego hasa aplikacji.
                        Log.v(TAG, "Usuwam stary salt");
                    }

                    if (isCryptoEnabledboolean == true) {
                        appPasswordcharArray = set_app_passwordEditText.getText().toString().toCharArray();
                        aXMLReaderWriter.createEncryptedXMLFileWithServerList(serverListArrayList,
                                appPasswordcharArray);
                    } else {
                        appPasswordcharArray = "default_password".toCharArray();
                        aXMLReaderWriter.createEncryptedXMLFileWithServerList(serverListArrayList,
                                appPasswordcharArray);
                    }
                    if (serverListArrayList != null) {
                        for (int i = 0; i < serverListArrayList.size(); i++) {

                            createConnectButtons(i);

                        }
                    }
                    dismissdialog_FIRST_TIME_RUNING();
                }
            }
        });
        break;
    case DIALOG_GIVE_ME_A_APP_PASSWORD:

        dialog_GIVE_ME_A_APP_PASSWORD.setContentView(R.layout.layout_for_dialog_give_me_a_app_password);
        dialog_GIVE_ME_A_APP_PASSWORD.setTitle(R.string.title_for_dialog_GIVE_ME_A_APP_PASSWORD);
        dialog_GIVE_ME_A_APP_PASSWORD.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();

            }
        });
        final Button check_app_passwordButton = (Button) dialog_GIVE_ME_A_APP_PASSWORD
                .findViewById(R.id.check_app_password_Button);
        check_app_passwordButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText app_password_EditText = (EditText) dialog_GIVE_ME_A_APP_PASSWORD
                        .findViewById(R.id.app_password_EditText);
                if (app_password_EditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else {
                    app_password_EditText.setOnKeyListener(new OnKeyListener() {
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            // If the event is a key-down event on the "enter" button
                            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                // Perform action on key press
                                return true;
                            }
                            return false;
                        }
                    });
                    appPasswordcharArray = (app_password_EditText.getText().toString()).toCharArray();

                    try {
                        serverListArrayList = aXMLReaderWriter
                                .decryptFileWithXMLAndParseItToServerList(appPasswordcharArray);

                        if (serverListArrayList != null) {
                            for (int i = 0; i < serverListArrayList.size(); i++) {

                                createConnectButtons(i);

                            }
                        }
                        final CheckBox remember_app_password_in_sesion_CheckBox = (CheckBox) dialog_GIVE_ME_A_APP_PASSWORD
                                .findViewById(R.id.remember_app_password_in_sesion_CheckBox);
                        if (remember_app_password_in_sesion_CheckBox.isChecked() == true) {
                            rememberAppPasswordInSesionboolean = true;
                            SharedPreferences settings_for_APP = getSharedPreferences("settings_for_APP", 0);
                            SharedPreferences.Editor editor = settings_for_APP.edit();
                            editor.putBoolean("remember_app_password_in_sesion_boolean",
                                    rememberAppPasswordInSesionboolean);
                            // Commit the edits!
                            editor.commit();
                        } else {
                            Arrays.fill(appPasswordcharArray, '0');
                            appPasswordcharArray = null;
                            rememberAppPasswordInSesionboolean = false;
                            SharedPreferences settings_for_APP = getSharedPreferences("settings_for_APP", 0);
                            SharedPreferences.Editor editor = settings_for_APP.edit();
                            editor.putBoolean("remember_app_password_in_sesion_boolean",
                                    rememberAppPasswordInSesionboolean);
                            // Commit the edits!
                            editor.commit();
                        }
                        dismissdialog_GIVE_ME_A_APP_PASSWORD();
                    } catch (WrongPasswordException e) {
                        appPasswordcharArray = null;
                        Toast.makeText(getApplicationContext(), R.string.wrong_app_password_exeption,
                                Toast.LENGTH_SHORT).show();
                        showdialog_GIVE_ME_A_APP_PASSWORD();
                    }

                }
            }
        });

        break;
    //called in dialogs DIALOG_ADD_NEW_SERVER... and DIALOG_EDIT_SERVER.. 
    case DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE:
        dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE.setContentView(
                R.layout.layout_for_dialog__because_remember_app_password_in_sesion_boolean_is_false);
        dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE.setTitle(
                R.string.title_for_dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE);
        Button continue_with_given_app_password_Button = (Button) dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE
                .findViewById(R.id.continue_with_given_app_password_Button);
        continue_with_given_app_password_Button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText app_password_EditText = (EditText) dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE
                        .findViewById(
                                R.id.app_password_EditText_in_layout_for_dialog__because_remember_app_password_in_sesion_boolean_is_false);
                if (app_password_EditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else {
                    app_password_EditText.setOnKeyListener(new OnKeyListener() {
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            // If the event is a key-down event on the "enter" button
                            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                // Perform action on key press
                                return true;
                            }
                            return false;
                        }
                    });
                    Log.v(TAG,
                            "app_password przez odczytaniem z app_password_EditText w: DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE"
                                    + appPasswordcharArray);
                    appPasswordcharArray = (app_password_EditText.getText().toString()).toCharArray();
                    Log.v(TAG,
                            "app_password po odczytaniu z app_password_EditText w: DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE"
                                    + appPasswordcharArray.toString());
                    try {
                        List<Server> test_input_server_list = new ArrayList<Server>();
                        test_input_server_list = aXMLReaderWriter
                                .decryptFileWithXMLAndParseItToServerList(appPasswordcharArray); //catch if password is wrong
                        aXMLReaderWriter.createEncryptedXMLFileWithServerList(serverListArrayList,
                                appPasswordcharArray);
                        //Log.v(TAG,server.getServer_name());
                        //Log.v(TAG,server.getIP_address());
                        //Log.v(TAG,server.getUsername());
                        //Log.v(TAG,new String(server.getPassword())); 

                        //removeDialog(DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                        Arrays.fill(appPasswordcharArray, '0');
                        appPasswordcharArray = null;
                        finish();
                        Intent intent = new Intent(mContext, ServerList.class);
                        startActivity(intent);
                    } catch (WrongPasswordException e) {
                        appPasswordcharArray = null;
                        Toast.makeText(getApplicationContext(), R.string.wrong_app_password_exeption,
                                Toast.LENGTH_SHORT).show();
                        //showDialog(DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                    }
                }
            }
        });
        break;

    case DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST:
        dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST
                .setContentView(
                        R.layout.layout_for_dialog__because_remember_app_password_in_sesion_boolean_is_false);
        dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST
                .setTitle(
                        R.string.title_for_dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE);
        Button continue_with_given_app_password_Button2 = (Button) dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST
                .findViewById(R.id.continue_with_given_app_password_Button);
        continue_with_given_app_password_Button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText app_password_EditText = (EditText) dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST
                        .findViewById(
                                R.id.app_password_EditText_in_layout_for_dialog__because_remember_app_password_in_sesion_boolean_is_false);
                if (app_password_EditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else {
                    app_password_EditText.setOnKeyListener(new OnKeyListener() {
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            // If the event is a key-down event on the "enter" button
                            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                // Perform action on key press
                                return true;
                            }
                            return false;
                        }
                    });
                    Log.v(TAG,
                            "app_password przez odczytaniem z app_password_EditText w: DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST"
                                    + appPasswordcharArray);
                    appPasswordcharArray = (app_password_EditText.getText().toString()).toCharArray();
                    Log.v(TAG,
                            "app_password po odczytaniu z app_password_EditText w: DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST"
                                    + appPasswordcharArray.toString());
                    try {
                        List<Server> test_input_server_list = new ArrayList<Server>();
                        test_input_server_list = aXMLReaderWriter
                                .decryptFileWithXMLAndParseItToServerList(appPasswordcharArray); //catch if password is wrong
                        aXMLReaderWriter.createEncryptedXMLFileWithServerList(serverListArrayList,
                                appPasswordcharArray);

                        final Intent intent_start_settings_activity_for_ServerList = new Intent(
                                getApplicationContext(), SettingsForAPP.class);
                        intent_start_settings_activity_for_ServerList.putExtra("app_password",
                                appPasswordcharArray);
                        startActivity(intent_start_settings_activity_for_ServerList);
                        finish();

                        //removeDialog(DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                        Arrays.fill(appPasswordcharArray, '0');
                        appPasswordcharArray = null;

                    } catch (WrongPasswordException e) {
                        appPasswordcharArray = null;
                        Toast.makeText(getApplicationContext(), R.string.wrong_app_password_exeption,
                                Toast.LENGTH_SHORT).show();
                        //showDialog(DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                    }
                }
            }
        });
        break;

    case DIALOG_GIVE_ME_A_SERVER_PASSWORD:

        dialog_GIVE_ME_A_SERVER_PASSWORD.setContentView(R.layout.layout_for_dialog_give_me_a_server_password);
        dialog_GIVE_ME_A_SERVER_PASSWORD.setTitle(R.string.title_for_dialog_GIVE_ME_A_SERVER_PASSWORD);

        final Button connect_to_server_button_in_DIALOG_GIVE_ME_A_SERVER_PASSWORD = (Button) dialog_GIVE_ME_A_SERVER_PASSWORD
                .findViewById(R.id.connect_to_server_Button_in_dialog_give_me_a_server_password);
        connect_to_server_button_in_DIALOG_GIVE_ME_A_SERVER_PASSWORD.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText server_password_EditText = (EditText) dialog_GIVE_ME_A_SERVER_PASSWORD
                        .findViewById(R.id.server_password_EditText);
                if (server_password_EditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else {
                    server_password_EditText.setOnKeyListener(new OnKeyListener() {
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            // If the event is a key-down event on the "enter" button
                            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                                // Perform action on key press
                                return true;
                            }
                            return false;
                        }
                    });
                    char[] server_password = (server_password_EditText.getText().toString().toCharArray());
                    Log.v(TAG, "server_password przeczytane z server_password_EditText: "
                            + new String(server_password));
                    int id_of_clicked_button = retrievedBundle.getInt("clicked_button");
                    Log.v(TAG, "id of clicked button: " + id_of_clicked_button);
                    Intent intent_start_ConnectToServer = new Intent(getApplicationContext(),
                            ConnectToServer.class);
                    final Intent intent_start_ConnectAndPlayService = new Intent(getApplicationContext(),
                            ConnectAndPlayService.class);
                    intent_start_ConnectAndPlayService.putExtra("server_name",
                            serverListArrayList.get(id_of_clicked_button).getServerName());
                    intent_start_ConnectAndPlayService.putExtra("IP_address",
                            serverListArrayList.get(id_of_clicked_button).getIPAddress());
                    intent_start_ConnectAndPlayService.putExtra("username",
                            serverListArrayList.get(id_of_clicked_button).getUsername());
                    intent_start_ConnectAndPlayService.putExtra("password", server_password);
                    startService(intent_start_ConnectAndPlayService);

                    connectingToSshProgressDialog = ProgressDialog.show(ServerList.this, "",
                            getString(R.string.text_for_progressdialog_from_connecttoserver), true, true);

                    removeDialog(DIALOG_GIVE_ME_A_SERVER_PASSWORD);
                    Arrays.fill(server_password, '0');
                }
            }
        });
        break;
    case DIALOG_ADD_NEW_SERVER_CRYPTO_ENABLED:
        dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                .setContentView(R.layout.layout_for_dialog_add_new_server_crypto_enabled);
        dialog_ADD_NEW_SERVER_CRYPTO_ENABLED.setTitle(R.string.title_for_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED);

        //Buttons
        final Button saveButton_in_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED = (Button) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.saveButton_crypto_enabled);
        final Button cancelButton_in_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED = (Button) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.cancelButton_crypto_enabled);
        saveButton_in_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText server_nameEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                        .findViewById(R.id.server_nameEditText_crypto_enabled);
                server_nameEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });
                EditText IP_addressEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                        .findViewById(R.id.IP_addressEditText_crypto_enabled);
                IP_addressEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });
                EditText usernameEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                        .findViewById(R.id.usernameEditText_crypto_enabled);
                usernameEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });
                EditText passwordEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_ENABLED
                        .findViewById(R.id.passwordEditText_crypto_enabled);
                passwordEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });

                Log.v(TAG, "obecna ilosc zapisanych serverow wynosi: " + serverListArrayList.size());

                if (server_nameEditText.getText().length() == 0 || IP_addressEditText.getText().length() == 0
                        || usernameEditText.getText().length() == 0
                        || passwordEditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                    //}else if(!validateIP(IP_addressEditText.getText().toString())){
                    //Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address, Toast.LENGTH_LONG).show();
                    //}else if (server_nameEditText.getText().toString().matches(".*\\s+.*") || IP_addressEditText.getText().toString().matches(".*\\s+.*") || usernameEditText.getText().toString().matches(".*\\s+.*") || passwordEditText.getText().toString().matches(".*\\s+.*")){   
                    //Toast.makeText(getApplicationContext(), R.string.text_for_toast_fields_should_not_contain_a_whitespace_character, Toast.LENGTH_LONG).show();
                } else if (!(isIPv4OrIPv6(IP_addressEditText.getText().toString()))) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address,
                            Toast.LENGTH_LONG).show();

                } else {
                    Server server = new Server();
                    server.setServerName(server_nameEditText.getText().toString());
                    server.setIPAddress(IP_addressEditText.getText().toString());
                    server.setUsername(usernameEditText.getText().toString());
                    server.setPassword(passwordEditText.getText().toString().toCharArray());

                    serverListArrayList.add(server);
                    if (appPasswordcharArray == null) {
                        showDialog(
                                DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                        //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);   //sprawdzi czy bdzie dziaa bez tego e niby w onPause() wystarczy
                        removeDialog(DIALOG_ADD_NEW_SERVER_CRYPTO_ENABLED);

                    } else {
                        Log.v(TAG, server.getServerName());
                        Log.v(TAG, server.getIPAddress());
                        Log.v(TAG, server.getUsername());
                        Log.v(TAG, new String(server.getPassword()));

                        removeDialog(DIALOG_ADD_NEW_SERVER_CRYPTO_ENABLED);
                        finish();
                        Intent intent = new Intent(mContext, ServerList.class);
                        startActivity(intent);
                    }
                }

            }

        });

        cancelButton_in_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeDialog(DIALOG_ADD_NEW_SERVER_CRYPTO_ENABLED);
            }

        });
        dialog_ADD_NEW_SERVER_CRYPTO_ENABLED.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub

            }
        });
        break;
    case DIALOG_ADD_NEW_SERVER_CRYPTO_DISABLED:
        dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                .setContentView(R.layout.layout_for_dialog_add_new_server_crypto_disabled);
        dialog_ADD_NEW_SERVER_CRYPTO_DISABLED.setTitle(R.string.title_for_dialog_ADD_NEW_SERVER_CRYPTO_ENABLED); //title is the same

        //Buttons
        final Button saveButton_in_dialog_ADD_NEW_SERVER_CRYPTO_DISABLED = (Button) dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.saveButton_crypto_disabled);
        final Button cancelButton_in_dialog_ADD_NEW_SERVER_CRYPTO_DISABLED = (Button) dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.cancelButton_crypto_disabled);
        saveButton_in_dialog_ADD_NEW_SERVER_CRYPTO_DISABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText server_nameEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                        .findViewById(R.id.server_nameEditText_crypto_disabled);
                server_nameEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });
                EditText IP_addressEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                        .findViewById(R.id.IP_addressEditText_crypto_disabled);
                IP_addressEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });
                EditText usernameEditText = (EditText) dialog_ADD_NEW_SERVER_CRYPTO_DISABLED
                        .findViewById(R.id.usernameEditText_crypto_disabled);
                usernameEditText.setOnKeyListener(new OnKeyListener() {
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // If the event is a key-down event on the "enter" button
                        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                            // Perform action on key press
                            return true;
                        }
                        return false;
                    }
                });

                Log.v(TAG, "obecna ilosc zapisanych serverow wynosi: " + serverListArrayList.size());
                if (server_nameEditText.getText().length() == 0 || IP_addressEditText.getText().length() == 0
                        || usernameEditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                    //}else if(!validateIP(IP_addressEditText.getText().toString())){
                    //Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address, Toast.LENGTH_LONG).show();
                    //}else if (server_nameEditText.getText().toString().matches(".*\\s+.*") || IP_addressEditText.getText().toString().matches(".*\\s+.*") || usernameEditText.getText().toString().matches(".*\\s+.*") || passwordEditText.getText().toString().matches(".*\\s+.*")){   
                    //Toast.makeText(getApplicationContext(), R.string.text_for_toast_fields_should_not_contain_a_whitespace_character, Toast.LENGTH_LONG).show();
                } else if (!(isIPv4OrIPv6(IP_addressEditText.getText().toString()))) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address,
                            Toast.LENGTH_LONG).show();

                } else {
                    Server server = new Server();

                    server.setServerName(server_nameEditText.getText().toString());
                    server.setIPAddress(IP_addressEditText.getText().toString());
                    server.setUsername(usernameEditText.getText().toString());
                    server.setPassword("a_blank_password".toCharArray());

                    serverListArrayList.add(server);

                    //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);

                    Log.v(TAG, server.getServerName());
                    Log.v(TAG, server.getIPAddress());
                    Log.v(TAG, server.getUsername());
                    Log.v(TAG, new String(server.getPassword()));

                    removeDialog(DIALOG_ADD_NEW_SERVER_CRYPTO_DISABLED);

                    finish();
                    Intent intent = new Intent(mContext, ServerList.class);
                    startActivity(intent);
                }
            }
        });

        cancelButton_in_dialog_ADD_NEW_SERVER_CRYPTO_DISABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeDialog(DIALOG_ADD_NEW_SERVER_CRYPTO_DISABLED);
            }

        });

        break;

    case DIALOG_CHOOSE_SERVER_TO_EDIT:
        Log.v(TAG, "Wszedem do onCreate DIALOG_CHOOSE_SERVER_TO_EDIT");
        itemsFor_DIALOG_EDIT_SERVER = new CharSequence[serverListArrayList.size()];
        for (int i = 0; i < serverListArrayList.size(); i++) {

            itemsFor_DIALOG_EDIT_SERVER[i] = serverListArrayList.get(i).getServerName();
            Log.v(TAG, "Server_name :" + itemsFor_DIALOG_EDIT_SERVER[i]);
        }
        AlertDialog.Builder builder_for_DIALOG_CHOSE_SERVER_TO_EDIT = new AlertDialog.Builder(this);
        builder_for_DIALOG_CHOSE_SERVER_TO_EDIT.setTitle(R.string.title_for_dialog_CHOSE_SERVER_TO_EDIT);
        builder_for_DIALOG_CHOSE_SERVER_TO_EDIT.setItems(itemsFor_DIALOG_EDIT_SERVER,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog_CHOSE_SERVER_TO_EDIT, int item) {
                        //Toast.makeText(getApplicationContext(), items_for_DIALOG_EDIT_SERVER[item], Toast.LENGTH_SHORT).show();
                        serverToEditint = item;
                        Log.v(TAG, "server do edycji ma numer: " + item);
                        removeDialog(DIALOG_CHOOSE_SERVER_TO_EDIT);
                        if (isCryptoEnabledboolean == true) {
                            showDialog(DIALOG_EDIT_SERVER_CRYPTO_ENABLED);
                        } else {
                            showDialog(DIALOG_EDIT_SERVER_CRYPTO_DISABLED);
                        }
                    }
                });
        dialog_CHOSE_SERVER_TO_EDIT = builder_for_DIALOG_CHOSE_SERVER_TO_EDIT.create();

        break;
    case DIALOG_EDIT_SERVER_CRYPTO_ENABLED:

        dialog_EDIT_SERVER_CRYPTO_ENABLED.setContentView(R.layout.layout_for_dialog_edit_server_crypto_enabled);
        dialog_EDIT_SERVER_CRYPTO_ENABLED.setTitle(R.string.title_for_dialog_EDIT_SERVER_CRYPTO_ENABLED);

        //Buttons
        final Button saveButton_from_DIALOG_EDIT_SERVER = (Button) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.saveButton_in_dialog_edit_server_crypto_enabled);
        final Button cancelButton_from_DIALOG_EDIT_SERVER = (Button) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.cancelButton_in_dialog_edit_server_crypto_enabled);

        final EditText server_nameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED = (EditText) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.server_name_in_dialog_edit_server_EditText_crypto_enabled_from_edit_server);
        server_nameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED
                .setText(serverListArrayList.get(serverToEditint).getServerName());
        server_nameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });
        final EditText IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED = (EditText) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.IP_address_in_dialog_EditText_crypto_enabled_from_edit_server);
        IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED
                .setText(serverListArrayList.get(serverToEditint).getIPAddress());
        IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });
        final EditText usernameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED = (EditText) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.username_in_dialog_edit_server_EditText_crypto_enabled_from_edit_server);
        usernameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED
                .setText(serverListArrayList.get(serverToEditint).getUsername());
        usernameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });

        final EditText passwordEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED = (EditText) dialog_EDIT_SERVER_CRYPTO_ENABLED
                .findViewById(R.id.password_in_dialog_edit_server_EditText_crypto_enabled_from_edit_server);
        passwordEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED
                .setText(new String(serverListArrayList.get(serverToEditint).getPassword()));
        passwordEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });

        saveButton_from_DIALOG_EDIT_SERVER.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Log.v(TAG, "obecna ilosc zapisanych serverow wynosi: " + serverListArrayList.size());
                if (server_nameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().length() == 0
                        || IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().length() == 0
                        || usernameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().length() == 0
                        || passwordEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else if (!(isIPv4OrIPv6(
                        IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().toString()))) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address,
                            Toast.LENGTH_LONG).show();

                } else {
                    Server server = new Server();

                    server.setServerName(
                            server_nameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().toString());
                    server.setIPAddress(
                            IP_addressEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().toString());
                    server.setUsername(
                            usernameEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText().toString());
                    server.setPassword(passwordEditText_in_dialog_EDIT_SERVER_CRYPTO_ENABLED.getText()
                            .toString().toCharArray()); //server_nameEditText.getText().toString() to nazwa pliku

                    serverListArrayList.set(serverToEditint, server);
                    if (appPasswordcharArray == null) {
                        showDialog(
                                DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                        //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);   //sprawdzi czy bdzie dziaa bez tego e niby w onPause() wystarczy
                        removeDialog(DIALOG_EDIT_SERVER_CRYPTO_ENABLED);

                    } else {
                        Log.v(TAG, server.getServerName());
                        Log.v(TAG, server.getIPAddress());
                        Log.v(TAG, server.getUsername());
                        Log.v(TAG, new String(server.getPassword()));

                        removeDialog(DIALOG_EDIT_SERVER_CRYPTO_ENABLED);
                        finish();
                        Intent intent = new Intent(mContext, ServerList.class);
                        startActivity(intent);
                    }
                }
            }

        });

        cancelButton_from_DIALOG_EDIT_SERVER.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeDialog(DIALOG_EDIT_SERVER_CRYPTO_ENABLED);
            }

        });
        dialog_EDIT_SERVER_CRYPTO_ENABLED.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                // TODO Auto-generated method stub

            }
        });
        break;

    case DIALOG_EDIT_SERVER_CRYPTO_DISABLED:

        dialog_EDIT_SERVER_CRYPTO_DISABLED
                .setContentView(R.layout.layout_for_dialog_edit_server_crypto_disabled);
        dialog_EDIT_SERVER_CRYPTO_DISABLED.setTitle(R.string.title_for_dialog_EDIT_SERVER_CRYPTO_ENABLED);

        //Buttons
        final Button saveButton_in_dialog_EDIT_SERVER_CRYPTO_DISABLED = (Button) dialog_EDIT_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.saveButton_in_dialog_edit_server_crypto_disabled);
        final Button cancelButton_in_dialog_EDIT_SERVER_CRYPTO_DISABLED = (Button) dialog_EDIT_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.cancelButton_in_dialog_edit_server_crypto_disabled);

        final EditText server_nameEditText = (EditText) dialog_EDIT_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.server_name_in_dialog_edit_server_EditText_crypto_disabled_from_edit_server);
        server_nameEditText.setText(serverListArrayList.get(serverToEditint).getServerName());
        server_nameEditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });
        final EditText IP_addressEditText = (EditText) dialog_EDIT_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.IP_address_in_dialog_edit_server_EditText_crypto_disabled_from_edit_server);
        IP_addressEditText.setText(serverListArrayList.get(serverToEditint).getIPAddress());
        IP_addressEditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });
        final EditText usernameEditText = (EditText) dialog_EDIT_SERVER_CRYPTO_DISABLED
                .findViewById(R.id.username_in_dialog_edit_server_EditText_crypto_disabled_from_edit_server);
        usernameEditText.setText(serverListArrayList.get(serverToEditint).getUsername());
        usernameEditText.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    return true;
                }
                return false;
            }
        });

        saveButton_in_dialog_EDIT_SERVER_CRYPTO_DISABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Log.v(TAG, "obecna ilosc zapisanych serverow wynosi: " + serverListArrayList.size());
                if (server_nameEditText.getText().length() == 0 || IP_addressEditText.getText().length() == 0
                        || usernameEditText.getText().length() == 0) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_fill_up_the_empty_spaces,
                            Toast.LENGTH_LONG).show();
                } else if (!(isIPv4OrIPv6(IP_addressEditText.getText().toString()))) {
                    Toast.makeText(getApplicationContext(), R.string.text_for_toast_correct_IP_address,
                            Toast.LENGTH_LONG).show();

                } else {
                    Server server = new Server();

                    server.setServerName(server_nameEditText.getText().toString());
                    server.setIPAddress(IP_addressEditText.getText().toString());
                    server.setUsername(usernameEditText.getText().toString());
                    server.setPassword("a_blank_password".toCharArray());

                    serverListArrayList.set(serverToEditint, server);
                    //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);

                    Log.v(TAG, server.getServerName());
                    Log.v(TAG, server.getIPAddress());
                    Log.v(TAG, server.getUsername());
                    Log.v(TAG, new String(server.getPassword()));

                    removeDialog(DIALOG_EDIT_SERVER_CRYPTO_DISABLED);
                    finish();
                    Intent intent = new Intent(mContext, ServerList.class);
                    startActivity(intent);
                }
            }

        });

        cancelButton_in_dialog_EDIT_SERVER_CRYPTO_DISABLED.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                removeDialog(DIALOG_EDIT_SERVER_CRYPTO_DISABLED);
            }

        });

        break;

    case DIALOG_DELETE_SERVER:
        Log.v(TAG, "Wszedem do onCreate DIALOG_DELETE_SERVER");
        itemsFor_DIALOG_DELETE_SERVER = new CharSequence[serverListArrayList.size()];
        for (int i = 0; i < serverListArrayList.size(); i++) {

            itemsFor_DIALOG_DELETE_SERVER[i] = serverListArrayList.get(i).getServerName();
            Log.v(TAG, "Server_name :" + itemsFor_DIALOG_DELETE_SERVER[i]);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.title_for_dialog_DELETE_SERVER);
        builder.setItems(itemsFor_DIALOG_DELETE_SERVER, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog_DELETE_SERVER, int item) {

                serverToDelete = item;
                showDialog(DIALOG_DO_DELATE);
                /*
                 serverListArrayList.remove(item);
                 if (appPasswordcharArray == null){
                showDialog(DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);   //sprawdzi czy bdzie dziaa bez tego e niby w onPause() wystarczy
                            
                }else{   
                                  
                 finish();
                  Intent intent = new Intent(mContext, ServerList.class);
                    startActivity(intent);
                }
                */
            }
        });

        dialog_DELETE_SERVER = builder.create();

        break;

    case DIALOG_DO_DELATE:
        Log.v(TAG, "Wszedem do onCreate DIALOG_DO_DELATE");
        AlertDialog.Builder builderDIALOG_DO_DELATE = new AlertDialog.Builder(mContext);
        builderDIALOG_DO_DELATE.setTitle(getResources().getString(R.string.title_for_dialog_DO_DELETE));
        builderDIALOG_DO_DELATE.setMessage(getResources().getString(R.string.message_in_dialog_DO_DELATE) + " "
                + itemsFor_DIALOG_DELETE_SERVER[serverToDelete] + "?");
        // Add the buttons
        builderDIALOG_DO_DELATE.setPositiveButton(R.string.text_for_do_delete_button,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked OK button
                        serverListArrayList.remove(serverToDelete);
                        if (appPasswordcharArray == null) {
                            showDialog(
                                    DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE);
                            //a_XMLReaderWrriter.create_encrypted_XMLFile_with_server_list(server_list, app_password);   //sprawdzi czy bdzie dziaa bez tego e niby w onPause() wystarczy
                            removeDialog(DIALOG_DO_DELATE);
                        } else {

                            finish();
                            Intent intent = new Intent(mContext, ServerList.class);
                            startActivity(intent);
                            removeDialog(DIALOG_DO_DELATE);
                        }

                    }
                });
        builderDIALOG_DO_DELATE.setNegativeButton(R.string.text_for_cancel_button,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                        removeDialog(DIALOG_DO_DELATE);
                    }
                });
        // Set other dialog properties

        // Create the AlertDialog
        dialog_DO_DELATE = builderDIALOG_DO_DELATE.create();

        break;

    case DIALOG_LICENSE:
        // EULA title
        String title = getResources().getString(R.string.app_name);

        // EULA text
        String message = getResources().getString(R.string.Licences_text);

        AlertDialog.Builder builderDIALOG_LICENSE = new AlertDialog.Builder(mContext).setTitle(title)
                .setMessage(message)
                .setPositiveButton(R.string.text_for_cancel_button, new Dialog.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        dialogInterface.dismiss();

                    }
                });

        // Create the AlertDialog
        dialog_LICENSE = builderDIALOG_LICENSE.create();

        break;

    default:
        dialog = null;
    }
    if (id == DIALOG_FIRST_TIME_RUNING) {
        dialog = dialog_FIRST_TIME_RUNING;
    }
    if (id == DIALOG_GIVE_ME_A_APP_PASSWORD) {
        dialog = dialog_GIVE_ME_A_APP_PASSWORD;
    }
    if (id == DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE) {
        dialog = dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOILEAN_IS_FALSE;
    }
    if (id == DIALOG_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST) {
        dialog = dialog_GIVE_ME_A_APP_PASSWORD_BECAUSE_REMEMBER_APP_PASSWORD_IN_SESION_BOOLEAN_IS_FALSE_AND_I_NEED_IT_TO_START_SETTINGSFORSERVERLIST;
    }
    if (id == DIALOG_GIVE_ME_A_SERVER_PASSWORD) {
        dialog = dialog_GIVE_ME_A_SERVER_PASSWORD;
    }
    if (id == DIALOG_ADD_NEW_SERVER_CRYPTO_ENABLED) {
        dialog = dialog_ADD_NEW_SERVER_CRYPTO_ENABLED;
    }
    if (id == DIALOG_ADD_NEW_SERVER_CRYPTO_DISABLED) {
        dialog = dialog_ADD_NEW_SERVER_CRYPTO_DISABLED;
    }
    if (id == DIALOG_DELETE_SERVER) {
        dialog = dialog_DELETE_SERVER;
    }
    if (id == DIALOG_DO_DELATE) {
        dialog = dialog_DO_DELATE;
    }
    if (id == DIALOG_CHOOSE_SERVER_TO_EDIT) {
        dialog = dialog_CHOSE_SERVER_TO_EDIT;
    }
    if (id == DIALOG_EDIT_SERVER_CRYPTO_ENABLED) {
        dialog = dialog_EDIT_SERVER_CRYPTO_ENABLED;
    }
    if (id == DIALOG_EDIT_SERVER_CRYPTO_DISABLED) {
        dialog = dialog_EDIT_SERVER_CRYPTO_DISABLED;
    }
    if (id == DIALOG_LICENSE) {
        dialog = dialog_LICENSE;
    }

    return dialog;
}

From source file:paulscode.android.mupen64plusae.game.GameFragment.java

/**
 * Handle view onKey callbacks/*from   w  ww  .  ja v a 2s .co m*/
 * @param view If view is NULL then this keycode will not be handled by the key provider. This is to avoid
 *             the situation where user maps the menu key to the menu command.
 * @param keyCode key code
 * @param event key event
 * @return True if handled
 */
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
    final boolean keyDown = event.getAction() == KeyEvent.ACTION_DOWN;

    boolean handled = false;

    // Attempt to reconnect any disconnected devices
    mGamePrefs.playerMap.reconnectDevice(AbstractProvider.getHardwareId(event));

    if (!mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        // If PeripheralControllers exist and handle the event,
        // they return true. Else they return false, signaling
        // Android to handle the event (menu button, vol keys).
        if (mKeyProvider != null && view != null) {
            handled = mKeyProvider.onKey(view, keyCode, event);

            //Don't use built in keys in the device to hide the touch controls
            if (handled && keyCode != KeyEvent.KEYCODE_MENU && keyCode != KeyEvent.KEYCODE_BACK
                    && keyCode != KeyEvent.KEYCODE_VOLUME_UP && keyCode != KeyEvent.KEYCODE_VOLUME_DOWN
                    && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE && mGlobalPrefs.touchscreenAutoHideEnabled) {
                mOverlay.onTouchControlsHide();
            }
        }
    }

    if (!handled) {
        if (keyDown && keyCode == KeyEvent.KEYCODE_MENU) {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawer(GravityCompat.START);
                mOverlay.requestFocus();
            } else {
                mCoreFragment.pauseEmulator();
                mDrawerLayout.openDrawer(GravityCompat.START);
                mDrawerOpenState = true;
                mGameSidebar.requestFocus();
                mGameSidebar.smoothScrollToPosition(0);
            }
            return true;
        } else if (keyDown && keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawer(GravityCompat.START);
                mOverlay.requestFocus();
            } else {
                //We are using the slide gesture for the menu, so the back key can be used to exit
                if (mGlobalPrefs.inGameMenuIsSwipGesture) {
                    mWaitingOnConfirmation = true;
                    mCoreFragment.exit();
                }
                //Else the back key bring up the in-game menu
                else {
                    mCoreFragment.pauseEmulator();
                    mDrawerLayout.openDrawer(GravityCompat.START);
                    mDrawerOpenState = true;
                    mGameSidebar.requestFocus();
                    mGameSidebar.smoothScrollToPosition(0);
                }
            }
            return true;
        }
    }

    return handled;
}

From source file:me.spadival.podmode.PodModeService.java

public void broadcastMediaButtons(int keyCode, String app) {
    long eventtime = SystemClock.uptimeMillis();

    Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, keyCode, 0);
    downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
    if (app != null)
        downIntent.setPackage(app);/*from www .  j a  va  2  s  .  c o m*/

    sendOrderedBroadcast(downIntent, null);

    eventtime = SystemClock.uptimeMillis();

    Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
    KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, keyCode, 0);
    upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
    if (app != null)
        upIntent.setPackage(app);

    sendOrderedBroadcast(upIntent, null);

}