Keep Running

导航

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     }

       

 

 

posted on 2012-05-23 19:04  Keep Running  阅读(5688)  评论(3编辑  收藏  举报