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后台开启服务默默拍照

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

(0)

相关推荐

  • android 拍照和上传的实现代码

    复制代码 代码如下: import java.io.ByteArrayOutputStream;   import java.io.File;   import android.app.Activity;   import android.content.Intent;   import android.graphics.Bitmap;   import android.net.Uri;   import android.os.Bundle;   import android.os.Enviro

  • Android拍照保存在系统相册不显示的问题解决方法

    可能大家都知道我们保存相册到Android手机的时候,然后去打开系统图库找不到我们想要的那张图片,那是因为我们插入的图片还没有更新的缘故,先讲解下插入系统图库的方法吧,很简单,一句代码就能实现 复制代码 代码如下: MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", ""); 通过上面的那句代码就能插入到系统图库,这时候有一个问题,就是我们不能指定插入照片的名字,而是系统给了我

  • Android实现从本地图库/相机拍照后裁剪图片并设置头像

    玩qq或者是微信的盆友都知道,这些聊天工具里都要设置头像,一般情况下大家的解决办法是从本地图库选择图片或是从相机拍照,然后根据自己的喜爱截取图片.上述过程已经实现好了,最后一步我加上了把截取好的图片在保存到本地的操作,来保存头像.为了大家需要,下面我们小编把完整的代码贴出来供大家参考. 先给大家展示效果图: 代码部分: 布局代码(其实就是两个按钮和一个ImageView来显示头像) <LinearLayout xmlns:android="http://schemas.android.co

  • Android仿微信发表说说实现拍照、多图上传功能

    本文实例为大家分享了Android仿微信发表说说.心情功能,供大家参考,具体内容如下 既能实现拍照,选图库,多图案上传的案例,目前好多App都有类似微信朋友圈的功能,能过发表说说等附带图片上传.下面的就是实现该功能的过程:大家还没有看过Android Retrofit 2.0框架上传图片解决方案这篇文章,在看今天的就很容易,接在本项目中用到了一个library:photopicker,封装了图片的选择功能,是否选相机,还有选中图片后可以查看图片的功能.  一. 首先:将photopicker到工

  • Android应用中拍照后获取照片路径并上传的实例分享

    Activity 中的代码,我只贴出重要的事件部分代码 public void doPhoto(View view) { destoryBimap(); String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); s

  • android图像绘制(六)获取本地图片或拍照图片等图片资源

    从SD卡中获取图片资源,或者拍一张新的图片. 先贴代码 获取图片: 注释:拍照获取的话,可以指定图片的保存地址,在此不说明. 复制代码 代码如下: CharSequence[] items = {"相册", "相机"}; new AlertDialog.Builder(this) .setTitle("选择图片来源") .setItems(items, new OnClickListener() { public void onClick(Dia

  • Android启动相机拍照并返回图片

    具体实现过程请看下面代码: 简单的调用了一下系统的拍照功能 代码如下所示: //拍照的方法 private void openTakePhoto(){ /** * 在启动拍照之前最好先判断一下sdcard是否可用 */ String state = Environment.getExternalStorageState(); //拿到sdcard是否可用的状态码 if (state.equals(Environment.MEDIA_MOUNTED)){ //如果可用 Intent intent

  • Android拍照得到全尺寸图片并进行压缩

    废话不多说了,直接给大家贴代码了,具体代码如下所示: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <

  • Android选择图片或拍照图片上传到服务器

    最近要搞一个项目,需要上传相册和拍照的图片,不负所望,终于完成了!  不过需要说明一下,其实网上很多教程拍照的图片,都是缩略图不是很清晰,所以需要在调用照相机的时候,事先生成一个地址,用于标识拍照的图片URI 具体上传代码: 1.选择图片和上传界面,包括上传完成和异常的回调监听 package com.spring.sky.image.upload; import java.util.HashMap; import java.util.Map; import android.app.Activi

  • Android实现拍照、选择图片并裁剪图片功能

    一. 实现拍照.选择图片并裁剪图片效果 按照之前博客的风格,首先看下实现效果. 二. uCrop项目应用 想起之前看到的Yalantis/uCrop效果比较绚,但是研究源码之后发现在定制界面方面还是有一点的限制,于是在它的基础上做了修改Android-Crop,把定制界面独立出来,让用户去自由设置.下图为使用Android-Crop实现的模仿微信选择图片并裁剪Demo. 三. 实现思路 比较简单的选择设备图片裁剪,并将裁剪后的图片保存到指定路径: 调用系统拍照,将拍照图片保存在SD卡,然后裁剪图

随机推荐