Example usage for android.view KeyEvent KEYCODE_BACK

List of usage examples for android.view KeyEvent KEYCODE_BACK

Introduction

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

Prototype

int KEYCODE_BACK

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

Click Source Link

Document

Key code constant: Back key.

Usage

From source file:com.example.android.foodrecipes.app.RecipeDetailsFragment.java

private void saveCurrentRecipeInFavorites() {
    String title = getActivity().getString(R.string.text_please_wait);
    String text = getActivity().getString(R.string.text_saving_in_favorites);

    final ProgressDialog dialog = ProgressDialog.show(getActivity(), title, text);
    final BitmapDrawable bitmapDrawable = (BitmapDrawable) mRecipeImage.getDrawable();

    dialog.show();//from  w w w  .j av a2  s. co m

    final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_EXTERNAL_ID, mRecipe.getExternalId());
            cv.put(COLUMN_TITLE, mRecipe.getTitle());
            cv.put(COLUMN_IMAGE_URL, mRecipe.getImageUrl());
            cv.put(COLUMN_SOCIAL_RANK, mRecipe.getSocialRank());
            cv.put(COLUMN_SOURCE_URL, mRecipe.getSourceUrl());
            cv.put(COLUMN_INGREDIENTS, buildIngredientsString(mRecipe.getIngredients()));

            if (PrefsUtil.shouldSaveRecipeImages(getActivity())) {
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    cv.put(COLUMN_IMAGE_CONTENT, stream.toByteArray());
                }
            }

            getActivity().getContentResolver().insert(CONTENT_URI, cv);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(getActivity(), getActivity().getString(R.string.recipe_saved_in_favorites),
                    Toast.LENGTH_SHORT).show();

            mFavoritesActionButton.setEnabled(false);
        }
    };

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                task.cancel(true);
                dialog.dismiss();
            }
            return true;
        }
    });

    task.execute();
}

From source file:com.app.sample.chatting.activity.chat.ChatActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && box.isShow()) {
        box.hideLayout();/*from   ww  w  . j  ava 2  s  .  c  o m*/
        return true;
    } else {
        return super.onKeyDown(keyCode, event);
    }
}

From source file:com.cleveroad.audiowidget.AudioWidget.java

private boolean hasNavigationBar() {
    boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
    boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
    int id = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
    return !hasBackKey && !hasHomeKey || id > 0 && context.getResources().getBoolean(id);
}

From source file:app.axe.imooc.zxing.app.CaptureActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (source == Source.NATIVE_APP_INTENT) {
            setResult(RESULT_CANCELED);//from   w w  w. jav  a 2  s .  com
            finish();
            return true;
        } else if ((source == Source.NONE || source == Source.ZXING_LINK) && lastResult != null) {
            resetStatusView();
            if (handler != null) {
                handler.sendEmptyMessage(R.id.restart_preview);
            }
            return true;
        }
    } else if (keyCode == KeyEvent.KEYCODE_FOCUS || keyCode == KeyEvent.KEYCODE_CAMERA) {
        // Handle these events so they don't launch the Camera app
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.android.tv.settings.accessories.AddAccessoryActivity.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
        if (mPairingBluetooth && !mDone) {
            cancelBtPairing();/* ww w.j  a va2 s .  c o m*/
        }
    }
    return super.onKeyUp(keyCode, event);
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Get image from photo library.//w  w  w  . j a  v  a2 s.  c o m
 * 
 * @param quality
 *            Compression quality hint (0-100: 0=low quality & high
 *            compression, 100=compress of max quality)
 * @param srcType
 *            The album to get image from.
 * @param returnType
 *            Set the type of image to return.
 */
// TODO: Images selected from SDCARD don't display correctly, but from
// CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {

    final int srcTypeFinal = srcType;
    final int returnTypeFinal = returnType;

    String[] choices = { "Upload a Photo", "Upload a Video" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this.cordova.getActivity());
    builder.setItems(choices, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Log.d(LOG_TAG, "Index #" + which + " chosen.");
            Intent intent = new Intent();
            if (which == 0) {
                // set up photo intent
                WsiCameraLauncher.this.mediaType = PICTURE;
                intent.setType("image/*");
            } else if (which == 1) {
                // set up video intent
                WsiCameraLauncher.this.mediaType = VIDEO;
                intent.setType("video/*");
            } else {
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return;
            }
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            if (WsiCameraLauncher.this.cordova != null) {
                WsiCameraLauncher.this.cordova.startActivityForResult((CordovaPlugin) WsiCameraLauncher.this,
                        Intent.createChooser(intent, new String("Pick")),
                        (srcTypeFinal + 1) * 16 + returnTypeFinal + 1);
            }
        }
    });
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP
                    && !event.isCanceled()) {
                dialog.cancel();
                WsiCameraLauncher.this.failPicture("Selection cancelled.");
                return true;
            }
            return false;
        }
    });
    builder.show();
}

