android獲得手機照片,攝像,拍照,錄音等功能並將其轉為字符串


  1. 今天在項目中,需要獲得手機本地相冊中的照片路徑,拍照並獲得拍照后的路徑,攝像並獲得攝像后的路徑,錄音並獲得錄音后的路徑,並將相應文件轉為string格式以便利用json上傳至服務端。
  2. 參考了網上的一些材料,在這里個人覺得比較好的一個資料是:http://www.oschina.net/code/snippet_163910_6069
  3. 在這里做個筆記,也希望能對大家有一點幫助。
  • 第一步:布局文件,對於布局文件我總是做不好,希望大家湊合着
    View Code
      1 <?xml version="1.0" encoding="utf-8"?>
      2 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
      3     android:layout_width="match_parent"
      4     android:layout_height="match_parent"
      5     android:orientation="vertical"
      6     android:scrollbars="vertical" >
      7 
      8     <LinearLayout
      9         android:layout_width="match_parent"
     10         android:layout_height="match_parent"
     11         android:orientation="vertical" >
     12 
     13         <LinearLayout
     14             android:layout_width="fill_parent"
     15             android:layout_height="wrap_content"
     16             android:orientation="vertical" >
     17 
     18             <!-- 用戶名 -->
     19 
     20             <LinearLayout
     21                 android:layout_width="fill_parent"
     22                 android:layout_height="wrap_content"
     23                 android:layout_marginBottom="10px"
     24                 android:layout_marginTop="160px"
     25                 android:orientation="horizontal" >
     26 
     27                 <TextView
     28                     android:layout_width="wrap_content"
     29                     android:layout_height="wrap_content"
     30                     android:text="用  戶  名" />
     31 
     32                 <EditText
     33                     android:id="@+id/username"
     34                     android:layout_width="fill_parent"
     35                     android:layout_height="wrap_content"
     36                     android:layout_marginLeft="5px" />
     37             </LinearLayout>
     38 
     39             <!-- 身份證 -->
     40 
     41             <LinearLayout
     42                 android:layout_width="fill_parent"
     43                 android:layout_height="wrap_content"
     44                 android:layout_marginBottom="10px"
     45                 android:orientation="horizontal" >
     46 
     47                 <TextView
     48                     android:layout_width="wrap_content"
     49                     android:layout_height="wrap_content"
     50                     android:text="身  份  證" />
     51 
     52                 <EditText
     53                     android:id="@+id/identifi"
     54                     android:layout_width="fill_parent"
     55                     android:layout_height="wrap_content"
     56                     android:layout_marginLeft="5px" />
     57             </LinearLayout>
     58 
     59             <LinearLayout
     60                 android:layout_width="fill_parent"
     61                 android:layout_height="wrap_content"
     62                 android:orientation="horizontal" >
     63 
     64                 <TextView
     65                     android:layout_width="wrap_content"
     66                     android:layout_height="wrap_content"
     67                     android:text="信息" />
     68 
     69                 <EditText
     70                     android:id="@+id/alarminfo"
     71                     android:layout_width="fill_parent"
     72                     android:layout_height="wrap_content"
     73                     android:layout_marginLeft="5px"
     74                     android:lines="6" />
     75             </LinearLayout>
     76         </LinearLayout>
     77 
     78         <LinearLayout
     79             android:layout_width="fill_parent"
     80             android:layout_height="wrap_content"
     81             android:orientation="horizontal" >
     82 
     83             <Button
     84                 android:id="@+id/picbutton"
     85                 android:layout_width="wrap_content"
     86                 android:layout_height="wrap_content"
     87                 android:text="本地上傳" />
     88 
     89             <EditText
     90                 android:id="@+id/pictext"
     91                 android:layout_width="fill_parent"
     92                 android:layout_height="wrap_content"
     93                 android:layout_marginLeft="5px" />
     94         </LinearLayout>
     95 
     96         <LinearLayout
     97             android:layout_width="fill_parent"
     98             android:layout_height="wrap_content"
     99             android:orientation="horizontal" >
    100 
    101             <Button
    102                 android:id="@+id/photobutton"
    103                 android:layout_width="wrap_content"
    104                 android:layout_height="wrap_content"
    105                 android:text="拍照上傳" />
    106 
    107             <EditText
    108                 android:id="@+id/phototext"
    109                 android:layout_width="fill_parent"
    110                 android:layout_height="wrap_content"
    111                 android:layout_marginLeft="5px" />
    112         </LinearLayout>
    113 
    114         <LinearLayout
    115             android:layout_width="fill_parent"
    116             android:layout_height="wrap_content"
    117             android:orientation="horizontal" >
    118 
    119             <Button
    120                 android:id="@+id/mp3buttonbegin"
    121                 android:layout_width="wrap_content"
    122                 android:layout_height="wrap_content"
    123                 android:text="錄音開始" />
    124 
    125             <Button
    126                 android:id="@+id/vediobutton"
    127                 android:layout_width="wrap_content"
    128                 android:layout_height="wrap_content"
    129                 android:text="視頻錄制" />
    130 
    131             <Button
    132                 android:id="@+id/submit"
    133                 android:layout_width="wrap_content"
    134                 android:layout_height="wrap_content"
    135                 android:layout_marginLeft="90px"
    136                 android:layout_marginRight="5px"
    137                 android:text="提  交" />
    138         </LinearLayout>
    139     </LinearLayout>
    140 
    141 </ScrollView>
  • 第二步:主界面Activity
    View Code
      1 public class MppspPhoneAlarmAct extends ActivityGroup
      2 {
      3 
      4     /* 用來標識請求照相功能的activity */
      5     private static final int CAMERA_WITH_DATA = 1001;
      6     /* 用來標識請求gallery的activity */
      7     private static final int PHOTO_PICKED_WITH_DATA = 1002;
      8     // 用來標示請求錄音功能的activity
      9     private static final int RESULT_CAPTURE_RECORDER_SOUND = 1003;
     10     // 用來標示請求視頻錄制功能的activity
     11     private static final int REQUEST_CODE_TAKE_VIDEO = 1004;
     12     // 手機圖片路徑
     13     private String imagePath = "";
     14     // 拍照路徑
     15     private String strImgPath = "";
     16     // 獲得用戶名的文本框
     17     private EditText mNameText = null;
     18     // 獲得省份證的文本框
     19     private EditText mIdText = null;
     20     // 獲得信息的文本框
     21     private EditText mAlarmInfoText = null;
     22     // 文件路徑文本框
     23     private EditText mPictext = null;
     24     // 多媒體設備
     25     private MediaRecorder mRecod;
     26     // 錄音文件的路徑
     27     private String strRecorderPath = "";
     28     // 攝制視頻文件的路徑
     29     private String strVideoPath = "";
     30 
     31     @Override
     32     protected void onCreate(Bundle savedInstanceState)
     33     {
     34         super.onCreate(savedInstanceState);
     35         this.requestWindowFeature(Window.FEATURE_NO_TITLE);
     36         this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
     37                 WindowManager.LayoutParams.FLAG_FULLSCREEN);
     38         this.setContentView(R.layout.mppsp_phonealarm);
     39         mNameText = (EditText) this.findViewById(R.id.username);
     40         mIdText = (EditText) this.findViewById(R.id.identifi);
     41         mAlarmInfoText = (EditText) this.findViewById(R.id.alarminfo);
     42         // 手機圖片
     43         mPictext = (EditText) findViewById(R.id.pictext);
     44         // 上傳材料的按鈕
     45         Button mpicbutton = (Button) findViewById(R.id.picbutton);
     46         mpicbutton.setOnClickListener(new View.OnClickListener()
     47         {
     48 
     49             public void onClick(View v)
     50             {
     51                 Intent intent = new Intent();
     52                 /* 開啟Pictures畫面Type設定為image */
     53                 intent.setType("image/*");
     54                 /* 使用Intent.ACTION_GET_CONTENT這個Action */
     55                 intent.setAction(Intent.ACTION_GET_CONTENT);
     56                 /* 取得相片后返回本畫面 */
     57                 startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
     58             }
     59         });
     60         // 拍照按鈕
     61         Button mPhotobutton = (Button) findViewById(R.id.photobutton);
     62         // 視頻攝制按鈕
     63         Button mVediobutton = (Button) findViewById(R.id.vediobutton);
     64         // 注冊監聽事件
     65         mPhotobutton.setOnClickListener(new View.OnClickListener()
     66         {
     67 
     68             public void onClick(View v)
     69             {
     70                 Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     71                 // 存放照片的文件夾
     72                 strImgPath = Environment.getExternalStorageDirectory().toString() + "/media/";
     73                 // 照片命名
     74                 String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
     75                 File out = new File(strImgPath);
     76                 if (!out.exists())
     77                 {
     78                     // 創建文件夾
     79                     out.mkdirs();
     80                 }
     81                 out = new File(strImgPath, fileName);
     82                 // 該照片的絕對路徑
     83                 strImgPath = strImgPath + fileName;
     84                 Uri uri = Uri.fromFile(out);
     85                 imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
     86                 imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
     87                 startActivityForResult(imageCaptureIntent, CAMERA_WITH_DATA);
     88             }
     89         });
     90         // 錄音開始按鈕
     91         Button mBeginBtn = (Button) this.findViewById(R.id.mp3buttonbegin);
     92         // 錄音結束按鈕
     93         // 錄音按鈕事件監聽
     94         mBeginBtn.setOnClickListener(new OnClickListener()
     95         {
     96 
     97             public void onClick(View v)
     98             {
     99                 String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    100                 File dir = new File("/sdcard/arm/");
    101                 File mFile = null;
    102                 if (!dir.exists())
    103                 {
    104                     dir.mkdir();
    105                 }
    106                 // 設置輸出路徑
    107                 try
    108                 {
    109                     mFile = File.createTempFile(fileName + "-", ".mp3", dir);
    110                 }
    111                 catch (IOException e1)
    112                 {
    113                     e1.printStackTrace();
    114                 }
    115                 mRecod = new MediaRecorder();
    116                 // 設置音源
    117                 mRecod.setAudioSource(AudioSource.DEFAULT);
    118                 // 輸出格式
    119                 mRecod.setOutputFormat(OutputFormat.DEFAULT);
    120                 mRecod.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    121                 try
    122                 {
    123                     Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    124                     intent.setType("audio/amr");
    125                     startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);
    126                     mRecod.prepare();
    127                     mRecod.start();
    128                 }
    129                 catch (Exception e)
    130                 {
    131                     e.printStackTrace();
    132                 }
    133             }
    134         });
    135         // 視頻錄制按鈕監聽事件
    136         mVediobutton.setOnClickListener(new OnClickListener()
    137         {
    138 
    139             public void onClick(View v)
    140             {
    141                 Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    142                 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
    143                 startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
    144             }
    145         });
    146     }
    147     @Override
    148     protected void onActivityResult(int requestCode, int resultCode, Intent data)
    149     {
    150         switch (requestCode)
    151         {
    152         // 本地圖片
    153             case PHOTO_PICKED_WITH_DATA:
    154                 Uri mUri = data.getData();
    155                 String[] projection = { MediaStore.Images.Media.DATA };
    156                 Cursor actualimagecursor = managedQuery(mUri, projection, null, null, null);
    157                 int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    158                 actualimagecursor.moveToFirst();
    159                 // 獲取文件路徑,方便上傳文件等
    160                 imagePath = actualimagecursor.getString(actual_image_column_index);
    161                 mPictext.setText(imagePath);
    162                 break;
    163             // 照相機拍照
    164             case CAMERA_WITH_DATA:
    165                 EditText mphototext = (EditText) findViewById(R.id.phototext);
    166                 mphototext.setText(strImgPath);
    167                 break;
    168             // 錄音
    169             case RESULT_CAPTURE_RECORDER_SOUND:
    170                 if (resultCode == RESULT_OK)
    171                 {
    172                     Uri uriRecorder = data.getData();
    173                     Cursor mCusor = this.getContentResolver().query(uriRecorder, null, null, null, null);
    174                     if (mCusor.moveToNext())
    175                     {
    176                         // _data:文件的絕對路徑 ,_display_name:文件名
    177                         strRecorderPath = mCusor.getString(mCusor.getColumnIndex("_data"));
    178                         Toast.makeText(this, strRecorderPath, Toast.LENGTH_SHORT).show();
    179                     }
    180                 }
    181                 break;
    182             // 視頻攝制
    183             case REQUEST_CODE_TAKE_VIDEO:
    184                 if (resultCode == RESULT_OK)
    185                 {
    186                     Uri uriVideo = data.getData();
    187                     Cursor cursor = this.getContentResolver().query(uriVideo, null, null, null, null);
    188                     if (cursor.moveToNext())
    189                     {
    190                         strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
    191                         Toast.makeText(this, strVideoPath, Toast.LENGTH_SHORT).show();
    192                     }
    193                 }
    194                 break;
    195         }
    196         super.onActivityResult(requestCode, resultCode, data);
    197     }
    198 }
  • 第三步:將文件轉為String對象
    View Code
     1 public static String readStream(String path)  throws Exception
     2     {
     3         File file = new File(path);
     4         InputStream inStream = new FileInputStream(file);
     5         byte[] buffer = new byte[1024];
     6         int len = -1;
     7         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     8         while ((len = inStream.read(buffer)) != -1)
     9         {
    10             outStream.write(buffer, 0, len);
    11         }
    12         byte[] data = outStream.toByteArray();
    13         String mImage = new String(Base64.encode(data));
    14         outStream.close();
    15         inStream.close();
    16         return mImage;
    17     }

     

  • 將String轉為file
    View Code
     1 public static boolean string2File(String res, String filePath)
     2     {
     3         boolean flag = true;
     4         BufferedReader bufferedReader = null;
     5         BufferedWriter bufferedWriter = null;
     6         try
     7         {
     8             File distFile = new File(filePath);
     9             if (!distFile.getParentFile().exists())
    10                 distFile.getParentFile().mkdirs();
    11             bufferedReader = new BufferedReader(new StringReader(res));
    12             bufferedWriter = new BufferedWriter(new FileWriter(distFile));
    13             char buf[] = new char[1024]; // 字符緩沖區
    14             int len;
    15             while ((len = bufferedReader.read(buf)) != -1)
    16             {
    17                 bufferedWriter.write(buf, 0, len);
    18             }
    19             bufferedWriter.flush();
    20             bufferedReader.close();
    21             bufferedWriter.close();
    22         }
    23         catch (IOException e)
    24         {
    25             e.printStackTrace();
    26             flag = false;
    27             return flag;
    28         }
    29         finally
    30         {
    31             if (bufferedReader != null)
    32             {
    33                 try
    34                 {
    35                     bufferedReader.close();
    36                 }
    37                 catch (IOException e)
    38                 {
    39                     e.printStackTrace();
    40                 }
    41             }
    42         }
    43         return flag;
    44     }

    最后注意的一點是別忘了在AndroidManifest.xml中添加相應的權限:

    View Code
         <!-- 在SDCard中創建與刪除文件權限 -->  
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
        <!-- 申請使用攝像頭的權限 -->  
        <uses-permission android:name="android.permission.CAMERA"/>  
        <!-- 申請錄音權限 -->
        <uses-permission android:name="android.permission.RECORD_AUDIO"/>
        <!--SDCard存儲文件的權限  -->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
  • 到此功能基本完成了。

  1. 在這里在記錄一點題外的東西,比較細微的東西,就是利用java的反射機制動態調用相應方法。
    • 客戶端傳遞服務服務id,服務端根據服務id解析出類名和方法名,並執行改方法。
       1 public void invoke(String mClassName,String mMethodName)
       2     {
       3          //動態調用
       4          Class   clazz=Class.forName(mClassName);
       5         //調用沒有參數的構造函數得到一個實例
       6          Object   instance=clazz.newInstance();
       7         //第二個參數表示方法參數的類型 
       8          Method   method=clazz.getDeclaredMethod(mMethodName, String.class);
       9         //第一個參數是類對象,后面傳遞運行這個方法的參數 
      10          mRetunInfo = (String)method.invoke(instance,mDate);
      11     }

       

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM