Android实现后台开启服务默默拍照功能

 更新时间:2018年06月10日 11:55:40   作者:Snowball  
这篇文章主要为大家详细介绍了Android实现后台开启服务默默拍照功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android后台开启服务默默拍照的具体代码,供大家参考,具体内容如下

最近项目原因,需要编写一后台运行的程序,在给定时间间隔下进行拍照,关键技术主要是:1、开启服务;2、在不不预览的情况下,进行拍照操作。3、使用AlarmManager进行定时操作。

资源清单如下:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
 package="com.yang.testservice" 
 android:versionCode="1" 
 android:versionName="1.0" > 
 
 <uses-feature android:name="android.hardware.camera" /> 
 <uses-feature android:name="android.hardware.camera.autofocus" /> 
 
 <uses-permission android:name="android.permission.CAMERA" /> 
 <uses-permission android:name="android.permission.FLASHLIGHT" /> 
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
 
 <uses-feature android:name="android.hardware.camera.any" /> 
 
 <uses-sdk 
  android:minSdkVersion="13" 
  android:targetSdkVersion="15" /> 
 
 <application 
  android:icon="@drawable/ic_launcher" 
  android:label="@string/app_name" 
  android:theme="@style/AppTheme" > 
  <activity 
   android:name=".MainActivity" 
   android:label="@string/title_activity_main" > 
   <intent-filter> 
    <action android:name="android.intent.action.MAIN" /> 
 
    <category android:name="android.intent.category.LAUNCHER" /> 
   </intent-filter> 
  </activity> 
 
  <service android:name="com.yang.service.LocalService" /> 
 </application> 
 
</manifest> 

服务代码如下:

package com.yang.service; 
 
import java.io.IOException; 
 
import android.app.AlarmManager; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.hardware.Camera; 
import android.os.Binder; 
import android.os.IBinder; 
import android.util.Log; 
import android.view.SurfaceView; 
import android.widget.Toast; 
 
import com.yang.handle.PhotoHandler; 
import com.yang.testservice.MainActivity; 
import com.yang.testservice.R; 
 
public class LocalService extends Service { 
 
 private AlarmManager am = null; 
 private Camera camera; 
 
 private final IBinder mBinder = new LocalBinder(); 
 
 private NotificationManager mNM; 
 
 private int NOTIFICATION = R.string.local_service_started; 
 
 /** 
  * Class for clients to access. Because we know this service always runs in 
  * the same process as its clients, we don't need to deal with IPC. 
  */ 
 public class LocalBinder extends Binder { 
  public LocalService getService() { 
   return LocalService.this; 
  } 
 
 } 
 
 @Override 
 public void onCreate() { 
  mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
  showNotification(); 
  init(); 
 } 
 
 private void init() { 
  am = (AlarmManager) getSystemService(ALARM_SERVICE); 
 
  camera = openFacingBackCamera(); 
 
  // 注册广播 
  IntentFilter filter = new IntentFilter(); 
  filter.addAction("com.vegetables_source.alarm"); 
  registerReceiver(alarmReceiver, filter); 
 
  Intent intent = new Intent(); 
  intent.setAction("com.vegetables_source.alarm"); 
  PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0); 
 
  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 
    1000 * 10, pi);// 马上开始,每1分钟触发一次 
 } 
 
 @Override 
 public int onStartCommand(Intent intent, int flags, int startId) { 
  Log.i("LocalService", "Received start id " + startId + ": " + intent); 
 
  return START_STICKY; 
 } 
 
 @Override 
 public void onDestroy() { 
  mNM.cancel(NOTIFICATION); 
 
  cancelAlertManager(); 
 
  if (camera != null) { 
   camera.release(); 
   camera = null; 
  } 
 
  Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT) 
    .show(); 
 } 
 
 @Override 
 public IBinder onBind(Intent intent) { 
  return mBinder; 
 } 
 
 /** 
  * Show a notification while this service is running. 
  */ 
 private void showNotification() { 
  CharSequence text = getText(R.string.local_service_started); 
 
  Notification notification = new Notification(R.drawable.stat_running, 
    text, System.currentTimeMillis()); 
 
  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
    new Intent(this, MainActivity.class), 0); 
 
  notification.setLatestEventInfo(this, 
    getText(R.string.local_service_label), text, contentIntent); 
 
  mNM.notify(NOTIFICATION, notification); 
 } 
 
 private void cancelAlertManager() { 
  Intent intent = new Intent(); 
  intent.setAction("com.vegetables_source.alarm"); 
  PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0); 
  am.cancel(pi); 
 
  // 注销广播 
  unregisterReceiver(alarmReceiver); 
 } 
 
 BroadcastReceiver alarmReceiver = new BroadcastReceiver() { 
 
  @Override 
  public void onReceive(Context context, Intent intent) { 
   if ("com.vegetables_source.alarm".equals(intent.getAction())) { 
 
    if (camera != null) { 
     SurfaceView dummy = new SurfaceView(getBaseContext()); 
     try { 
      camera.setPreviewDisplay(dummy.getHolder()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     camera.startPreview(); 
 
     camera.takePicture(null, null, new PhotoHandler( 
       getApplicationContext())); 
    } 
 
   } 
 
  } 
 }; 
 
 private Camera openFacingBackCamera() { 
  Camera cam = null; 
  Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); 
  ; 
  for (int camIdx = 0, cameraCount = Camera.getNumberOfCameras(); camIdx < cameraCount; camIdx++) { 
   Camera.getCameraInfo(camIdx, cameraInfo); 
   if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { 
    try { 
     cam = Camera.open(camIdx); 
    } catch (RuntimeException e) { 
     e.printStackTrace(); 
    } 
   } 
  } 
 
  return cam; 
 } 
} 

