Use of Android Camera

Asked

Viewed 742 times

1

Good afternoon, guys, I’m new here, so I’m sorry if I’m asking you something I’ve already talked about. Next we have an app in the company already a while ago for sdk 7, what happens is that recently requested to use the Camera for photos, as well I am using the camera Intent as below:

    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

    startActivityForResult(intent, 123);

and picking up the result normally as below:

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == 123) {
         if (resultCode == Activity.RESULT_OK) {

            Uri image = getLastImage();
            String caminho = getRealPathFromURI(image);

            Bitmap bitmap = BitmapFactory.decodeFile(caminho);


            // Chame este método pra obter a URI da imagem
            Uri uri = getImageUri(getApplicationContext(), bitmap);

            // Em seguida chame este método para obter o caminho do arquivo
            File file = new File(getRealPathFromURI(uri));




             System.out.println("Caminho - "+file.getPath());

        } else {
            Toast.makeText(this, "Imagem não enviada", Toast.LENGTH_LONG)
                    .show();

        }

    } else {
        Toast.makeText(this, "Request não confere", Toast.LENGTH_LONG)
                .show();

    }

    private Uri getLastImage() {
    final ContentResolver cr = getContentResolver();
    final String[] p1 = new String[] { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATE_TAKEN };
    Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1,
            null, null, p1[1] + " DESC");

    int imageID = 0;
    if (c1.moveToFirst()) {
        imageID = c1.getInt(0);
    }
    c1.close();
    Uri uri = Uri.withAppendedPath(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            Integer.toString(imageID));
    return uri;
}

private void Sleep(int i) {
    // TODO Auto-generated method stub

}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = Images.Media.insertImage(inContext.getContentResolver(),
            inImage, "50609", "drawing");
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

but unfortunately this not working very well on some gadgets, I tested on two androids 4.1.2 being LG and Samsung, I also tested on a bike G2 with android 6.0 and it worked, but on another G3 bike with same S.O and not even in Asus with 5.0.0 simply open the camera but when recording locks the mobile phones(unfortunately the mobile phones that gave problem I have not here for error test) by what I realized how to open the printing camera from lack of permission to write, I have tried several methods seen in google without success, someone has had this kind of problem, alias I have tried in several ways to get the result by date.getData(), or date.getExtras("date") where the first returns null in the latest android versions and the second hangs. if anyone has any ideas that can help me.

follows my manifest

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

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="7" />

<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.CAMERA" android:maxSdkVersion="22" android:required="true"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="22" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="22" android:required="true" />

<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera" android:required="false" />

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

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

  • Guys if anyone has another way that can work I appreciate

  • try this http://answall.com/questions/143916/tirar-uma-foto-com-a-camera-frontal-sem-usar-apis-obsoletas/146859?noredirect=1#comment303270_146859

2 answers

2


I create the Intent to camera passing the path where I want you to save the photo, so I already have the photo that was taken saved in this location.

void tirarFoto(){
    File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

    SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
    String nomeFoto = s.format(new Date());
    nomeFoto = codigo + nomeFoto + ".jpg";

    File file = new File(imagesFolder, nomeFoto);
    mCurrentPhotoPath = file.getAbsolutePath();//variavel global
    Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    mTipoFoto = tipofoto;
    startActivityForResult(imageIntent, CAMERA_ACTIVITY_REQUEST_CODE);
}

When I get the result from the camera I get the photo taken from the global variable I saved the path previously.

@OnActivityResult(CAMERA_ACTIVITY_REQUEST_CODE)
void onResult(int resultCode) {
    File file = new File(mCurrentPhotoPath);
    switch (resultCode) {
        case RESULT_OK:
        // salvar foto
        break;
        case RESULT_CANCELED:
            //deletar a foto
            break;
        default:
            //deletar a foto
    }
}

In case he cancels and does not take the photo I delete the created file.

I hope I’ve helped.

1

already managed to solve the problem, I followed some tips from Edileuson Dias, I will post the complete process if someone needs it is easy to use.

I made this test application to another so it may have some flaws that I fixed when transporting to my main, but this worked

I’m taking photos compressing and sending by FTP follow:

