本文出自 “whithin's” 博客,请务必保留此出处http://whithin.blog.51cto.com/690417/1058972

Sample code,实现简单应用界面包含两个button,点击button 分别打开camera, 和cameroder,主界面如下图所示

145628415.png

1. 在AndroidManifest.xml文件中包含camera 相关的权限

 
  
  1. AndroidManifest.xml

  2. <?xml version= "1.0" encoding ="utf-8"?>

  3. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  4. package="android.study.sample"

  5.    android:versionCode= "1"

  6.    android:versionName= "1.0" >

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

  8.    <uses-permission android:name= "android.permission.CAMERA" />

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

  10.    <application

  11.        android:icon="@drawable/ic_launcher"

  12.        android:label="@string/app_name" >

  13.        <activity

  14.            android:name="android.study.sample.CameraIntentActivity"

  15.            android:label="@string/app_name" >

  16.            <intent-filter>

  17.                <action android:name="android.intent.action.MAIN" />

  18.                <category android:name="android.intent.category.LAUNCHER" />

  19.            </intent-filter>

  20.        </activity>

  21.    </application >

  22. </manifest>


2.在主界面的layout文件中添加两个button,分别负责打开拍照和录视频的应用

  1. -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  2. res/layout/main.xml

  3. <? xml version= "1.0" encoding = "utf-8"?>

  4. < RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android"

  5.    android:layout_width= "match_parent"

  6.    android:layout_height= "match_parent" >

  7.    <Button

  8.        android:id ="@+id/buttonTakePic"

  9.        android:layout_width ="match_parent"

  10.        android:layout_height ="wrap_content"

  11.        android:layout_alignParentTop ="true"

  12.        android:layout_centerHorizontal ="true"

  13.        android:layout_marginTop ="100dp"

  14.        android:text ="takepicture" />

  15.    <Button

  16.        android:id ="@+id/buttonRecordVideo"

  17.        android:layout_width ="match_parent"

  18.        android:layout_height ="wrap_content"

  19.        android:layout_alignParentLeft ="true"

  20.        android:layout_alignParentTop ="true"

  21.        android:layout_marginTop ="42dp"

  22.        android:text ="recordvideo" />

  23. </ RelativeLayout>


3.通过发送不同的Intent打开拍照和录视频的应用

MediaStore.ACTION_IMAGE_CAPTURE
MediaStore.ACTION_VIDEO_CAPTURE