进行拍照存储的操作代码如下:

package com.yang.handle; 
 
import java.io.File; 
import java.io.FileOutputStream; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import android.content.Context; 
import android.hardware.Camera; 
import android.hardware.Camera.PictureCallback; 
import android.os.Environment; 
import android.widget.Toast; 
 
public class PhotoHandler implements PictureCallback { 
 
 private final Context context; 
 
 public PhotoHandler(Context context) { 
  this.context = context; 
 } 
 
 @Override 
 public void onPictureTaken(byte[] data, Camera camera) { 
 
  File pictureFileDir = getDir(); 
 
  if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { 
 
   Toast.makeText(context, "Can't create directory to save image.", 
     Toast.LENGTH_LONG).show(); 
   return; 
 
  } 
 
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); 
  String date = dateFormat.format(new Date()); 
  String photoFile = "Picture_" + date + ".jpg"; 
 
  String filename = pictureFileDir.getPath() + File.separator + photoFile; 
 
  File pictureFile = new File(filename); 
  System.out.println("filename is "+ filename); 
 
  try { 
   FileOutputStream fos = new FileOutputStream(pictureFile); 
   fos.write(data); 
   fos.close(); 
   Toast.makeText(context, "New Image saved:" + photoFile, 
     Toast.LENGTH_LONG).show(); 
  } catch (Exception error) { 
   Toast.makeText(context, "Image could not be saved.", 
     Toast.LENGTH_LONG).show(); 
  } 
 } 
 
 private File getDir() { 
  File sdDir = Environment 
   .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
  return new File(sdDir, "ServiceCamera"); 
 } 
} 

项目代码如下:

Android后台开启服务默默拍照

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Android性能优化之plt hook与native线程监控详解

    Android性能优化之plt hook与native线程监控详解

    这篇文章主要为大家介绍了Android性能优化之plt hook与native线程监控详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • Android自定义动画根据控件Y轴旋转动画(仿红包)

    Android自定义动画根据控件Y轴旋转动画(仿红包)

    这篇文章主要介绍了Android自定义动画根据控件Y轴旋转动画(仿红包),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • Android获取手机联系人的方法

    Android获取手机联系人的方法

    这篇文章主要介绍了Android 获取系统联系人信息的实例的相关资料,希望通过本文大家能实现这样的功能,需要的朋友可以参考下
    2017-09-09
  • Android实现自动轮播图效果

    Android实现自动轮播图效果

    这篇文章主要为大家详细介绍了Android实现自动轮播图效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-11-11
  • Android Studio 3.0的下载安装教程

    Android Studio 3.0的下载安装教程

    Android Studio从3.0版本新增了许多功能,当然首当其冲就是从3.0版本新增了对 Kotlin 开发语言的支持,除此之外还有其他一些新功能,今天我们主要来看看如何更新Android Studio 3.0
    2017-10-10
  • Android Jetpack组件DataBinding详解

    Android Jetpack组件DataBinding详解

    这篇文章主要介绍了Android Jetpack组件DataBinding,DataBinding有很多优势,其中最明显是代码更加简洁,可读性会更高。部分和UI控件有关的代码可以在布局文件当中完成,本文给大家详细讲解,需要的朋友可以参考下
    2022-10-10
  • 详解Android截屏事件监听

    详解Android截屏事件监听

    本篇文章主要介绍了Android截屏事件监听,Android系统没有直接对截屏事件监听的接口,本文介绍了2种方法,有兴趣的可以了解一下。
    2016-12-12
  • 两分钟让你彻底明白Android Activity生命周期的详解(图文介绍)

    两分钟让你彻底明白Android Activity生命周期的详解(图文介绍)

    本篇文章是对Android的生命周期进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • Android编程实现禁止系统锁屏与解锁亮屏的方法

    Android编程实现禁止系统锁屏与解锁亮屏的方法

    这篇文章主要介绍了Android编程实现禁止系统锁屏与解锁亮屏的方法,实例分析了Android关闭屏幕、锁屏及解锁屏幕的相关技巧,需要的朋友可以参考下
    2015-12-12
  • Android实现动态高斯模糊效果

    Android实现动态高斯模糊效果

    在Android开发中常常会用到高斯模糊,但有的时候我们可能会需要一个图片以不同的模糊程度展现出来,那如何实现呢,一起通过本文来学习学习吧。
    2016-08-08

最新评论