FTP class

  import java.io.FileInputStream;

  import org.apache.commons.net.ftp.FTP;
  import org.apache.commons.net.ftp.FTPClient;

  import android.os.AsyncTask;
  import android.util.Log;


    public class Envio extends AsyncTask<String, Integer, Boolean> {
    private FTPClient ftp;
    private Object sistema;
    private String numero;
    private String longitude;
    private String latitude;
    private Boolean Erro;
    private String local;
    private String caminho;

    @Override
    protected Boolean doInBackground(String... params) {

        sistema = params[0];
        numero = params[1];
        caminho = params[2];
        longitude = params[3];
        latitude = params[4];

        ftp = new FTPClient();

        if (sistema.equals("1")) {
            local = "se precicar colocar em pasta diferente";
        }
        if (sistema.equals("2")) {
            local = "se precicar colocar em pasta diferente";
        }

        try {

            String diretorio = caminho;
            String nomeArquivo = numero + ".jpg";
            ftp.connect("www.seuendereco.com.br", 21);
            ftp.login("login", "senha");
            ftp.changeWorkingDirectory("/imagens/" + local);
            FileInputStream arqEnviar = new FileInputStream(diretorio);

            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.storeFile(nomeArquivo + "_" + latitude + "_" + longitude,
                    arqEnviar);
            ftp.logout();
            ftp.disconnect();
            Log.d("AMEE LD", "enviado com sucesso");
            Erro = true;

        } catch (Exception e) {
            Erro = false;
        }

        return Erro;
    }
 }

Class to create Database

   import android.content.Context;
   import android.database.sqlite.SQLiteDatabase;
   import android.database.sqlite.SQLiteOpenHelper;

    public class CriaBanco extends SQLiteOpenHelper {

    private static final String NOME_BANCO = "imagem.db";
    private static final Integer ID = 0;
    private static final String TIPO = "tipo";
    private static final String NUMERO_OS = "numero_os";
    private static final String END_IMAGEM = "end_imagem";
    private static final String LONGITUDE = "longitude";
    private static final String LATITUDE = "latitude";

    private static final String TABELA = "IMAGEM";
    private static final int VERSAO = 1;

    public CriaBanco(Context context) {
        super(context, NOME_BANCO, null, VERSAO);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String sql = "CREATE TABLE " + TABELA + "("
                + "id integer primary key autoincrement,"
                + TIPO  + " text,"
                + NUMERO_OS + " text,"
                + END_IMAGEM + " text,"
                + LONGITUDE + " text,"
                + LATITUDE + " text )";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS" + TABELA);
        onCreate(db);
    }

    public static String getNomeBanco() {
        return NOME_BANCO;
    }

    public static Integer getId() {
        return ID;
    }

    public static String getTipo() {
        return TIPO;
    }

    public static String getNumeroOs() {
        return NUMERO_OS;
    }

    public static String getEndImagem() {
        return END_IMAGEM;
    }


    public static String getLongitude() {
        return LONGITUDE;
    }

    public static String getLatitude() {
        return LATITUDE;
    }

    public static String getTabela() {
        return TABELA;
    }

    public static int getVersao() {
        return VERSAO;
    }

    }

