Example usage for android.content.pm PackageManager FEATURE_CAMERA

List of usage examples for android.content.pm PackageManager FEATURE_CAMERA

Introduction

In this page you can find the example usage for android.content.pm PackageManager FEATURE_CAMERA.

Prototype

String FEATURE_CAMERA

To view the source code for android.content.pm PackageManager FEATURE_CAMERA.

Click Source Link

Document

Feature for #getSystemAvailableFeatures and #hasSystemFeature : The device has a camera facing away from the screen.

Usage

From source file:com.psu.capstonew17.pdxaslapp.CreateCardActivity.java

@Override
public void onClick(View view) {
    switch (view.getId()) {
    //user wants to record a video for the new card
    case R.id.buttonRecordVideo:
        //check perms, if we don't have then then request them
        if (this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
                && PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA)) {
            dispatchTakeVideoIntent();//from w w  w  .  j a v a  2  s. c  o  m
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA },
                    REQ_CAMERA_PERMS);
        }
        break;

    //user wants to use a video from the gallery. check for external storage perms.
    //if we don't have them, then request them.
    case R.id.buttonFromGallery:
        dispatchGalleryIntent();
        break;

    //user is finished creating this card.
    case R.id.button_submit:
        videoLabel = editText.getText().toString().trim();
        //make sure that the video imported successfully
        //and that the length of the answer is in valid range
        if (!videoLabelCheck() || video == null) {
            Toast.makeText(this, R.string.import_video_error, Toast.LENGTH_SHORT).show();

        } else {
            CardManager cardManager = ExternalCardManager.getInstance(this);

            try {
                //video and label look good, create the card.
                Card card = cardManager.buildCard(video, videoLabel);

                //add the card to all of the selected decks.
                for (int i = 0; i < listRows.size(); i++) {
                    ListRow curr = listRows.get(i);
                    if (curr.isChecked) {
                        Deck slctdDeck = deckList.get(i);
                        List<Card> cards = slctdDeck.getCards();
                        cards.add(card);
                        slctdDeck.commit();
                    }
                }
                finish();

                //cards can't have the same video!
            } catch (ObjectAlreadyExistsException e) {
                Toast.makeText(this, R.string.card_already_exists, Toast.LENGTH_SHORT).show();
            }
        }
        break;
    }
}

From source file:com.grokkingandroid.sampleapp.samples.data.contentprovider.lentitems.LentItemFormFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_detail_form_fragment, menu);
    if (mItemId == -1) {
        menu.removeItem(R.id.menu_delete);
    }/*from w  ww.j  a v a  2 s  .c o m*/
    if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
            || !Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        menu.removeItem(R.id.menu_photo);
    }
}

From source file:com.platform.middlewares.plugins.CameraPlugin.java

