Android プログラミング デバイス制御2
カメラ
まず、Manifest.xmlの変更。
<uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ~省略~ android:screenOrientation="landscape" >
Acitvityのほう。
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // フルスクリーンの設定 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(new CameraView(this)); }
Viewのほう。
public class CameraView extends TextureView implements TextureView.SurfaceTextureListener, Camera.PictureCallback{ private Camera camera; // カメラ public CameraView(Context context){ super(context); // テクスチャービューのリスナー登録 setSurfaceTextureListener(this); } @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { // カメラの初期化 try{ camera = Camera.open(); if(camera == null) camera = Camera.open(0); camera.setPreviewTexture(surface); camera.startPreview(); }catch (Exception e){ } } // サーフェステクスチャサイズ変更時に呼ばれる @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } // サーフェステクスチャ更新時に呼ばれるs @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } // サーフェステクスチャに呼ばれる @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { camera.setPreviewCallback(null); camera.stopPreview(); camera.release(); camera = null; return true; } // タッチ時に呼ばれる @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ // カメラのスクリーンショットの取得 camera.takePicture(null,null,this); } return true; } public void onPictureTaken(byte[] data, Camera camera){ try{ // ファイル名の生成 SimpleDateFormat format = new SimpleDateFormat( "'IMG'_yyyyMdd_HHmmss'.jpg'", Locale.getDefault()); String fileName = format.format(new Date(System.currentTimeMillis())); // SDカードへの保存 String path = Environment.getExternalStorageDirectory()+"/"+fileName; saveToSD(data,path); // ギャラリーへの登録 MediaScannerConnection.scanFile(this.getContext(), new String[]{path},new String[]{"image/jpeg"},null); toast("撮影完了"); }catch (Exception e){ toast(e.toString()); } // プレビューの再開 camera.startPreview(); } // SDカードへの保存 private void saveToSD(byte[] w,String path) throws Exception{ FileOutputStream out = null; try{ out = new FileOutputStream(path); out.write(w); out.close(); }catch (Exception e){ if(out != null) out.close(); throw e; } } private void toast(String text){ if(text == null) text = ""; Toast.makeText(getContext(),text, Toast.LENGTH_LONG).show(); } }
参考文献
Androidプログラミングバイブル SDK5/4対応 (smart phone programming bible)
- 作者: 布留川英一
- 出版社/メーカー: ソシム
- 発売日: 2015/01/26
- メディア: 単行本
- この商品を含むブログ (2件) を見る