android-Android拍照、录像、录音代码范例以备后用

package com.cons.dcg.collect;

 

import java.io.File;

import java.text.SimpleDateFormat;

import java.util.*;

import android.app.*;

import android.content.Intent;

import android.database.Cursor;

import android.net.Uri;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Environment;

import android.provider.MediaStore;

import android.view.*;

import android.widget.*;

 

public class RecordActivity extends Activity implements OnClickListener {

 

        private static final int RESULT_CAPTURE_IMAGE = 1;// 照相的requestCode

        private static final int REQUEST_CODE_TAKE_VIDEO = 2;// 摄像的照相的requestCode

        private static final int RESULT_CAPTURE_RECORDER_SOUND = 3;// 录音的requestCode

       

        private String strImgPath = "";// 照片文件绝对路径

        private String strVideoPath = "";// 视频文件的绝对路径

        private String strRecorderPath = "";// 录音文件的绝对路径

 

        @Override

        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                this.setContentView(R.layout.problem_report);

        }

 

        @Override

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                super.onActivityResult(requestCode, resultCode, data);

                switch (requestCode) {

                case RESULT_CAPTURE_IMAGE://拍照

                        if (resultCode == RESULT_OK) {

                                Toast.makeText(this, strImgPath, Toast.LENGTH_SHORT).show();

                        }

                        break;

                case REQUEST_CODE_TAKE_VIDEO://拍摄视频

                        if (resultCode == RESULT_OK) {

                                Uri uriVideo = data.getData();

                                Cursor cursor=this.getContentResolver().query(uriVideo, null, null, null, null);

                                if (cursor.moveToNext()) {

                                        /** _data:文件的绝对路径 ,_display_name:文件名 */

                                        strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));

                                        Toast.makeText(this, strVideoPath, Toast.LENGTH_SHORT).show();

                                }

                        }

                        break;

                case RESULT_CAPTURE_RECORDER_SOUND://录音

                        if (resultCode == RESULT_OK) {

                                Uri uriRecorder = data.getData();

                                Cursor cursor=this.getContentResolver().query(uriRecorder, null, null, null, null);

                                if (cursor.moveToNext()) {

                                        /** _data:文件的绝对路径 ,_display_name:文件名 */

                                        strRecorderPath = cursor.getString(cursor.getColumnIndex("_data"));

                                        Toast.makeText(this, strRecorderPath, Toast.LENGTH_SHORT).show();

                                }

                        } 

                        break;

                }

        }

       

       

 

       /**

        * 照相功能

         */

        private void cameraMethod() {

                Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                strImgPath = Environment.getExternalStorageDirectory().toString() + "/CONSDCGMPIC/";//存放照片的文件夹

                String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";//照片命名

                File out = new File(strImgPath);

                if (!out.exists()) {

                        out.mkdirs();

                }

                out = new File(strImgPath, fileName);

                strImgPath = strImgPath + fileName;//该照片的绝对路径

                Uri uri = Uri.fromFile(out);

                imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

                imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                startActivityForResult(imageCaptureIntent, RESULT_CAPTURE_IMAGE);

 

        }

 

       /**

         * 拍摄视频

         */

        private void videoMethod() {

                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);

                startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);

        }

 

        /**

         * 录音功能

         */

        private void soundRecorderMethod() {

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

                intent.setType("audio/amr");

                startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);

        }

 

        /**

         * 提示信息

         * @param text

         * @param duration

         */

        private void showToast(String text, int duration) {

                Toast.makeText(ProblemReport.this, text, duration).show();

        }

}

源自:http://www.oschina.net/code/snippet_163910_6069

 

 

package com.tangzq;

  

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.List;

 

import com.tangzq.Controllers.DialogController;

import  com.tangzq.Util.FilesUtil;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import android.graphics.PixelFormat;

import android.net.Uri;

import android.os.Build;

import android.os.Bundle;

import android.os.Environment;

import android.provider.MediaStore;

import android.util.Log;

import android.view.Window;

import android.view.WindowManager;

import android.widget.ImageView;

 

/**

 * @author tangzq

 *

 */

public class PhotoAndVideoActivity extends Activity {

    private static final String TAG="PhotoAndVideoActivity";

