Example usage for android.provider MediaStore ACTION_IMAGE_CAPTURE

List of usage examples for android.provider MediaStore ACTION_IMAGE_CAPTURE

Introduction

In this page you can find the example usage for android.provider MediaStore ACTION_IMAGE_CAPTURE.

Prototype

String ACTION_IMAGE_CAPTURE

To view the source code for android.provider MediaStore ACTION_IMAGE_CAPTURE.

Click Source Link

Document

Standard Intent action that can be sent to have the camera application capture an image and return it.

Usage

From source file:org.opendatakit.survey.activities.MediaCaptureImageActivity.java

@Override
protected void onResume() {
    super.onResume();

    if (afterResult) {
        // this occurs if we re-orient the phone during the save-recording
        // action
        returnResult();/*from   w w  w  .j  a  va  2  s.c  o m*/
    } else if (!hasLaunched && !afterResult) {
        Intent i = null;
        if (launchIntent == null) {
            i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        } else {
            i = launchIntent;
        }
        // workaround for image capture bug
        // create an empty file and pass filename to Camera app.
        if (uriFragmentToMedia == null) {
            uriFragmentToMedia = uriFragmentNewFileBase + TMP_EXTENSION;
        }
        // to make the name unique...
        File mediaFile = ODKFileUtils.getRowpathFile(appName, tableId, instanceId, uriFragmentToMedia);
        if (!mediaFile.exists()) {
            boolean success = false;
            String errorString = " Could not create: " + mediaFile.getAbsolutePath();
            try {
                success = (mediaFile.getParentFile().exists() || mediaFile.getParentFile().mkdirs())
                        && mediaFile.createNewFile();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                errorString = e.toString();
            } finally {
                if (!success) {
                    String err = getString(R.string.media_save_failed);
                    WebLogger.getLogger(appName).e(t, err + errorString);
                    deleteMedia();
                    Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
                    setResult(Activity.RESULT_CANCELED);
                    finish();
                    return;
                }
            }
        }
        i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));

        try {
            hasLaunched = true;
            startActivityForResult(i, ACTION_CODE);
        } catch (ActivityNotFoundException e) {
            String intentActivityName = null;
            if (launchIntent != null && launchIntent.getComponent() != null) {
                intentActivityName = launchIntent.getComponent().getClassName();
            }
            String err = getString(R.string.activity_not_found,
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            WebLogger.getLogger(appName).e(t, err);
            deleteMedia();
            Toast.makeText(this, err, Toast.LENGTH_SHORT).show();
            setResult(Activity.RESULT_CANCELED);
            finish();
        }
    }
}

From source file:com.github.dfa.diaspora_android.activity.ShareActivity2.java

@SuppressLint("SetJavaScriptEnabled")
@Override//ww  w  .  j a v  a  2s  .com
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Helpers.isOnline(ShareActivity2.this)) {
                Intent intent = new Intent(ShareActivity2.this, MainActivity.class);
                startActivityForResult(intent, 100);
                overridePendingTransition(0, 0);
            } else {
                Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
            }
        }
    });

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    fab = (com.getbase.floatingactionbutton.FloatingActionsMenu) findViewById(R.id.fab_expand_menu_button);
    fab.setVisibility(View.GONE);

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.hideTopBar(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.drawer_layout), "Unable to get image",
                            Snackbar.LENGTH_SHORT).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    Intent intent = getIntent();
    final Bundle extras = intent.getExtras();
    String action = intent.getAction();

    if (Intent.ACTION_SEND.equals(action)) {
        webView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

                if (extras.containsKey(Intent.EXTRA_TEXT) && extras.containsKey(Intent.EXTRA_SUBJECT)) {
                    final String extraText = (String) extras.get(Intent.EXTRA_TEXT);
                    final String extraSubject = (String) extras.get(Intent.EXTRA_SUBJECT);

                    webView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                            finish();

                            Intent i = new Intent(ShareActivity2.this, MainActivity.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(i);
                            overridePendingTransition(0, 0);

                            return false;
                        }
                    });

                    webView.loadUrl("javascript:(function() { "
                            + "document.getElementsByTagName('textarea')[0].style.height='110px'; "
                            + "document.getElementsByTagName('textarea')[0].innerHTML = '**[" + extraSubject
                            + "]** " + extraText + " *[shared with #DiasporaWebApp]*'; "
                            + "    if(document.getElementById(\"main_nav\")) {"
                            + "        document.getElementById(\"main_nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main_nav\"));"
                            + "    } else if (document.getElementById(\"main-nav\")) {"
                            + "        document.getElementById(\"main-nav\").parentNode.removeChild("
                            + "        document.getElementById(\"main-nav\"));" + "    }" + "})();");

                }
            }
        });
    }

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity2.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.drawer_layout), R.string.no_internet,
                    Snackbar.LENGTH_SHORT).show();
        }
    }

}

