Android開發: 通過Intent 調用Camera應用 sample code

Sample code,實現簡單應用界面包含兩個button,點擊button 分別打開camera, 和cameroder,主界面如下圖所示

1. 在AndroidManifest.xml文件中包含camera 相關的權限

  1. AndroidManifest.xml 
  2.  
  3. <?xml version= "1.0" encoding ="utf-8"?> 
  4. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  5.     package="android.study.sample" 
  6.     android:versionCode= "1" 
  7.     android:versionName= "1.0" > 
  8.  
  9.     <uses-sdk android:minSdkVersion= "15" /> 
  10.     <uses-permission android:name= "android.permission.CAMERA" /> 
  11.     <uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" /> 
  12.  
  13.     <application 
  14.         android:icon="@drawable/ic_launcher" 
  15.         android:label="@string/app_name" > 
  16.         <activity 
  17.             android:name="android.study.sample.CameraIntentActivity" 
  18.             android:label="@string/app_name" > 
  19.             <intent-filter> 
  20.                 <action android:name="android.intent.action.MAIN" /> 
  21.  
  22.                 <category android:name="android.intent.category.LAUNCHER" /> 
  23.             </intent-filter> 
  24.         </activity> 
  25.     </application > 
  26.  
  27. </manifest> 
  28.  