@Override
public boolean handle(String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) {

    // GET /_camera/take_picture
    ///*from  w w w . ja v a2 s .  c o  m*/
    // Optionally pass ?overlay=<id> (see overlay ids below) to show an overlay
    // in picture taking mode
    //
    // Status codes:
    //   - 200: Successful image capture
    //   - 204: User canceled image picker
    //   - 404: Camera is not available on this device
    //   - 423: Multiple concurrent take_picture requests. Only one take_picture request may be in flight at once.
    //

    if (target.startsWith("/_camera/take_picture")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());

            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }

        if (globalBaseRequest != null) {
            Log.e(TAG, "handle: already taking a picture: " + target + " " + baseRequest.getMethod());

            return BRHTTPHelper.handleError(423, null, baseRequest, response);
        }

        PackageManager pm = app.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e(TAG, "handle: no camera available: ");
            return BRHTTPHelper.handleError(402, null, baseRequest, response);
        }
        if (ContextCompat.checkSelfPermission(app,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(app, Manifest.permission.CAMERA)) {
                Log.e(TAG, "handle: no camera access, showing instructions");
                ((BreadWalletApp) app.getApplication()).showCustomToast(app,
                        app.getString(R.string.allow_camera_access), MainActivity.screenParametersPoint.y / 2,
                        Toast.LENGTH_LONG, 0);
            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(app, new String[] { Manifest.permission.CAMERA },
                        BRConstants.CAMERA_REQUEST_GLIDERA_ID);
            }
        } else {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(app.getPackageManager()) != null) {
                app.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }

            continuation = ContinuationSupport.getContinuation(request);
            continuation.suspend(response);
            globalBaseRequest = baseRequest;
        }

        return true;
    } else if (target.startsWith("/_camera/picture/")) {
        Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
        final MainActivity app = MainActivity.app;
        if (app == null) {
            Log.e(TAG, "handle: context is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "context is null", baseRequest, response);
        }
        String id = target.replace("/_camera/picture/", "");
        byte[] pictureBytes = readPictureForId(app, id);
        if (pictureBytes == null) {
            Log.e(TAG, "handle: WARNING pictureBytes is null: " + target + " " + baseRequest.getMethod());
            return BRHTTPHelper.handleError(500, "pictureBytes is null", baseRequest, response);
        }
        byte[] imgBytes = pictureBytes;
        String b64opt = request.getParameter("base64");
        String contentType = "image/jpeg";
        if (b64opt != null && !b64opt.isEmpty()) {
            contentType = "text/plain";
            String b64 = "data:image/jpeg;base64," + Base64.encodeToString(pictureBytes, Base64.NO_WRAP);
            try {
                imgBytes = b64.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return BRHTTPHelper.handleError(500, null, baseRequest, response);
            }
        }
        return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, contentType);
    } else
        return false;
}

From source file:org.cyanogenmod.theme.chooser.WallpaperAndIconPreviewFragment.java

public static ComponentName[] getIconComponents(Context context) {

    if (sIconComponents == null || sIconComponents.length == 0) {
        sIconComponents = new ComponentName[] { COMPONENT_DIALER, COMPONENT_MESSAGING, COMPONENT_CAMERA,
                COMPONENT_BROWSER };/*from  w w  w  . j a v a 2 s.com*/

        PackageManager pm = context.getPackageManager();

        // if device does not have telephony replace dialer and mms
        if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
            sIconComponents[0] = COMPONENT_CALENDAR;
            sIconComponents[1] = COMPONENT_GALERY;
        }

        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            sIconComponents[2] = COMPONENT_SETTINGS;
        } else {
            // decide on which camera icon to use
            try {
                if (pm.getPackageInfo(CAMERA_NEXT_PACKAGE, 0) != null) {
                    sIconComponents[2] = COMPONENT_CAMERANEXT;
                }
            } catch (NameNotFoundException e) {
                // default to COMPONENT_CAMERA
            }
        }

    }

    return sIconComponents;
}

From source file:es.ugr.swad.swadroid.modules.rollcall.UsersActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_items_pulltorefresh);

    refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container_list);
    emptyUsersTextView = (TextView) findViewById(R.id.list_item_title);
    lvUsers = (ListView) findViewById(R.id.list_pulltorefresh);

    lvUsers.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override//from  w w w . jav  a2  s.c o  m
        public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {

            /*boolean enable = true;
            if ((lvUsers != null) && (lvUsers.getChildCount() > 0)) {
                    
            // check if the first item of the list is visible
            boolean firstItemVisible = lvUsers.getFirstVisiblePosition() == 0;
            // check if the top of the first item is visible
            boolean topOfFirstItemVisible = lvUsers.getChildAt(0).getTop() == 0;
            // enabling or disabling the refresh layout
            enable = firstItemVisible && topOfFirstItemVisible;
            }*/
            boolean enable = (lvUsers != null) && (lvUsers.getChildCount() == 0);
            refreshLayout.setEnabled(enable);
        }
    });

    refreshLayout.setOnRefreshListener(this);
    setAppearance();

    getSupportActionBar().setSubtitle(Courses.getSelectedCourseShortName());
    getSupportActionBar().setIcon(R.drawable.roll_call);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    eventCode = this.getIntent().getIntExtra("attendanceEventCode", 0);
    hasRearCam = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}

