Sunday, March 5, 2017

Use camera in Android

Camera is a useful and frequently used feature in Android applications. So here is the simple way to implement feature of camera in your Android application.

1. Manifest permission: 
     
     Provide following uses-feature to use camera in your app.
  
    <uses-feature android:name="android.hardware.camera"     
     android:required="true" />
2. Button to open camera:
    
    Just take a button in your activity_main.xml layout file. So on click of that of button we can open         camera. And an Image View to display image.

3. Now do some stuff in your MainActivity.Java or any other file where you want to implement.

   public class MainActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageView mImageView;
    private Button mCam;

       @Override    
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mImageView = (ImageView) findViewById(R.id.image);
        mCam = (Button) findViewById(R.id.cam);

        mCam.setOnClickListener(new View.OnClickListener() {
            @Override            
             public void onClick(View view) {
                dispatchTakePictureIntent();
            }
        });
    }


    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }


    @Override   
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
    
} 


You can see the result below:


That's it...... Thanks