From source file:com.trail.octo.UploadDocs.java

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

    sharedPreferences = getSharedPreferences("user_data", MODE_PRIVATE);
    user_name = sharedPreferences.getString("user_name", "");

    sharedPreferences_docs = getSharedPreferences("docs_data", MODE_PRIVATE);

    upload_docs_pan_select = (ImageView) findViewById(R.id.upload_docs_pan_select);
    upload_docs_driving_select = (ImageView) findViewById(R.id.upload_docs_driving_select);
    upload_docs_aadhar_select = (ImageView) findViewById(R.id.upload_docs_aadhar_select);
    upload_docs_voter_select = (ImageView) findViewById(R.id.upload_docs_voter_select);
    upload_docs_passport_select = (ImageView) findViewById(R.id.upload_docs_passport_select);

    if (sharedPreferences_docs.getString("pancard", "").equals(""))
        pan = true;/* ww w .ja  v  a2  s.c om*/
    else
        upload_docs_pan_select.setVisibility(View.VISIBLE);
    if (sharedPreferences_docs.getString("drivinglicense", "").equals(""))
        driving = true;
    else
        upload_docs_driving_select.setVisibility(View.VISIBLE);
    if (sharedPreferences_docs.getString("voterid", "").equals(""))
        voter = true;
    else
        upload_docs_voter_select.setVisibility(View.VISIBLE);
    if (sharedPreferences_docs.getString("aadharcard", "").equals(""))
        aadhar = true;
    else
        upload_docs_aadhar_select.setVisibility(View.VISIBLE);
    if (sharedPreferences_docs.getString("passport", "").equals(""))
        passport = true;
    else
        upload_docs_passport_select.setVisibility(View.VISIBLE);

    if (savedInstanceState != null)
        file_type = savedInstanceState.getString("file_type");
    imageView_camera = (ImageView) findViewById(R.id.upload_docs_camera);
    imageView_gallery = (ImageView) findViewById(R.id.upload_docs_gallery);
    imageView_profilepic = (ImageView) findViewById(R.id.upload_docs_profile_pic);

    linearLayout_aadhar = (LinearLayout) findViewById(R.id.upload_docs_aadhar);
    linearLayout_driving = (LinearLayout) findViewById(R.id.upload_docs_driving);
    linearLayout_pan = (LinearLayout) findViewById(R.id.upload_docs_pan);
    linearLayout_voter = (LinearLayout) findViewById(R.id.upload_docs_voter);
    linearLayout_passport = (LinearLayout) findViewById(R.id.upload_docs_passport);

    button_submit = (Button) findViewById(R.id.upload_docs_submit);

    button_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (user_name.equals("")) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(getApplicationContext(), Home.class);
                startActivity(intent);
            }
        }
    });
    imageView_camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (askCameraPermission()) {
                file_type = "profilepic";

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            }
        }
    });

    imageView_gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (askGalleryPermission()) {
                file_type = "profilepic";

                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
            }
        }
    });
    LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = layoutInflater.inflate(R.layout.loading_popup_window, null);
    popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, true);

    view_select = layoutInflater.inflate(R.layout.popup_image_capture, null);
    popup_imageView_camera = (ImageView) view_select.findViewById(R.id.popup_imageView_camera);
    popup_imageView_gallery = (ImageView) view_select.findViewById(R.id.popup_imageView_gallary);

    popupWindow_select_source = new PopupWindow(view_select, ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, true);
    popupWindow_select_source.setFocusable(false);
    popupWindow_select_source.setBackgroundDrawable(new BitmapDrawable());
    popupWindow_select_source.setOutsideTouchable(true);

    popup_imageView_gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (askGalleryPermission()) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
            }
        }
    });
    popup_imageView_camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (askCameraPermission()) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
            }
        }
    });
    linearLayout_driving.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (driving) {
                file_type = "drivinglicense";
                popupWindow_select_source.showAtLocation(view_select, Gravity.CENTER, 0, 40);
            } else
                Toast.makeText(getApplicationContext(), "You have already uploaded the Driving license",
                        Toast.LENGTH_SHORT).show();
        }
    });
    linearLayout_pan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (pan) {
                file_type = "pancard";
                popupWindow_select_source.showAtLocation(view_select, Gravity.CENTER, 0, 40);
            } else
                Toast.makeText(getApplicationContext(), "You have already uploaded the Pan Card",
                        Toast.LENGTH_SHORT).show();
        }
    });
    linearLayout_aadhar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (aadhar) {
                file_type = "aadharcard";
                popupWindow_select_source.showAtLocation(view_select, Gravity.CENTER, 0, 40);
            } else
                Toast.makeText(getApplicationContext(), "You have already uploaded the Aadhar Card",
                        Toast.LENGTH_SHORT).show();
        }
    });
    linearLayout_voter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (voter) {
                file_type = "voterid";
                popupWindow_select_source.showAtLocation(view_select, Gravity.CENTER, 0, 40);
            } else
                Toast.makeText(getApplicationContext(), "You have already uploaded the Voter id",
                        Toast.LENGTH_SHORT).show();
        }
    });

    linearLayout_passport.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (passport) {
                file_type = "passport";
                popupWindow_select_source.showAtLocation(view_select, Gravity.CENTER, 0, 40);
            } else
                Toast.makeText(getApplicationContext(), "You have already uploaded the Passport",
                        Toast.LENGTH_SHORT).show();
        }
    });

}