From source file:com.intel.xdk.camera.Camera.java

public synchronized void takePicture(final int quality, final String saveToLibYN, final String picType) {
    //saveToLibYN is not used because the camera activity always saves to gallery

    PackageManager pm = activity.getPackageManager();
    if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false) {
        fireJSEvent("camera.picture.add", false, null,
                new String[] { String.format("ev.error='device has no camera';") });
    }/*from w  w  w .j a v  a2s.  c  om*/

    if (busy) {
        cameraBusy();
    }
    this.busy = true;

    File outputFile = new File(Environment.getExternalStorageDirectory(), "test." + picType);

    //put required info in shared prefs
    SharedPreferences.Editor prefsEditor = activity.getSharedPreferences(cameraPrefsKey, 0).edit();
    prefsEditor.putString(cameraPrefsFileName, outputFile.getAbsolutePath());
    prefsEditor.putBoolean(cameraPrefsIsPNG, "png".equalsIgnoreCase(picType));
    prefsEditor.putInt(cameraPrefsQuality, quality);
    prefsEditor.commit();

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputFile));

    //cordova.setActivityResultCallback(this);
    // TODO: figure this out
    cordova.startActivityForResult(this, intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    //activity.setLaunchedChildActivity(true);
    //activity.startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}

From source file:com.feathercoin.wallet.feathercoin.ui.SendingAddressesFragment.java

@SuppressLint("InlinedApi")
@Override//from w w  w . jav  a 2s  . c o  m
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
    inflater.inflate(R.menu.sending_addresses_fragment_options, menu);

    final PackageManager pm = activity.getPackageManager();
    menu.findItem(R.id.sending_addresses_options_scan)
            .setVisible(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
                    || pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT));

    super.onCreateOptionsMenu(menu, inflater);
}

From source file:u.ready_wisc.MenuActivity.java

@Override
public void onClick(View v) {
    //TODO fix action bar or disable completely
    if ((v.getId() == (R.id.prepareButton)) || (v.getId() == (R.id.prepareMenuButton))) {
        Intent i = new Intent(MenuActivity.this, Prep_Main.class);
        startActivity(i);// www  .ja v a  2  s.c o  m
    } else if (v.getId() == (R.id.reportDamageButton) || v.getId() == (R.id.emergencyMenuButton)) {
        Intent i = new Intent(MenuActivity.this, Emergency.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.disasterResourcesButton) || v.getId() == (R.id.disasterMenuButton)) {
        Intent i = new Intent(MenuActivity.this, ResourcesActivity.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.typeDisasterButton)) {
        Intent i = new Intent(MenuActivity.this, DisastersType.class);
        MenuActivity.this.startActivity(i);
    } else if (v.getId() == (R.id.SOSMenubutton)) {
        if (!sosTone) {

            //sets device volume to maximum
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

            //begins looping tone
            mp.setLooping(true);
            sosTone = true;
            mp.start();
        }

    } else if (v.getId() == (R.id.FlashlightMenuButton)) {
        //check to see if device has a camera with flash
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {

            Log.e("err", "Device has no camera!");
            //Return from the method, do nothing after this code block
            return;
        }
        // if camera has flash toggle on and off
        else {
            // boolean to check status of camera flash
            if (!isFlashOn) {

                //if flash is off, toggle boolean to on and turn on flash
                isFlashOn = true;
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(parameters);
                camera.startPreview();

            } else {

                //if flash is on turn boolean to false and turn off flash
                isFlashOn = false;
                camera.stopPreview();
                camera.release();
                camera = null;

            }
        }
    } else {

        //stops looping sound
        Log.d("Sound test", "Stopping sound");
        mp.setLooping(false);
        mp.pause();
        sosTone = false;
    }
}

From source file:cc.mintcoin.wallet.ui.SendingAddressesFragment.java

@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
    inflater.inflate(R.menu.sending_addresses_fragment_options, menu);

    final PackageManager pm = activity.getPackageManager();
    menu.findItem(R.id.sending_addresses_options_scan)
            .setVisible(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
                    || pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT));

    super.onCreateOptionsMenu(menu, inflater);
}