程序调用startActivityForResult(Intent, int, Bundle)
接口启动相应的应用程序, 并且必须Activity实现 onActivityResult() 来接受调用相应的Camera应用activity之后的结果


  1. ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  2. android.study.sample/CameraIntentActivity.java  

  3. package android.study.sample;

  4. import java.io.File;

  5. import java.text.SimpleDateFormat;

  6. import java.util.Date;

  7. import android.app.Activity;

  8. import android.content.Intent;

  9. import android.net.Uri;

  10. import android.os.Bundle;

  11. import android.os.Environment;

  12. import android.provider.MediaStore;

  13. import android.util.Log;

  14. import android.view.View;

  15. import android.view.View.OnClickListener;

  16. import android.widget.Button;

  17. import android.widget.Toast;

  18. publicclass CameraIntentActivity extends Activity{

  19. publicstaticfinalint MEDIA_TYPE_IMAGE = 1;

  20. publicstaticfinalint MEDIA_TYPE_VIDEO = 2;

  21. privatestaticfinalint CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

  22. privatestaticfinalint CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;

  23. private Uri fileUri ;

  24.       Button takePicureButton;

  25.       Button recordVideoButton;

  26.       OnClickListener cameraButtonListenser =  new OnClickListener(){

  27. publicvoid onClick(View view) {

  28. // TODO Auto-generated method stub

  29.                     Intent intent = null;

  30. if(((Button)view).equals(takePicureButton )){

  31. // create Intent to take a picture and return control to the calling application

  32.                         intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

  33.                         fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the p_w_picpath

  34.                         intent.putExtra(MediaStore. EXTRA_OUTPUT, fileUri ); // set the p_w_picpath file name

  35. // start the video record Intent

  36.                         startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );

  37.                     } elseif (((Button)view).equals(recordVideoButton)){

  38.                         intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

  39.                         fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video

  40.                         intent.putExtra(MediaStore. EXTRA_OUTPUT, fileUri ); // set the video file name

  41.                         startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE );

  42.                     }

  43.              }

  44.       };

  45. @Override

  46. publicvoid onCreate(Bundle savedInstanceState) {

  47. super.onCreate(savedInstanceState);

  48.           setContentView(R.layout. main);

  49.           takePicureButton = (Button)findViewById(R.id.buttonTakePic);

  50.           recordVideoButton = (Button)findViewById(R.id.buttonRecordVideo);

  51.           takePicureButton.setOnClickListener(cameraButtonListenser );

  52.           recordVideoButton.setOnClickListener(cameraButtonListenser );

  53.       }

  54. @Override

  55. protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {

  56. if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

  57. if (resultCode == RESULT_OK) {

  58. // Image captured and saved to fileUri specified in the Intent

  59. if(data!=null ){

  60.                          Toast. makeText(this, "Image saved to:\n" +

  61.                                   data.getData().toString(), Toast.LENGTH_LONG).show();                      

  62.                     } else{                      

  63.                            System. out.println("can't get any data!!!" );

  64.                     }

  65.               } elseif (resultCode == RESULT_CANCELED) {

  66. // User cancelled the p_w_picpath capture

  67.               } else {

  68. // Image capture failed, advise user

  69.               }

  70.           }

  71. if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {

  72. if (resultCode == RESULT_OK) {

  73. // Video captured and saved to fileUri specified in the Intent

  74. if(data!=null ){

  75.                          Toast. makeText(this, "Image saved to:\n" +

  76.                                   data.getData().toString(), Toast.LENGTH_LONG).show();

  77.                     } else{

  78.                            System. out.println("can't get any data!!!" );

  79.                     }

  80.               } elseif (resultCode == RESULT_CANCELED) {

  81. // User cancelled the video capture

  82.               } else {

  83. // Video capture failed, advise user

  84.               }

  85.           }

  86.       }

  87. /** Create a file Uri for saving an p_w_picpath or video */

  88. privatestatic Uri getOutputMediaFileUri(int type){

  89. return Uri.fromFile( getOutputMediaFile(type));

  90.       }

  91. /** Create a File for saving an p_w_picpath or video */

  92. privatestatic File getOutputMediaFile(int type){

  93. // To be safe, you should check that the SDCard is mounted

  94. // using Environment.getExternalStorageState() before doing this.

  95.           File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(

  96.                     Environment. DIRECTORY_PICTURES), "MyCameraApp" );

  97. // This location works best if you want the created p_w_picpaths to be shared

  98. // between applications and persist after your app has been uninstalled.

  99. // Create the storage directory if it does not exist

  100. if (! mediaStorageDir.exists()){

  101. if (! mediaStorageDir.mkdirs()){

  102.                   Log. d("MyCameraApp", "failed to create directory");

  103. returnnull ;

  104.               }

  105.           }

  106. // Create a media file name

  107.           String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss" ).format(new Date());

  108.           File mediaFile;

  109. if (type == MEDIA_TYPE_IMAGE){

  110.               mediaFile = new File(mediaStorageDir.getPath() + File.separator +

  111. "IMG_"+ timeStamp + ".jpg" );

  112.           } elseif (type == MEDIA_TYPE_VIDEO) {

  113.               mediaFile = new File(mediaStorageDir.getPath() + File.separator +

  114. "VID_"+ timeStamp + ".mp4" );

  115.           } else {

  116. returnnull ;

  117.           }

  118. return mediaFile;

  119.       }

  120. }


本文出自 “whithin's” 博客,请务必保留此出处http://whithin.blog.51cto.com/690417/1058972