Connection to the bank

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;

    import com.example.conexao.CriaBanco;

    public class BancoController {
    private SQLiteDatabase db;
    private CriaBanco banco;

    public BancoController(Context context) {
        banco = new CriaBanco(context);
    }

    public String insereDado(String tipo, String numero_os, String end_imagem,
            String longitude, String latitude) {
        ContentValues valores;
        long resultado;

        db = banco.getWritableDatabase();
        valores = new ContentValues();
        valores.put(CriaBanco.getTipo(), tipo);
        valores.put(CriaBanco.getNumeroOs(), numero_os);
        valores.put(CriaBanco.getEndImagem(), end_imagem);
        valores.put(CriaBanco.getLongitude(), longitude);
        valores.put(CriaBanco.getLatitude(), latitude);

        resultado = db.insert("IMAGEM", null, valores);
        db.close();

        if (resultado == -1)
            return "Erro ao inserir registro";
        else
            return "Registro Inserido com sucesso";

    }

    public Cursor carregaDados() {
        Cursor cursor;
        String[] campos = { CriaBanco.getTipo(), CriaBanco.getNumeroOs(),
                CriaBanco.getEndImagem(), CriaBanco.getLongitude(),
                CriaBanco.getLatitude() };
        db = banco.getReadableDatabase();
        cursor = db.query(CriaBanco.getTabela(), campos, null, null, null,
                null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        db.close();
        return cursor;
    }

    public Cursor carregaDadoById(int id) {
        Cursor cursor;
        String[] campos = { CriaBanco.getTipo(), CriaBanco.getNumeroOs(),
                CriaBanco.getEndImagem(), CriaBanco.getLongitude(),
                CriaBanco.getLatitude() };
        String where = CriaBanco.getId() + "=" + id;
        db = banco.getReadableDatabase();
        cursor = db.query(CriaBanco.getTabela(), campos, where, null, null,
                null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        db.close();
        return cursor;
    }

    public String deletaRegistro(String numero_os) {
        long resultado;
        String where = CriaBanco.getNumeroOs() + "= '" + numero_os + "'";
        db = banco.getReadableDatabase();
        resultado = db.delete(CriaBanco.getTabela(), where, null);
        db.close();
        if (resultado == -1)
            return "Erro ao apagar registro";
        else
            return "Registro apagado com sucesso";
    }
   }

Main class

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


  @SuppressLint("NewApi")
  public class MainActivity extends ActionBarActivity {
  private ImageButton btCamera;
  private Button btler;
  private Button btdelete;
  private String numero_os1;
  private EditText numeroOs;
  private String Numero;
  private File tempFile;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Botao para Camera
    btCamera = (ImageButton) findViewById(R.id.btCamera);
    btCamera.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            numeroOs = (EditText) findViewById(R.id.etNumeroServico);
            Numero = numeroOs.getText().toString();

            if (Numero.equals("")) {
                Toast.makeText(getApplicationContext(),
                        "Favor Inserir Numero", Toast.LENGTH_LONG).show();
            } else {
                tirar_foto();
            }

        }
    });

    // Botao para ler
    btler = (Button) findViewById(R.id.btler);
    btler.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            BancoController read = new BancoController(getBaseContext());
            Cursor cursor = read.carregaDados();

            if (cursor.isAfterLast() == true) {
                Toast.makeText(getApplicationContext(),
                        "Nenhum Item a ser Enviado", Toast.LENGTH_LONG)
                        .show();
            } else {

                while (!cursor.isAfterLast()) {
                    String tipo = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getTipo())));
                    numero_os1 = (cursor.getString(cursor
                               .getColumnIndexOrThrow(CriaBanco.getNumeroOs())));
                    String end_imagem1 = (cursor.getString(cursor
                             .getColumnIndexOrThrow(CriaBanco.getEndImagem())));
                    String longitude = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getLongitude())));
                    String latitude = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getLatitude())));

                    System.out.println("TIPO - " + tipo);
                    System.out.println("numero_os - " + numero_os1);
                    System.out.println("tipo - " + tipo);
                    System.out.println("longitude - " + longitude);
                    System.out.println("latitude - " + latitude);

                    File file = new File(end_imagem1);
                    if (file.exists()) {
                        String Resultado = null;

                        try {
                            Boolean retorno = new Envio().execute(tipo,
                                    numero_os1, end_imagem1, longitude,
                                    latitude).get();

                            System.out.println("Retorno " + retorno);

                            if (retorno == true) {
                                Resultado = "Imagem enviada";
                            } else {
                                Resultado = "Imagem não enviada";
                            }

                        } catch (Exception ex) {
                            Resultado = "Imagem não enviada";
                            System.out.println(ex);
                        }
                        System.out.println("Imagem Enviada - Nº "
                                + numero_os1);

                        Toast.makeText(getApplicationContext(), Resultado
                                + " - Nº " + numero_os1, Toast.LENGTH_LONG);

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Imagem não encontrada", Toast.LENGTH_LONG)
                                .show();
                    }
                    cursor.moveToNext();

                }

            }
        }
    });

    // Botao para delete
    btdelete = (Button) findViewById(R.id.btdelete);
    btdelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // prepara variavel para receber o numero do servico

            BancoController read = new BancoController(getBaseContext());
            Cursor cursor = read.carregaDados();

            // chama classe controller do bd
            BancoController crud = new BancoController(getBaseContext());

            if (cursor.isAfterLast() == true) {
                Toast.makeText(getApplicationContext(),
                        "Nenhum Item a ser Apagado", Toast.LENGTH_LONG)
                        .show();
            } else {
                while (!cursor.isAfterLast()) {
                    String resultado;

                    numero_os1 = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getNumeroOs())));

                    String end_imagem1 = (cursor.getString(cursor
                            .getColumnIndexOrThrow(CriaBanco.getEndImagem())));

                    File file = new File(end_imagem1);
                    Boolean deleted = true;
                    if (file.exists()) {
                        try {
                            deleted = file.delete();
                        } catch (Exception e) {
                            deleted = false;
                            throw new RuntimeException(
                                    "Erro ao deletar imagem", e);
                        }

                    } else {
                        Toast.makeText(getApplicationContext(),
                                "Imagem não encontrada", Toast.LENGTH_LONG)
                                .show();
                    }
                    if (deleted == true) {
                        resultado = crud.deletaRegistro(numero_os1);

                        Toast.makeText(getApplicationContext(),
                                resultado + " - Imagem - " + numero_os1,
                                Toast.LENGTH_LONG).show();
                    }

                    cursor.moveToNext();
                }

            }
        }
    });

}