From source file:com.mobicage.rogerthat.plugins.messaging.widgets.PhotoUploadWidget.java

@Override
public void initializeWidget() {
    mImagePreview = (ImageView) findViewById(R.id.image_preview);
    mSourceButton = (Button) findViewById(R.id.select_picture);
    mSourceButton.setText(R.string.get_picture);
    mPhotoSelected = false;/* w ww .  j av a2 s .c o  m*/

    mRatio = (String) mWidgetMap.get("ratio");
    mQuality = (String) mWidgetMap.get("quality");

    mSourceButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final SafeRunnable runnableContinue = new SafeRunnable() {
                @Override
                protected void safeRun() throws Exception {
                    getPicture();
                }
            };

            final SafeRunnable runnableCheckStorage = new SafeRunnable() {
                @Override
                protected void safeRun() throws Exception {
                    if (mActivity.askPermissionIfNeeded(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            ServiceMessageDetailActivity.PERMISSION_REQUEST_PHOTO_UPLOAD_WIDGET,
                            runnableContinue, mActivity.showMandatoryPermissionPopup(mActivity,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE)))
                        return;
                    runnableContinue.run();
                }
            };

            if (TRUE.equals(mWidgetMap.get("camera"))) {
                if (mActivity.askPermissionIfNeeded(Manifest.permission.CAMERA,
                        ServiceMessageDetailActivity.PERMISSION_REQUEST_PHOTO_UPLOAD_WIDGET,
                        runnableCheckStorage,
                        mActivity.showMandatoryPermissionPopup(mActivity, Manifest.permission.CAMERA)))
                    return;
            }

            runnableCheckStorage.run();
        }

        private void getPicture() {
            File image;
            try {
                image = getTmpUploadPhotoLocation();
            } catch (IOException e) {
                L.d(e.getMessage());
                UIUtils.showLongToast(getContext(), e.getMessage());
                return;
            }
            mUriSavedImage = Uri.fromFile(image);

            Intent cameraIntent = null;
            boolean hasCamera = mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
            boolean hasCameraPermission = mActivity.getMainService().isPermitted(Manifest.permission.CAMERA);
            if (hasCamera && hasCameraPermission) {
                cameraIntent = ActivityUtils.buildTakePictureIntent(mActivity, mUriSavedImage, Facing.BACK);
            }

            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUriSavedImage);
            galleryIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            galleryIntent.setType("image/*");

            final Intent chooserIntent;
            if (TRUE.equals(mWidgetMap.get("gallery")) && TRUE.equals(mWidgetMap.get("camera"))) {
                chooserIntent = Intent.createChooser(galleryIntent,
                        mActivity.getString(R.string.select_source));
                if (cameraIntent != null) {
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { cameraIntent });
                }

                mActivity.startActivityForResult(chooserIntent, PICK_IMAGE);
            } else if (TRUE.equals(mWidgetMap.get("gallery"))) {
                chooserIntent = Intent.createChooser(galleryIntent,
                        mActivity.getString(R.string.select_source));
                mActivity.startActivityForResult(chooserIntent, PICK_IMAGE);
            } else if (TRUE.equals(mWidgetMap.get("camera"))) {
                if (cameraIntent != null) {
                    mActivity.startActivityForResult(cameraIntent, PICK_IMAGE);
                } else if (!hasCamera) {
                    UIUtils.showDialog(mActivity, R.string.no_camera_available_title,
                            R.string.no_camera_available);
                } else if (!hasCameraPermission) {
                    String title = mActivity.getString(R.string.need_camera_permission_title);
                    String message = mActivity.getString(R.string.need_camera_permission);
                    SafeDialogClick onPositiveClick = new SafeDialogClick() {
                        @Override
                        public void safeOnClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
                            intent.setData(uri);
                            mActivity.startActivity(intent);
                        }
                    };
                    UIUtils.showDialog(mActivity, title, message, R.string.go_to_app_settings, onPositiveClick,
                            R.string.cancel, null);
                }
            }
        }
    });
}