Como Capturar Imagem da Câmera do Android?

Olá pessoal.

Estou com problemas para abrir a câmera, que irá fazer a captura de imagens para tirar fotos e salvá-las, no Android Studio utilizando emuladores. Segue o código abaixo:

CameraActivity.java

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.io.File;

public class CameraActivity extends AppCompatActivity {
    private static final int CAPTURAR_IMAGEM = 1;
    private Uri uri;

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

    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        if (requestCode == CAPTURAR_IMAGEM) {
            if (resultCode == RESULT_OK) {
                mostrarMensagem("Imagem capturada!");
                adicionarNaGaleria();
            } else {
                mostrarMensagem("Imagem não capturada!");
            }
        }
    }

    private void mostrarMensagem(String msg){
        Toast.makeText(this, msg,
                Toast.LENGTH_LONG)
                .show();
    }

    private void adicionarNaGaleria() {
        Intent intent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(uri);
        this.sendBroadcast(intent);
    }

    public void capturarImagem(View v){
        boolean temCamera = getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA);
        if(temCamera) {
            File diretorio = Environment
                    .getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES);
            String nomeImagem = diretorio.getPath() + "/" +
                    System.currentTimeMillis() +
                    ".jpg";
            uri = Uri.fromFile(new File(nomeImagem));

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, CAPTURAR_IMAGEM);
        }
    }
    public void visualizarImagem(View v){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "image/jpeg");
        startActivity(intent);
    }
}

activity_camera.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout `xmlns:android="http://schemas.android.com/apk/res/android"`
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.testarcamera.CameraActivity">

    <LinearLayout
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnCapturarImagem"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/capturarImagem"
                android:onClick="capturarImagem"/>

            <Button
                android:id="@+id/btnVisualizarImagem"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/visualizarImagem"
                android:onClick="visualizarImagem"/>
        </LinearLayout>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testarcamera">

    <uses-sdk
        android:maxSdkVersion="26"
        android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CameraActivity"></activity>
    </application>

</manifest>

Pesquisei em vários lugares, seguindo passo a passo do que falaram, porém ainda não achei o erro. Está acontecendo tudo certo, porém quando clico no botão para abrir a câmera e tirar foto, ele diz que o app parou de funcionar e fecha ele. Coloquei as permissões que diziam para colocar no AndroidManifest.xml, mas mesmo assim não adiantou. Mudei as configurações dos emuladores que utilizo na parte da câmera para usar Webcam0 e não funcionou, então coloquei para usar Emulated e também não deu. Alguém pode me ajudar pra eu saber qual é o problema e o que fazer? Obrigado.

Qual o erro que está dando?

Tenho um código semelhante, que funciona… mas no nomeImagem coloquei .png e em intent.setDataAndType(uri, “image/jpeg”); coloquei image/*. Mas coloque o erro, assim fica mais fácil de identificar o problema. Att.

Olá Marcus. Bom, fiz as devidas modificações para ficar igual ao seu e continua dando erro. O erro que está dando é: file:///storage/emulated/0/Pictures/1500485038789.png exposed beyond app through ClipData.Item.getUri().

Antes de eu fazer essas modificações aparecia a mesma coisa, porém com o .jpg em vez do .png.

Além disso, no logcat está aparecendo isso:

07-19 17:10:18.213 4252-4252/? W/IInputConnectionWrapper: reportFullscreenMode on inexistent `InputConnection`
07-19 17:10:18.213 4252-4252/? W/IInputConnectionWrapper: finishComposingText on inactive `InputConnection`
07-19 17:13:46.002 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/networkstatistics.sqlite' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:13:46.005 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:13:46.005 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:13:46.005 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:18:38.329 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:18:38.329 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:18:38.330 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:27:32.041 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:27:32.041 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`
07-19 17:27:32.042 2252-2260/? W/SQLiteConnectionPool: A SQLiteConnection object for database `'/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.`

Obrigado pela resposta.

Guilherme, sei que já tem algum tempo mas você conseguiu resolver o problema?
É que estou tomando erro intermitente na captura da imagem. Eu abro a câmera pelo app e quando tiro a foto algumas vezes da erro e outras a captura funciona.