From source file:ca.uwaterloo.magic.goodhikes.AddMilestoneDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mapsActivity = (MapsActivity) getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View dialog = inflater.inflate(R.layout.dialog_add_milestone, null);
    previewImage = (ImageView) dialog.findViewById(R.id.previewImage);

    if (savedInstanceState != null) {
        Bitmap image = savedInstanceState.getParcelable("image");
        if (image != null) {
            previewImage.setImageBitmap(image);
        }/*from  w ww . ja  va 2 s  .  c om*/
    }

    builder.setView(dialog).setTitle(R.string.add_milestone)
            .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    EditText noteField = (EditText) ((Dialog) dialog).findViewById(R.id.note);
                    String note = noteField.getText().toString();
                    Bitmap image = previewImage.getDrawable() == null ? null
                            : ((BitmapDrawable) previewImage.getDrawable()).getBitmap();

                    mapsActivity.imageSelected(image, note);
                    Toast.makeText(getActivity(), "Milestone added", Toast.LENGTH_SHORT).show();
                    Log.d(LOG_TAG, "Thread: " + Thread.currentThread().getId() + "; milestone added");
                }
            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Log.d(LOG_TAG, "Thread: " + Thread.currentThread().getId() + "; milestone cancelled");
                }
            });

    Button addImageButton = (Button) dialog.findViewById(R.id.addImageButton);
    addImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create intent to Open Image applications like Gallery, Google Photos
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    });

    Button cameraButton = (Button) dialog.findViewById(R.id.cameraButton);
    cameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Create intent to open device's Camera
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, RESULT_CAPTURE_IMG);
        }
    });

    return builder.create();
}