 ImageView tanmatsuCamera;

 

private static final int REQUEST_CODE_CAMERA_SHOOT = 1;

private static final int REQUEST_CODE_VIDEO_SHOOT=2;

private SharedPreferences sp;

String manu = Build.MANUFACTURER;

Uri pictureUri;

Uri videoUri;

List<String> imageList = new ArrayList<String>();

List<String> videoList=new ArrayList<String>();

String newPath;

String filename;

private List<String> temp;

Bitmap bmp;

String fileUri = Environment.getExternalStorageDirectory()

.getAbsolutePath() + "/Temp/";

    public static final String TAKEN_PICTURE_PREFIX="taken_pic_";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

getWindow().setFormat(PixelFormat.TRANSLUCENT);

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.tanmatsu_camera);

tanmatsuCamera = (ImageView) findViewById(R.id.tanmatsuCamera);

 

temp = getIntent().getStringArrayListExtra("imagefiles");

if (temp != null)

imageList = temp;

        boolean isTakenPicture=getIntent().getBooleanExtra("isTakenPicture", false);

        boolean isShootVideo=getIntent().getBooleanExtra("isShootVideo", false);

        if(isTakenPicture){

        startCamera();

        }

        if(isShootVideo){

        startVideo();

        }

}

 

public void startCamera() {

filename = "template" + (imageList.size() + 1) + ".jpg";

pictureUri = Uri.fromFile(new File(fileUri, filename));

if (sp == null)

sp = getPreferences(MODE_PRIVATE);

Editor editor = sp.edit();

editor.putString("pictureUri", pictureUri.toString());

editor.commit();

//启动照相功能

Intent intent = new Intent();

intent.setAction("android.media.action.IMAGE_CAPTURE");

intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

startActivityForResult(intent, REQUEST_CODE_CAMERA_SHOOT);

}

   public void startVideo(){

  filename="video_template"+System.currentTimeMillis()+".mp4";

  videoUri=Uri.fromFile(new File(fileUri,filename));

  if(sp==null)

  sp=getPreferences(MODE_PRIVATE);

  Editor editor=sp.edit();

  editor.putString("videoUri", videoUri.toString());

   //启动录视频功能

  Intent mIntent = new Intent();

  mIntent.setAction("android.media.action.VIDEO_CAPTURE");

  startActivityForResult(mIntent, REQUEST_CODE_VIDEO_SHOOT);

   }

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

 

Log.e("SHELF ON ACTIVITY RESULT CODE", "RESULT CODE: " + resultCode);

if (requestCode == REQUEST_CODE_CAMERA_SHOOT) {//获得图片

if (resultCode == Activity.RESULT_OK) {

Intent intentResult = new Intent();

Uri resultUri = null;

if (sp == null) {

sp = getPreferences(MODE_PRIVATE);

}

if (intentResult != null && intentResult.getData() != null) {

resultUri = intentResult.getData();

} else {

resultUri = pictureUri;

}

String oldPath = resultUri.getPath();

try {

filename = (imageList.size() + 1) + ".jpg";

newPath = fileUri + filename;

FileOutputStream filedest = new FileOutputStream(newPath);

BitmapFactory.Options bmpOpt = new BitmapFactory.Options();

bmpOpt.inJustDecodeBounds = true;

bmp = BitmapFactory.decodeFile(oldPath, bmpOpt);

int megaPixel = bmpOpt.outWidth * bmpOpt.outHeight;

int sampleSize = 1;

if (bmpOpt.outWidth > 0 && bmpOpt.outHeight > 0) {

while ((megaPixel / (sampleSize * sampleSize)) > 500000) {

sampleSize++;

}

bmpOpt.inJustDecodeBounds = false;

bmpOpt.inSampleSize = sampleSize;

 

Bitmap bmpTemp = BitmapFactory.decodeFile(oldPath,

bmpOpt);

int w = bmpTemp.getWidth();

int h = bmpTemp.getHeight();

 

if (w > h) {

Matrix mtx = new Matrix();

if (w > h) {

mtx.setRotate(90);

}

Bitmap rotatedBMP = Bitmap.createBitmap(bmpTemp, 0,

0, w, h, mtx, true);

tanmatsuCamera.setImageBitmap(rotatedBMP);

rotatedBMP.compress(CompressFormat.JPEG, 100,

filedest);

} else {

tanmatsuCamera.setImageBitmap(bmpTemp);

bmpTemp.compress(CompressFormat.JPEG, 100, filedest);

}

FileInputStream is=new FileInputStream(new File(oldPath));

saveTakenPictureToJacket(is,Main.main.photosDirectoryPathFromLocal);

 

System.gc();

}

filedest.close();

 

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

Log.e("CAMERA ROLL", "Error: " + e.getMessage());

} catch (IOException e) {

// TODO Auto-generated catch block

Log.e("CAMERA ROLL", "Error: " + e.getMessage());

}

imageList.add(newPath);

repeatDialogOpen();

}

else {

if (imageList.size() != 0) {

finishDialogOpen();

} else {

finish();

}

}

}