From source file:net.evecom.androidecssp.gps.EventItemizedOverlayActivity.java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK)
        finish();/*from w w w.  j  a v a 2 s.  c om*/
    return super.onKeyUp(keyCode, event);
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
* 
*///from www  .  java  2s.com
@Override
public void onCreate(final Bundle savedInstanceState) {
    //Log.i("MAIN ACTIVITY", "onCreate");
    restoreInstance(savedInstanceState);
    super.onCreate(savedInstanceState);
    NetworkInfoCollector.init(this);
    networkInfoCollector = NetworkInfoCollector.getInstance();

    preferencesUpdate();
    setContentView(R.layout.main_with_navigation_drawer);

    if (VIEW_HIERARCHY_SERVER_ENABLED) {
        ViewServer.get(this).addWindow(this);
    }

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    actionBar.setDisplayUseLogoEnabled(true);

    // initialize the navigation drawer with the main menu list adapter:
    String[] mainTitles = getResources().getStringArray(R.array.navigation_main_titles);
    int[] navIcons = new int[] { R.drawable.ic_action_home, R.drawable.ic_action_history,
            R.drawable.ic_action_map, R.drawable.ic_action_stat, R.drawable.ic_action_help,
            R.drawable.ic_action_about, R.drawable.ic_action_settings, R.drawable.ic_action_about };

    MainMenuListAdapter mainMenuAdapter = new MainMenuListAdapter(this, mainTitles, navIcons);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);
    drawerLayout.setBackgroundResource(R.drawable.ic_drawer);

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer,
            R.string.page_title_title_page, R.string.page_title_title_page) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            //refreshActionBar(null);
            exitAfterDrawerClose = false;
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };

    drawerLayout.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && exitAfterDrawerClose) {
                onBackPressed();
                return true;
            }
            return false;
        }
    });
    drawerLayout.setDrawerListener(drawerToggle);
    drawerList.setAdapter(mainMenuAdapter);
    drawerList.setOnItemClickListener(new OnItemClickListener() {
        final int[] menuIds = new int[] { R.id.action_title_page, R.id.action_history, R.id.action_map,
                R.id.action_stats, R.id.action_help, R.id.action_info, R.id.action_settings,
                R.id.action_netstat, R.id.action_log };

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectMenuItem(menuIds[position]);
            drawerLayout.closeDrawers();
        }
    });

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // Do something against banding effect in gradients
    // Dither flag might mess up on certain devices??
    final Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
    window.addFlags(WindowManager.LayoutParams.FLAG_DITHER);

    // Setzt Default-Werte, wenn noch keine Werte vorhanden
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    final String uuid = ConfigHelper.getUUID(getApplicationContext());

    fm = getFragmentManager();
    final Fragment fragment = fm.findFragmentById(R.id.fragment_content);
    if (!ConfigHelper.isTCAccepted(this)) {
        if (fragment != null && fm.getBackStackEntryCount() >= 1)
            // clear fragment back stack
            fm.popBackStack(fm.getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);

        getActionBar().hide();
        setLockNavigationDrawer(true);

        showTermsCheck();
    } else {
        currentMapOptions.put("highlight", uuid);
        if (fragment == null) {
            if (false) // deactivated for si // ! ConfigHelper.isNDTDecisionMade(this))
            {
                showTermsCheck();
                showNdtCheck();
            } else
                initApp(true);
        }
    }

    geoLocation = new MainGeoLocation(getApplicationContext());

    mNetworkStateChangedFilter = new IntentFilter();
    mNetworkStateChangedFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    mNetworkStateIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                final boolean connected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
                        false);
                final boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

                if (connected) {
                    if (networkInfoCollector != null) {
                        networkInfoCollector.setHasConnectionFromAndroidApi(true);
                    }
                } else {
                    if (networkInfoCollector != null) {
                        networkInfoCollector.setHasConnectionFromAndroidApi(false);
                    }
                }

                Log.i(DEBUG_TAG, "CONNECTED: " + connected + " FAILOVER: " + isFailover);
            }
        }
    };
}

From source file:br.com.anteros.vendas.gui.AnexoCadastroActivity.java

/**
 * Se clicou no boto voltar para sair da Activity.
 * @param keyCode Tecla pressionada/*ww w .  j a  va 2 s.co  m*/
 * @param event Evento
 * @return true se OK
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        /**
         * Pergunta ao usurio se deseja cancelar a edio do anexo.
         */
        new QuestionAlert(this, getResources().getString(R.string.app_name), "Cancelar o anexo?",
                new QuestionAlert.QuestionListener() {
                    public void onPositiveClick() {
                        cancelaEdicaoAnexo();
                    }

                    public void onNegativeClick() {
                    }
                }).show();

        return false;
    }
    return super.onKeyDown(keyCode, event);
}

From source file:br.org.funcate.dynamicforms.FragmentDetailActivity.java

public boolean onKeyDown(int keyCode, KeyEvent event) {
    // force to exit through the exit button, in order to avoid losing info
    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
        return true;
    }/*  w  w w .  j a v a 2  s  .c  om*/
    return super.onKeyDown(keyCode, event);
}