From source file:com.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.uiHandler = new Handler();
    this.app = (MessengerApp) getApplication();

    setContentView(R.layout.atlas_screen_messages);

    boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false);
    String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI);
    if (convUri != null) {
        Uri uri = Uri.parse(convUri);// w  ww  .j a va  2s .c o m
        conv = app.getLayerClient().getConversation(uri);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation
    }

    participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker);
    participantsPicker.init(new String[] { app.getLayerClient().getAuthenticatedUserId() },
            app.getParticipantProvider());
    if (convIsNew) {
        participantsPicker.setVisibility(View.VISIBLE);
    }

    messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer);
    messageComposer.init(app.getLayerClient(), conv);
    messageComposer.setListener(new AtlasMessageComposer.Listener() {
        public boolean beforeSend(Message message) {
            boolean conversationReady = ensureConversationReady();
            if (!conversationReady)
                return false;

            // push
            preparePushMetadata(message);
            return true;
        }

    });

    messageComposer.registerMenuItem("Photo", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg";
            photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName);
            final Uri outputUri = Uri.fromFile(photoFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            if (debug)
                Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri);
            startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA);
        }
    });

    messageComposer.registerMenuItem("Image", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            // in onCreate or any event where your want the user to select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY);
        }
    });

    messageComposer.registerMenuItem("Location", new OnClickListener() {
        public void onClick(View v) {
            if (!ensureConversationReady())
                return;

            if (lastKnownLocation == null) {
                Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":"
                    + lastKnownLocation.getLongitude() + "}";
            MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION,
                    locationString.getBytes());
            Message message = app.getLayerClient().newMessage(Arrays.asList(part));

            preparePushMetadata(message);
            conv.send(message);

            if (debug)
                Log.w(TAG, "onSendLocation() loc:  " + locationString);
        }
    });

    messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list);
    messagesList.init(app.getLayerClient(), app.getParticipantProvider());
    if (USE_QUERY) {
        Query<Message> query = Query.builder(Message.class)
                .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv))
                .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING))
                .build();
        messagesList.setQuery(query);
    } else {
        messagesList.setConversation(conv);
    }

    messagesList.setItemClickListener(new ItemClickListener() {
        public void onItemClick(Cell cell) {
            if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) {
                String jsonLonLat = new String(cell.messagePart.getData());
                JSONObject json;
                try {
                    json = new JSONObject(jsonLonLat);
                    double lon = json.getDouble("lon");
                    double lat = json.getDouble("lat");
                    Intent openMapIntent = new Intent(Intent.ACTION_VIEW);
                    String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18,
                            lat, lon);
                    final Uri geoUri = Uri.parse(uriString);
                    openMapIntent.setData(geoUri);
                    if (openMapIntent.resolveActivity(getPackageManager()) != null) {
                        startActivity(openMapIntent);
                        if (debug)
                            Log.w(TAG, "onItemClick() starting Map: " + uriString);
                    } else {
                        if (debug)
                            Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri);
                    }
                } catch (JSONException ignored) {
                }
            } else if (cell instanceof ImageCell) {
                Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(),
                        AtlasImageViewScreen.class);
                app.setParam(intent, cell);
                startActivity(intent);
            }
        }
    });

    typingIndicator = (AtlasTypingIndicator) findViewById(R.id.atlas_screen_messages_typing_indicator);
    typingIndicator.init(conv,
            new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider()));

    // location manager for inserting locations:
    this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    prepareActionBar();
}

From source file:ca.ualberta.cmput301.t03.inventory.AddItemView.java

/**
 * When the upload photos button is clicked an alert dialog will get created asking the
 * user if they want to upload a photo or take a photo, either option will result in a returned
 * bitmap which is handled in onActivityResult.
 *
 * Code used:/*w ww.  ja v  a 2  s . c o  m*/
 * http://stackoverflow.com/questions/27874038/how-to-make-intent-chooser-for-camera-or-gallery-application-in-android-like-wha
 */