if(requestCode==REQUEST_CODE_VIDEO_SHOOT){//获得录的视频

if (resultCode == Activity.RESULT_OK){

Log.e(TAG, data.getData().toString());

//Toast.makeText(this, data.getData().toString(), 1).show();

Cursor cursor=this.getContentResolver().query(data.getData(), null, null, null, null);

                if (cursor.moveToNext()) {

                        /** _data:文件的绝对路径 ,_display_name:文件名 */

                        String strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));

                        String videoFilename=cursor.getString(cursor.getColumnIndex("_display_name"));

                        Log.e(TAG, "videoPath:"+strVideoPath);

                       // Toast.makeText(this, strVideoPath, Toast.LENGTH_SHORT).show();

        String oldPath =strVideoPath;

        String newPath=Main.main.moviesDirectoryPathFromLocal+videoFilename;

        //move the video to Movies folder in sdcard

        try {

        FilesUtil.saveFileToFolder(new FileInputStream(oldPath), Main.main.moviesDirectoryPathFromLocal, videoFilename);

        Log.e(TAG, "oldPath:"+oldPath+","+videoList);

        //delete the template mp4 file 

        FilesUtil.deleteFilesInFolder(oldPath);

        videoList.add(newPath);

        //repeatShootVideoDialogOpen();

        Main.main.integrateMovie(Main.main.moviesDirectoryPathFromLocal);

Main.main.getTabHost().setCurrentTab(0);

Shelves.setupShelf();

Shelves.shelfadap.notifyDataSetChanged();

finish();

        } catch (FileNotFoundException e) {

        e.printStackTrace();

        } catch (IOException e) {

        e.printStackTrace();

        }

                }

}

}

}

 

public void saveTakenPictureToJacket(FileInputStream is,String bookJacketDirectoryPath){

BitmapFactory.Options options = new BitmapFactory.Options();

//options.inSampleSize = 8;

options.inSampleSize = 4;

Bitmap bMap = BitmapFactory.decodeStream(new BufferedInputStream(is), null, options);

 

Calendar rightNow = Calendar.getInstance();

String bookJacketName = TAKEN_PICTURE_PREFIX + rightNow.get(Calendar.YEAR) + ""

+ rightNow.get(Calendar.MONTH) + ""

+ rightNow.get(Calendar.DAY_OF_MONTH) + ""

+ rightNow.get(Calendar.HOUR_OF_DAY) + ""

+ rightNow.get(Calendar.MINUTE) + ""

+ rightNow.get(Calendar.SECOND) + ""

+ rightNow.get(Calendar.MILLISECOND);

File bookJacketFile = new File(bookJacketDirectoryPath

+ bookJacketName + ".jpg");

 

if (bookJacketFile.exists()) {

bookJacketFile.delete();

}

 

FileOutputStream fos;

try {

fos = new FileOutputStream(bookJacketFile);

bMap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

public void repeatDialogOpen() {

final AlertDialog dialogDep = new AlertDialog.Builder(this)

.setTitle(getResources().getString(R.string.camera_confirm))

.setMessage(

getResources().getString(

R.string.camera_continue_question))

.setPositiveButton(

getResources().getString(R.string.camera_continue),

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface di,

int whichButton) {

startCamera();

}

})

.setNegativeButton(

getResources().getString(R.string.camera_end),

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface di,

int whichButton) {

finishDialogOpen();

}

}).create();

dialogDep.show();

}

 

public void finishDialogOpen() {

if (Main.main.create == true) {

DialogController dialog = new DialogController(TanmatsuCamera.this,

imageList);

dialog.displayDialog(R.layout.exportoptions, getResources()

.getString(R.string.Export_Option));

} else {

Intent intent = new Intent(Shelves.shelves, ImageList.class);

intent.putExtra("name", "");

intent.putStringArrayListExtra("imagefiles",

(ArrayList<String>) imageList);

Shelves.shelves.startActivityForResult(intent,

Main.main.CREATE_EBOOK);

finish();

}

}

}

posted @ 2013-06-12 22:06  火腿骑士  阅读(393)  评论(0编辑  收藏  举报