• 安卓Service拍照


    1. package com.example.phoneguard.service;
    2. import android.app.Service;
    3. import android.content.Context;
    4. import android.content.Intent;
    5. import android.content.pm.PackageManager;
    6. import android.graphics.Bitmap;
    7. import android.graphics.BitmapFactory;
    8. import android.graphics.Matrix;
    9. import android.hardware.Camera;
    10. import android.os.Build;
    11. import android.os.Environment;
    12. import android.os.IBinder;
    13. import android.util.Log;
    14. import android.view.SurfaceHolder;
    15. import android.view.SurfaceView;
    16. import android.view.WindowManager;
    17. import android.widget.Toast;
    18. import java.io.File;
    19. import java.io.FileOutputStream;
    20. import java.io.IOException;
    21. import java.text.SimpleDateFormat;
    22. import java.util.Date;
    23. import java.util.Iterator;
    24. import java.util.List;
    25. import java.util.Locale;
    26. public class BackgroundPhoto extends Service implements SurfaceHolder.Callback {
    27. private static BackgroundPhoto instance;
    28. private int caremaid;
    29. public BackgroundPhoto() {
    30. }
    31. public BackgroundPhoto(int caremaid) {
    32. this.caremaid = caremaid;
    33. }
    34. public static BackgroundPhoto getInstance(int caremaid) {
    35. if (instance == null) {
    36. instance = new BackgroundPhoto(caremaid);
    37. }
    38. return instance;
    39. }
    40. private WindowManager windowManager;
    41. private SurfaceView surfaceView;
    42. private Camera camera = null;
    43. String TAG = "BackgroundPhoto";
    44. Context mContext;
    45. private Camera.Parameters mParameters;
    46. @Override
    47. public void onCreate() {
    48. mContext = this;
    49. // Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
    50. windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
    51. surfaceView = new SurfaceView(this);
    52. WindowManager.LayoutParams params = new WindowManager.LayoutParams();
    53. params.width = 1;
    54. params.height = 1;
    55. params.alpha = 0;
    56. //检查版本,注意当type为TYPE_APPLICATION_OVERLAY时,铺满活动窗口,但在关键的系统窗口下面,如状态栏或IME
    57. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    58. params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
    59. } else {
    60. params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
    61. }
    62. // 屏蔽点击事件
    63. params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
    64. | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
    65. | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
    66. windowManager.addView(surfaceView, params);
    67. surfaceView.getHolder().addCallback(this);
    68. }
    69. // Method called right after Surface created (initializing and starting MediaRecorder)
    70. @Override
    71. public void surfaceCreated(SurfaceHolder surfaceHolder) {
    72. /* camera = Camera.open();
    73. camera.unlock();*/
    74. initCamera();
    75. }
    76. // 初始化摄像头
    77. private void initCamera() {
    78. // 如果存在摄像头
    79. if (checkCameraHardware(mContext.getApplicationContext())) {
    80. // 获取摄像头(首选前置,无前置选后置)
    81. if (openFacingFrontCamera()) {
    82. Log.i(TAG, "openCameraSuccess");
    83. // 进行对焦
    84. autoFocus();
    85. } else {
    86. Log.i(TAG, "openCameraFailed");
    87. }
    88. }
    89. }
    90. // 对焦并拍照
    91. private void autoFocus() {
    92. try {
    93. // 因为开启摄像头需要时间,这里让线程睡两秒
    94. Thread.sleep(1000);
    95. } catch (InterruptedException e) {
    96. e.printStackTrace();
    97. }
    98. startPreview();
    99. // 自动对焦
    100. camera.autoFocus(myAutoFocus);
    101. // 对焦后拍照
    102. // camera.unlock();
    103. camera.takePicture(null, null, myPicCallback);
    104. }
    105. private void startPreview() {
    106. setCameraParameters();
    107. camera.startPreview();
    108. }
    109. /**
    110. * 设置Camera参数
    111. * 设置预览界面的宽高,图片保存的宽、高
    112. */
    113. private void setCameraParameters() {
    114. if (camera != null) {
    115. Log.d(TAG, "setCameraParameters >> begin. mCamera != null");
    116. if (mParameters == null) {
    117. mParameters = camera.getParameters();
    118. }
    119. int PreviewWidth = 0;
    120. int PreviewHeight = 0;
    121. List sizeList = mParameters.getSupportedPreviewSizes();
    122. if (sizeList.size() > 1) {
    123. Iterator itor = sizeList.iterator();
    124. while (itor.hasNext()) {
    125. Camera.Size cur = itor.next();
    126. if (cur.width >= PreviewWidth
    127. && cur.height >= PreviewHeight) {
    128. PreviewWidth = cur.width;
    129. PreviewHeight = cur.height;
    130. break;
    131. }
    132. }
    133. } else if (sizeList.size() == 1) {
    134. Camera.Size size = sizeList.get(0);
    135. PreviewWidth = size.width;
    136. PreviewHeight = size.height;
    137. }
    138. mParameters.setPreviewSize(PreviewWidth, PreviewHeight); //获得摄像区域的大小
    139. mParameters.setPictureSize(PreviewWidth, PreviewHeight);//设置拍出来的屏幕大小
    140. try {
    141. camera.setParameters(mParameters);
    142. } catch (Exception e) {
    143. Camera.Parameters parameters = camera.getParameters();// 得到摄像头的参数
    144. camera.setParameters(parameters);
    145. }
    146. } else {
    147. Log.e(TAG, "setCameraParameters >> mCamera == null!!");
    148. }
    149. }
    150. // 判断是否存在摄像头
    151. private boolean checkCameraHardware(Context context) {
    152. if (context.getPackageManager().hasSystemFeature(
    153. PackageManager.FEATURE_CAMERA)) {
    154. // 设备存在摄像头
    155. return true;
    156. } else {
    157. // 设备不存在摄像头
    158. return false;
    159. }
    160. }
    161. // 得到后置摄像头
    162. private boolean openFacingFrontCamera() {
    163. // 尝试开启前置摄像头
    164. Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    165. camera = Camera.open(camIdx);
    166. try {
    167. // 这里的myCamera为已经初始化的Camera对象
    168. camera.setPreviewDisplay(surfaceView.getHolder());
    169. } catch (IOException e) {
    170. e.printStackTrace();
    171. camera.stopPreview();
    172. camera.release();
    173. camera = null;
    174. }
    175. camera.startPreview();
    176. return true;
    177. }
    178. // 自动对焦回调函数(空实现)
    179. private Camera.AutoFocusCallback myAutoFocus = new Camera.AutoFocusCallback() {
    180. @Override
    181. public void onAutoFocus(boolean success, Camera camera) {
    182. }
    183. };
    184. // 拍照成功回调函数
    185. private Camera.PictureCallback myPicCallback = new Camera.PictureCallback() {
    186. @Override
    187. public void onPictureTaken(byte[] data, Camera camera) {
    188. // 完成拍照后关闭Activity
    189. // 将得到的照片进行270°旋转,使其竖直
    190. Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    191. Matrix matrix = new Matrix();
    192. matrix.preRotate(90);
    193. bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
    194. bitmap.getHeight(), matrix, true);
    195. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
    196. String imageFileName = "Photo" + dateFormat.format(new Date(System.currentTimeMillis())) + ".jpg";
    197. // 创建并保存图片文件
    198. File pictureFile = new File(Environment.getExternalStorageDirectory() + "/1/", imageFileName);
    199. try {
    200. FileOutputStream fos = new FileOutputStream(pictureFile);
    201. bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
    202. fos.close();
    203. } catch (Exception error) {
    204. Toast.makeText(mContext, "拍照失败", Toast.LENGTH_SHORT)
    205. .show();
    206. Log.i(TAG, "保存照片失败" + error.toString());
    207. error.printStackTrace();
    208. camera.stopPreview();
    209. camera.release();
    210. camera = null;
    211. }
    212. Log.i(TAG, "获取照片成功" + pictureFile.getAbsolutePath());
    213. Toast.makeText(mContext, "获取照片成功", Toast.LENGTH_SHORT)
    214. .show();
    215. camera.stopPreview();
    216. camera.release();
    217. camera = null;
    218. }
    219. };
    220. // Stop recording and remove SurfaceView
    221. @Override
    222. public void onDestroy() {
    223. camera.release();
    224. windowManager.removeView(surfaceView);
    225. }
    226. @Override
    227. public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
    228. }
    229. @Override
    230. public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    231. }
    232. @Override
    233. public IBinder onBind(Intent intent) {
    234. return null;
    235. }
    236. }

    然后start此service就可以了

  • 相关阅读:
    【码蹄集新手村 600 题】判断俩个矩阵是否相等,以及 exit 与 return 的区别
    时序预测 | Pytorch实现TCN-Transformer的时间序列预测
    C++面向对象——类与对象
    Linux-命令大全
    数字化采购:企企通、商越同行不同路
    Ansys Lumerical|菲涅尔透镜设计
    【项目笔记】java微服务:黑马头条(day03)
    ClickHouse SQL操作
    学习pytorch6 torchvision中的数据集使用
    【数据结构-图】图的常用算法
  • 原文地址:https://blog.csdn.net/guodashen007/article/details/132891417