private void onUploadPhotosButtonClicked() {
    final CharSequence[] items = { "Take A Photo", "Choose Photo from Gallery" };

    AlertDialog.Builder builder = new AlertDialog.Builder(AddItemView.this);
    builder.setTitle("Attach Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (item == 0) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            } else if (item == 1) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
            }
        }
    });
    builder.show();
}

From source file:it.rignanese.leo.slimtwitter.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    setContentView(R.layout.activity_main);

    //setup the floating button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override//from w  w  w  . ja v  a 2  s . c o  m
        public void onClick(View view) {
            webViewTwitter.scrollTo(0, 0);//scroll up
        }
    });

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialAzureTwitter, R.color.darkAzureSlimTwitterTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    // setup the webView
    webViewTwitter = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewTwitter);//set the settings

    goHome();//load homepage

    //WebViewClient that is the client callback.
    webViewTwitter.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body><h1 "
                    + "style='text-align:center; padding-top:15%;'>" + getString(R.string.titleNoConnection)
                    + "</h1> <h3 style='text-align:center; padding-top:1%; font-style: italic;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='text-align:center; padding-top:80%; opacity: 0.3;'>"
                    + getString(R.string.awards) + "</h5></body></html>";
            webViewTwitter.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || url.contains("twitter.com")) {
                //url is ok
                return false;
            } else {
                //if the link doesn't contain 'twitter.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }

        //START management of loading
        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
            super.onPageFinished(view, url);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewTwitter.setWebChromeClient(new WebChromeClient() {
        //to upload files
        //thanks to gauntface
        //https://github.com/GoogleChrome/chromium-webview-samples
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getBaseContext().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });
}

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 ww.j  a v  a2 s . co  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:bizapps.com.healthforusPatient.activity.RegisterActivity.java

private void cameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

From source file:de.enlightened.peris.ProfileFragment.java

private void setupElements() {
    this.tvCreated = (TextView) this.activity.findViewById(R.id.profileCreated);
    this.tvPostCount = (TextView) this.activity.findViewById(R.id.profilePostCount);
    this.tvActivity = (TextView) this.activity.findViewById(R.id.profileLastActivity);
    this.tvTagline = (TextView) this.activity.findViewById(R.id.profileTagline);
    this.tvAbout = (TextView) this.activity.findViewById(R.id.profileAbout);
    this.ivProfilePic = (ImageView) this.activity.findViewById(R.id.profilePicture);

    final String userid = this.application.getSession().getServer().serverUserId;
    final LinearLayout avatarButtons = (LinearLayout) this.activity
            .findViewById(R.id.profile_avatar_editor_buttons);

    if (this.userId == null) {
        avatarButtons.setVisibility(View.GONE);
    } else if (!this.userId.equals(userid)) {
        avatarButtons.setVisibility(View.GONE);
    }//  w w  w . j av  a 2 s .c om

    final Button btnPicFromCamera = (Button) this.activity.findViewById(R.id.profile_upload_avatar_camera);
    final Button btnPicFromGallery = (Button) this.activity.findViewById(R.id.profile_upload_avatar_gallery);
    if (!this.canHandleCameraIntent()) {
        btnPicFromCamera.setVisibility(View.GONE);
    }
    btnPicFromGallery.setOnClickListener(new View.OnClickListener() {
        public void onClick(final View v) {
            final Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), GALLERY_PIC_REQUEST);
        }
    });

    btnPicFromCamera.setOnClickListener(new View.OnClickListener() {
        public void onClick(final View v) {
            final Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            final File imagesFolder = new File(Environment.getExternalStorageDirectory(), "temp");
            imagesFolder.mkdirs();
            final File image = new File(imagesFolder, "temp.jpg");
            final Uri uriSavedImage = Uri.fromFile(image);
            imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
            startActivityForResult(imageIntent, CAMERA_PIC_REQUEST);
        }
    });

}