public void tirar_foto() {

    File mediaStorage = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
            "Camera");

    String nomeFoto = Numero + ".jpg";
    tempFile = new File(mediaStorage, nomeFoto);

    System.out.println("temp -" + tempFile);

    if (tempFile.exists()) {
        tempFile.delete();
    }
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));

    startActivityForResult(intent, 123);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent  data) {
    if (requestCode == 123) {
        if (resultCode == Activity.RESULT_OK) {
            String end_imagem = null;

            numeroOs = (EditText) findViewById(R.id.etNumeroServico);
            Numero = numeroOs.getText().toString();

            // variaveis para gravação
            String tipo = "1";// pos
            String numero_os = Numero;
            String longitude = "-25.4344087";
            String latitude = "-49.26725736";
            String resultado;

            File mediaStorage = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    "Camera");

            String nomeFoto = Numero + ".jpg";
            tempFile = new File(mediaStorage, nomeFoto);

            end_imagem = tempFile.getPath();

            File cam_imagem = new File(end_imagem);

            if (cam_imagem.exists()) {
                Toast.makeText(getApplicationContext(), "existe",
                        Toast.LENGTH_LONG).show();
            }
            System.out.println("caminho - " + end_imagem);

            // busca imagem e comprime
            new BitmapFactory();
            Bitmap bitmap = BitmapFactory.decodeFile(end_imagem);

            // cria um stream pra salvar o arquivo
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(end_imagem);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // salva a imagem reduzida no disco
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);

            // chama classe controller do bd
            BancoController crud = new BancoController(getBaseContext());
            resultado = crud.insereDado(tipo, numero_os, end_imagem,
                    longitude, latitude);

            Toast.makeText(getApplicationContext(), resultado,
                    Toast.LENGTH_LONG).show();

        } else {
            Toast.makeText(this, "Imagem não enviada", Toast.LENGTH_LONG)
                    .show();

        }

    } else {
        Toast.makeText(this, "Request não confere", Toast.LENGTH_LONG)
                .show();
    }
}

public boolean verificaConexao() {
    boolean conectado;
    ConnectivityManager conectivtyManager = (ConnectivityManager)   getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conectivtyManager.getActiveNetworkInfo() != null
            && conectivtyManager.getActiveNetworkInfo().isAvailable()
            && conectivtyManager.getActiveNetworkInfo().isConnected()) {
        conectado = true;
    } else {
        conectado = false;
    }
    return conectado;
}

private void Sleep(int i) {
    // TODO Auto-generated method stub

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

layout

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<ImageButton
    android:id="@+id/btCamera"
    android:layout_width="37dp"
    android:layout_height="32dp"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="104dp"
    android:src="@drawable/cameras" />

<EditText
    android:id="@+id/etNumeroServico"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="24dp"
    android:ems="10"
    android:inputType="text" />

<Button
    android:id="@+id/btdelete"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/btler"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="56dp"
    android:text="Deletar" />

<Button
    android:id="@+id/btler"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/btdelete"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="52dp"
    android:text="Ler/Enviar" />

only I don’t know how to close the question as resolved, if anyone can help me.

  • personal is very simple but suddenly someone has some similar doubt, may help someone

  • To indicate how "solved" click the V in the top left corner of the answer, below the number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.