In questo esempio andremo ad utilizzare un intent per avviare la fotocamera del telefonino con MediaStore.ACTION_IMAGE_CAPTURE.
Per avviare l’intento utilizzeremmo il metodo
startActivityForResult e
onActivityResult , per ricevere i dati della fotocamera.
Ecco il codice:
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>
<Button
android:text=”Photo”
android:id=”@+id/btn”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”/>
<ImageView
android:id=”@+id/image”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”/>
</LinearLayout>
package com.example.camera.activities;
import android.app.Activity;
import android.os.Bundle;
import com.example.camera.R;
import android.widget.*;
import android.view.*;
import android.content.*;
import android.hardware.*;
import android.provider.*;
import android.graphics.*;
public class MainActivity extends Activity {
Button button;
ImageView image;
int camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= findViewById(R.id.btn);
image = findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult( intent,camera);
}
});
}
@Override
protected void onActivityResult( int requestCode, int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (resultCode == Activity.RESULT_OK) {
Bitmap bm = (Bitmap)data.getExtras().get(“data”);
image.setImageBitmap(bm);
}
}
}