Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 709dca44 authored by Scott Main's avatar Scott Main Committed by Android Git Automerger
Browse files

am fb214e6b: am 3032999b: Merge "Update to the Taking Photos Simply lesson...

am fb214e6b: am 3032999b: Merge "Update to the Taking Photos Simply lesson (offshoot of the intent doc rewrite) clarifications about different external directories, information about required permissions, intent resolution technique to match other docs, clarify sectio

* commit 'fb214e6b':
  Update to the Taking Photos Simply lesson (offshoot of the intent doc rewrite) clarifications about different external directories, information about required permissions, intent resolution technique to match other docs, clarify section headings, plus other code clarification
parents 4dd5c377 fb214e6b
Loading
Loading
Loading
Loading
+11 −21
Original line number Original line Diff line number Diff line
@@ -152,10 +152,8 @@ public void setCamera(Camera camera) {
            e.printStackTrace();
            e.printStackTrace();
        }
        }
      
      
        /*
        // Important: Call startPreview() to start updating the preview
          Important: Call startPreview() to start updating the preview surface. Preview must 
        // surface. Preview must be started before you can take a picture.
          be started before you can take a picture.
          */
        mCamera.startPreview();
        mCamera.startPreview();
    }
    }
}
}
@@ -177,10 +175,8 @@ public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    requestLayout();
    requestLayout();
    mCamera.setParameters(parameters);
    mCamera.setParameters(parameters);


    /*
    // Important: Call startPreview() to start updating the preview surface.
      Important: Call startPreview() to start updating the preview surface. Preview must be
    // Preview must be started before you can take a picture.
      started before you can take a picture.
    */
    mCamera.startPreview();
    mCamera.startPreview();
}
}
</pre>
</pre>
@@ -251,9 +247,7 @@ Preview} class.</p>
public void surfaceDestroyed(SurfaceHolder holder) {
public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    // Surface will be destroyed when we return, so stop the preview.
    if (mCamera != null) {
    if (mCamera != null) {
        /*
        // Call stopPreview() to stop updating the preview surface.
          Call stopPreview() to stop updating the preview surface.
        */
        mCamera.stopPreview();
        mCamera.stopPreview();
    }
    }
}
}
@@ -264,16 +258,12 @@ public void surfaceDestroyed(SurfaceHolder holder) {
private void stopPreviewAndFreeCamera() {
private void stopPreviewAndFreeCamera() {


    if (mCamera != null) {
    if (mCamera != null) {
        /*
        // Call stopPreview() to stop updating the preview surface.
          Call stopPreview() to stop updating the preview surface.
        */
        mCamera.stopPreview();
        mCamera.stopPreview();
    
    
        /*
        // Important: Call release() to release the camera for use by other
          Important: Call release() to release the camera for use by other applications. 
        // applications. Applications should release the camera immediately
          Applications should release the camera immediately in onPause() (and re-open() it in
        // during onPause() and re-open() it during onResume()).
          onResume()).
        */
        mCamera.release();
        mCamera.release();
    
    
        mCamera = null;
        mCamera = null;
+1 −1
Original line number Original line Diff line number Diff line
@@ -14,7 +14,7 @@ next.link=photobasics.html


<h2>Dependencies and prerequisites</h2>
<h2>Dependencies and prerequisites</h2>
<ul>
<ul>
  <li>Android 1.5 (API level 3) or higher</li>
  <li>Android 2.2 (API level 8) or higher</li>
  <li>A device with a camera</li>
  <li>A device with a camera</li>
</ul>
</ul>


+119 −82
Original line number Original line Diff line number Diff line
@@ -16,8 +16,8 @@ next.link=videobasics.html
    <ol>
    <ol>
      <li><a href="#TaskManifest">Request Camera Permission</a></li>
      <li><a href="#TaskManifest">Request Camera Permission</a></li>
      <li><a href="#TaskCaptureIntent">Take a Photo with the Camera App</a></li>
      <li><a href="#TaskCaptureIntent">Take a Photo with the Camera App</a></li>
      <li><a href="#TaskPhotoView">View the Photo</a></li>
      <li><a href="#TaskPhotoView">Get the Thumbnail</a></li>
      <li><a href="#TaskPath">Save the Photo</a></li>
      <li><a href="#TaskPath">Save the Full-size Photo</a></li>
      <li><a href="#TaskGallery">Add the Photo to a Gallery</a></li>
      <li><a href="#TaskGallery">Add the Photo to a Gallery</a></li>
      <li><a href="#TaskScalePhoto">Decode a Scaled Image</a></li>
      <li><a href="#TaskScalePhoto">Decode a Scaled Image</a></li>
    </ol>
    </ol>
@@ -60,15 +60,16 @@ that your application depends on having a camera, put a <a
href="{@docRoot}guide/topics/manifest/uses-feature-element.html"> {@code
href="{@docRoot}guide/topics/manifest/uses-feature-element.html"> {@code
&lt;uses-feature&gt;}</a> tag in your manifest file:</p>
&lt;uses-feature&gt;}</a> tag in your manifest file:</p>


<pre>
<pre style="clear:right">
&lt;manifest ... >
&lt;manifest ... >
    &lt;uses-feature android:name="android.hardware.camera" /&gt;
    &lt;uses-feature android:name="android.hardware.camera"
                  android:required="true" /&gt;
    ...
    ...
&lt;/manifest ... >
&lt;/manifest>
</pre>
</pre>


<p>If your application uses, but does not require a camera in order to function, add {@code
<p>If your application uses, but does not require a camera in order to function, instead set {@code
android:required="false"} to the tag. In doing so, Google Play will allow devices without a
android:required} to {@code false}. In doing so, Google Play will allow devices without a
camera to download your application. It's then your responsibility to check for the availability
camera to download your application. It's then your responsibility to check for the availability
of the camera at runtime by calling {@link
of the camera at runtime by calling {@link
android.content.pm.PackageManager#hasSystemFeature hasSystemFeature(PackageManager.FEATURE_CAMERA)}.
android.content.pm.PackageManager#hasSystemFeature hasSystemFeature(PackageManager.FEATURE_CAMERA)}.
@@ -85,30 +86,27 @@ and some code to handle the image data when focus returns to your activity.</p>
<p>Here's a function that invokes an intent to capture a photo.</p>
<p>Here's a function that invokes an intent to capture a photo.</p>


<pre>
<pre>
private void dispatchTakePictureIntent(int actionCode) {
static final int REQUEST_IMAGE_CAPTURE = 1;

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


<p>Notice that the {@link android.app.Activity#startActivityForResult
startActivityForResult()} method is protected by a condition that calls
{@link android.content.Intent#resolveActivity resolveActivity()}, which returns the
first activity component that can handle the intent. Performing this check
is important because if you call {@link android.app.Activity#startActivityForResult
startActivityForResult()} using an intent that no app can handle,
your app will crash. So as long as the result is not null, it's safe to use the intent. </p>


<p>Congratulations: with this code, your application has gained the ability to
make another camera application do its bidding! Of course, if no compatible
application is ready to catch the intent, then your app will fall down like a
botched stage dive. Here is a function to check whether an app can handle your intent:</p>

<pre>
public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List&lt;ResolveInfo> list =
            packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}
</pre>




<h2 id="TaskPhotoView">View the Photo</h2>
<h2 id="TaskPhotoView">Get the Thumbnail</h2>


<p>If the simple feat of taking a photo is not the culmination of your app's
<p>If the simple feat of taking a photo is not the culmination of your app's
ambition, then you probably want to get the image back from the camera
ambition, then you probably want to get the image back from the camera
@@ -120,10 +118,13 @@ android.graphics.Bitmap} in the extras, under the key {@code "data"}. The follow
this image and displays it in an {@link android.widget.ImageView}.</p>
this image and displays it in an {@link android.widget.ImageView}.</p>


<pre>
<pre>
private void handleSmallCameraPhoto(Intent intent) {
&#64;Override
    Bundle extras = intent.getExtras();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mImageBitmap = (Bitmap) extras.get("data");
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
    mImageView.setImageBitmap(mImageBitmap);
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}
}
</pre>
</pre>


@@ -132,72 +133,104 @@ icon, but not a lot more. Dealing with a full-sized image takes a bit more
work.</p>
work.</p>




<h2 id="TaskPath">Save the Photo</h2> 
<h2 id="TaskPath">Save the Full-size Photo</h2>


<p>The Android Camera application saves a full-size photo if you give it a file to
<p>The Android Camera application saves a full-size photo if you give it a file to
save into. You must provide a path that includes the storage volume,
save into. You must provide a fully qualified file name where the camera app should
folder, and file name.</p>
save the photo.</p>


<p>There is an easy way to get the path for photos, but it works only on Android 2.2 (API level 8)
<p>Generally, any photos that the user captures with the device camera should be saved on
and later:</p>
the device in the public external storage so they are accessible by all apps.
The proper directory for shared photos is provided by {@link
android.os.Environment#getExternalStoragePublicDirectory getExternalStoragePublicDirectory()},
with the {@link android.os.Environment#DIRECTORY_PICTURES} argument. Because the directory
provided by this method is shared among all apps, reading and writing to it requires the
{@link android.Manifest.permission#READ_EXTERNAL_STORAGE} and
{@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permissions, respectively.
The write permission implicitly allows reading, so if you need to write to the external
storage then you need to request only one permission:</p>


<pre>
<pre>
storageDir = new File(
&lt;manifest ...>
    Environment.getExternalStoragePublicDirectory(
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        Environment.DIRECTORY_PICTURES
    ...
    ), 
&lt;/manifest>
    getAlbumName()
);		
</pre>
</pre>


<p>For earlier API levels, you have to provide the name of the photo
<p>However, if you'd like the photos to remain private to your app only, you can instead use the
directory yourself.</p>
directory provided by {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}.

On Android 4.3 and lower, writing to this directory also requires the
{@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permission. Beginning with
Android 4.4, the permission is no longer required because the directory is not accessible
by other apps, so you can declare the permission should be requested only on the lower versions
of Android by adding the <a
href="{@docRoot}guide/topics/manifest/uses-permission-element.html#maxSdk">{@code maxSdkVersion}</a>
attribute:</p>
<pre>
<pre>
storageDir = new File (
&lt;manifest ...>
    Environment.getExternalStorageDirectory()
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        + PICTURES_DIR
                     android:maxSdkVersion="18" />
        + getAlbumName()
    ...
);
&lt;/manifest>
</pre>
</pre>


<p class="note"><strong>Note:</strong> The path component {@code PICTURES_DIR} is
<p class="note"><strong>Note:</strong> Files you save in the directories provided by
just {@code Pictures/}, the standard location for shared photos on the external/shared
{@link android.content.Context#getExternalFilesDir getExternalFilesDir()} are deleted
storage.</p>
when the user uninstalls your app.</p>



<h3 id="TaskFileName">Set the file name</h3> 
<p>Once you decide the directory for the file, you need to create a

collision-resistant file name. You may wish also to save the path in a
<p>As shown in the previous section, the file location for an image should be
member variable for later use. Here's an example solution in a method that returns
driven by the device environment. What you need to do yourself is choose a
a unique file name for a new photo using a date-time stamp:</p>
collision-resistant file-naming scheme. You may wish also to save the path in a
member variable for later use. Here's an example solution:</p>


<pre>
<pre>
String mCurrentPhotoPath;

private File createImageFile() throws IOException {
private File createImageFile() throws IOException {
    // Create an image file name
    // Create an image file name
    String timeStamp = 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
    File image = File.createTempFile(
        imageFileName, 
        imageFileName,  /* prefix */
        JPEG_FILE_SUFFIX, 
        ".jpg",         /* suffix */
        getAlbumDir()
        storageDir      /* directory */
    );
    );
    mCurrentPhotoPath = image.getAbsolutePath();

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
    return image;
}
}
</pre>
</pre>




<h3 id="TaskIntentFileName">Append the file name onto the Intent</h3>
<p>With this method available to create a file for the photo, you can now

create and invoke the {@link android.content.Intent} like this:</p>
<p>Once you have a place to save your image, pass that location to the camera
application via the {@link android.content.Intent}.</p>


<pre>
<pre>
File f = createImageFile();
static final in REQUEST_TAKE_PHOTO = 1;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}
</pre>
</pre>




@@ -207,6 +240,10 @@ takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
you said where to save it in the first place.  For everyone else, perhaps the easiest way to make
you said where to save it in the first place.  For everyone else, perhaps the easiest way to make
your photo accessible is to make it accessible from the system's Media Provider.</p>
your photo accessible is to make it accessible from the system's Media Provider.</p>


<p class="note"><strong>Note:</strong> If you saved your photo to the directory provided by
{@link android.content.Context#getExternalFilesDir getExternalFilesDir()}, the media
scanner cannot access the files because they are private to your app.</p>

<p>The following example method demonstrates how to invoke the system's media scanner to add your
<p>The following example method demonstrates how to invoke the system's media scanner to add your
photo to the Media Provider's database, making it available in the Android Gallery application
photo to the Media Provider's database, making it available in the Android Gallery application
and to other apps.</p>
and to other apps.</p>
+30 −30
Original line number Original line Diff line number Diff line
@@ -54,15 +54,16 @@ records video. In this lesson, you make it do this for you.</p>
<p>To advertise that your application depends on having a camera, put a
<p>To advertise that your application depends on having a camera, put a
{@code &lt;uses-feature&gt;} tag in the manifest file:</p>
{@code &lt;uses-feature&gt;} tag in the manifest file:</p>


<pre>
<pre style="clear:right">
&lt;manifest ... >
&lt;manifest ... >
    &lt;uses-feature android:name="android.hardware.camera" /&gt;
    &lt;uses-feature android:name="android.hardware.camera"
                  android:required="true" /&gt;
    ...
    ...
&lt;/manifest ... >
&lt;/manifest>
</pre>
</pre>


<p>If your application uses, but does not require a camera in order to function, add {@code
<p>If your application uses, but does not require a camera in order to function, set {@code
android:required="false"} to the tag. In doing so, Google Play will allow devices without a
android:required} to {@code false}. In doing so, Google Play will allow devices without a
camera to download your application. It's then your responsibility to check for the availability
camera to download your application. It's then your responsibility to check for the availability
of the camera at runtime by calling {@link
of the camera at runtime by calling {@link
android.content.pm.PackageManager#hasSystemFeature hasSystemFeature(PackageManager.FEATURE_CAMERA)}.
android.content.pm.PackageManager#hasSystemFeature hasSystemFeature(PackageManager.FEATURE_CAMERA)}.
@@ -71,36 +72,32 @@ If a camera is not available, you should then disable your camera features.</p>


<h2 id="TaskCaptureIntent">Record a Video with a Camera App</h2>
<h2 id="TaskCaptureIntent">Record a Video with a Camera App</h2>


<p>The Android way of delegating actions to other applications is to invoke
<p>The Android way of delegating actions to other applications is to invoke an {@link
an {@link android.content.Intent} that describes what you want done.  This
android.content.Intent} that describes what you want done. This process involves three pieces: The
involves three pieces: the {@link android.content.Intent} itself, a call to start the external
{@link android.content.Intent} itself, a call to start the external {@link android.app.Activity},
{@link android.app.Activity}, and some code to handle the video when focus returns
and some code to handle the video when focus returns to your activity.</p>
to your activity.</p>


<p>Here's a function that invokes an intent to capture video.</p>
<p>Here's a function that invokes an intent to capture video.</p>


<pre>
<pre>
static final int REQUEST_VIDEO_CAPTURE = 1;

private void dispatchTakeVideoIntent() {
private void dispatchTakeVideoIntent() {
    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
    }
    }
</pre>


<p>It's a good idea to make sure an app exists to handle your intent
before invoking it. Here's a function that checks for apps that can handle your intent:</p>

<pre>
public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List&lt;ResolveInfo> list =
        packageManager.queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}
}
</pre>
</pre>


<p>Notice that the {@link android.app.Activity#startActivityForResult
startActivityForResult()} method is protected by a condition that calls
{@link android.content.Intent#resolveActivity resolveActivity()}, which returns the
first activity component that can handle the intent. Performing this check
is important because if you call {@link android.app.Activity#startActivityForResult
startActivityForResult()} using an intent that no app can handle,
your app will crash. So as long as the result is not null, it's safe to use the intent. </p>



<h2 id="TaskVideoView">View the Video</h2>
<h2 id="TaskVideoView">View the Video</h2>


@@ -110,9 +107,12 @@ android.net.Uri} pointing to the video location in storage. The following code
retrieves this video and displays it in a {@link android.widget.VideoView}.</p>
retrieves this video and displays it in a {@link android.widget.VideoView}.</p>


<pre>
<pre>
private void handleCameraVideo(Intent intent) {
&#64;Override
    mVideoUri = intent.getData();
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    mVideoView.setVideoURI(mVideoUri);
    if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
        Uri videoUri = intent.getData();
        mVideoView.setVideoURI(videoUri);
    }
}
}
</pre>
</pre>