2.在主界面的layout文件中添加兩個button,分別負責打開拍照和錄視頻的應用

  1. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
  2. res/layout/main.xml 
  3.  
  4. <? xml version= "1.0" encoding = "utf-8"?> 
  5. < RelativeLayout xmlns:android ="http://schemas.android.com/apk/res/android" 
  6.     android:layout_width= "match_parent" 
  7.     android:layout_height= "match_parent" > 
  8.  
  9.     <Button 
  10.         android:id ="@+id/buttonTakePic" 
  11.         android:layout_width ="match_parent" 
  12.         android:layout_height ="wrap_content" 
  13.         android:layout_alignParentTop ="true" 
  14.         android:layout_centerHorizontal ="true" 
  15.         android:layout_marginTop ="100dp" 
  16.         android:text ="takepicture" /> 
  17.  
  18.     <Button 
  19.         android:id ="@+id/buttonRecordVideo" 
  20.         android:layout_width ="match_parent" 
  21.         android:layout_height ="wrap_content" 
  22.         android:layout_alignParentLeft ="true" 
  23.         android:layout_alignParentTop ="true" 
  24.         android:layout_marginTop ="42dp" 
  25.         android:text ="recordvideo" /> 
  26.  
  27. </ RelativeLayout> 
  28.  
  29.  

 

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.  
  4.  
  5. package android.study.sample; 
  6.  
  7. import java.io.File; 
  8. import java.text.SimpleDateFormat; 
  9. import java.util.Date; 
  10.  
  11.  
  12. import android.app.Activity; 
  13. import android.content.Intent; 
  14. import android.net.Uri; 
  15. import android.os.Bundle; 
  16. import android.os.Environment; 
  17. import android.provider.MediaStore; 
  18. import android.util.Log; 
  19. import android.view.View; 
  20. import android.view.View.OnClickListener; 
  21. import android.widget.Button; 
  22. import android.widget.Toast; 
  23.  
  24. public class CameraIntentActivity extends Activity{ 
  25.  
  26.         
  27.         public static final int MEDIA_TYPE_IMAGE = 1
  28.         public static final int MEDIA_TYPE_VIDEO = 2
  29.         
  30.         private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100
  31.         private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200
  32.         private Uri fileUri ; 
  33.         
  34.        Button takePicureButton; 
  35.        Button recordVideoButton; 
  36.         
  37.        OnClickListener cameraButtonListenser =  new OnClickListener(){ 
  38.  
  39.                public void onClick(View view) { 
  40.                       // TODO Auto-generated method stub 
  41.                       
  42.                      Intent intent = null
  43.                       
  44.                       if(((Button)view).equals(takePicureButton )){ 
  45.                             
  46.                          // create Intent to take a picture and return control to the calling application 
  47.                          intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
  48.  
  49.                          fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the p_w_picpath 
  50.                          intent.putExtra(MediaStore. EXTRA_OUTPUT, fileUri ); // set the p_w_picpath file name 
  51.                          
  52.                         // start the video record Intent 
  53.                          startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE ); 
  54.                             
  55.                      } else if (((Button)view).equals(recordVideoButton)){ 
  56.                             
  57.                          intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); 
  58.  
  59.                          fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video 
  60.                          intent.putExtra(MediaStore. EXTRA_OUTPUT, fileUri ); // set the video file name 
  61.                          
  62.                          
  63.                          startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE ); 
  64.                      } 
  65.               } 
  66.                
  67.        }; 
  68.  
  69.         @Override 
  70.         public void onCreate(Bundle savedInstanceState) { 
  71.            super.onCreate(savedInstanceState); 
  72.            setContentView(R.layout. main); 
  73.            
  74.            takePicureButton = (Button)findViewById(R.id.buttonTakePic); 
  75.            recordVideoButton = (Button)findViewById(R.id.buttonRecordVideo); 
  76.            
  77.            
  78.            takePicureButton.setOnClickListener(cameraButtonListenser ); 
  79.            recordVideoButton.setOnClickListener(cameraButtonListenser ); 
  80.  
  81.        } 
  82.         
  83.         @Override 
  84.         protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  85.            if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { 
  86.                if (resultCode == RESULT_OK) { 
  87.                    // Image captured and saved to fileUri specified in the Intent 
  88.                       
  89.                       
  90.                       if(data!=null ){ 
  91.                              
  92.                           Toast. makeText(this"Image saved to:\n" + 
  93.                                    data.getData().toString(), Toast.LENGTH_LONG).show();                       
  94.                      } else{                       
  95.                             System. out.println("can't get any data!!!" ); 
  96.                      } 
  97.                
  98.                } else if (resultCode == RESULT_CANCELED) { 
  99.                    // User cancelled the p_w_picpath capture 
  100.                } else { 
  101.                    // Image capture failed, advise user 
  102.                } 
  103.            } 
  104.  
  105.            if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) { 
  106.                if (resultCode == RESULT_OK) { 
  107.                    // Video captured and saved to fileUri specified in the Intent 
  108.                       if(data!=null ){ 
  109.                              
  110.                           Toast. makeText(this"Image saved to:\n" + 
  111.                                    data.getData().toString(), Toast.LENGTH_LONG).show(); 
  112.                              
  113.                      } else
  114.                              
  115.                             System. out.println("can't get any data!!!" ); 
  116.  
  117.                      } 
  118.                } else if (resultCode == RESULT_CANCELED) { 
  119.                    // User cancelled the video capture 
  120.                } else { 
  121.                    // Video capture failed, advise user 
  122.                } 
  123.            } 
  124.        } 
  125.         
  126.         
  127.         /** Create a file Uri for saving an p_w_picpath or video */ 
  128.         private static Uri getOutputMediaFileUri(int type){ 
  129.              return Uri.fromFile( getOutputMediaFile(type)); 
  130.        } 
  131.  
  132.         /** Create a File for saving an p_w_picpath or video */ 
  133.         private static File getOutputMediaFile(int type){ 
  134.            // To be safe, you should check that the SDCard is mounted 
  135.            // using Environment.getExternalStorageState() before doing this. 
  136.  
  137.            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( 
  138.                      Environment. DIRECTORY_PICTURES), "MyCameraApp" ); 
  139.            // This location works best if you want the created p_w_picpaths to be shared 
  140.            // between applications and persist after your app has been uninstalled. 
  141.  
  142.            // Create the storage directory if it does not exist 
  143.            if (! mediaStorageDir.exists()){ 
  144.                if (! mediaStorageDir.mkdirs()){ 
  145.                    Log. d("MyCameraApp""failed to create directory"); 
  146.                    return null ; 
  147.                } 
  148.            } 
  149.  
  150.            // Create a media file name 
  151.            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss" ).format(new Date()); 
  152.            File mediaFile; 
  153.            if (type == MEDIA_TYPE_IMAGE){ 
  154.                mediaFile = new File(mediaStorageDir.getPath() + File.separator + 
  155.                "IMG_"+ timeStamp + ".jpg" ); 
  156.            } else if (type == MEDIA_TYPE_VIDEO) { 
  157.                mediaFile = new File(mediaStorageDir.getPath() + File.separator + 
  158.                "VID_"+ timeStamp + ".mp4" ); 
  159.            } else { 
  160.                return null ; 
  161.            } 
  162.  
  163.            return mediaFile; 
  164.        } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章