Android實(shí)現(xiàn)后臺開啟服務(wù)默默拍照功能
本文實(shí)例為大家分享了Android后臺開啟服務(wù)默默拍照的具體代碼,供大家參考,具體內(nèi)容如下
最近項(xiàng)目原因,需要編寫一后臺運(yùn)行的程序,在給定時(shí)間間隔下進(jìn)行拍照,關(guān)鍵技術(shù)主要是:1、開啟服務(wù);2、在不不預(yù)覽的情況下,進(jìn)行拍照操作。3、使用AlarmManager進(jìn)行定時(shí)操作。
資源清單如下:
<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>
服務(wù)代碼如下:
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分鐘觸發(fā)一次
}
@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;
}
}
進(jìn)行拍照存儲的操作代碼如下:
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");
}
}
項(xiàng)目代碼如下:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android實(shí)現(xiàn)拍照、選擇圖片并裁剪圖片功能
- Android啟動相機(jī)拍照并返回圖片
- Android拍照保存在系統(tǒng)相冊不顯示的問題解決方法
- Android仿微信發(fā)表說說實(shí)現(xiàn)拍照、多圖上傳功能
- android 拍照和上傳的實(shí)現(xiàn)代碼
- Android拍照得到全尺寸圖片并進(jìn)行壓縮
- android圖像繪制(六)獲取本地圖片或拍照圖片等圖片資源
- Android應(yīng)用中拍照后獲取照片路徑并上傳的實(shí)例分享
- Android實(shí)現(xiàn)從本地圖庫/相機(jī)拍照后裁剪圖片并設(shè)置頭像
- Android選擇圖片或拍照圖片上傳到服務(wù)器
相關(guān)文章
Android使用Canvas?2D實(shí)現(xiàn)循環(huán)菜單效果
循環(huán)菜單有很多種自定義方式,我們可以利用ViewPager或者RecyclerView?+?CarouselLayoutManager?或者RecyclerView?+?PageSnapHelper來實(shí)現(xiàn)這種效果,今天我們使用Canvas?2D來實(shí)現(xiàn)這種效果,感興趣的朋友可以參考下2024-01-01
神奇的listView實(shí)現(xiàn)自動顯示隱藏布局Android代碼
這篇文章主要介紹了神奇的listView實(shí)現(xiàn)自動顯示隱藏布局Android代碼實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
詳解flutter如何實(shí)現(xiàn)局部導(dǎo)航管理
這篇文章主要為大家介紹了詳解flutter如何實(shí)現(xiàn)局部導(dǎo)航管理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
Android編程實(shí)現(xiàn)通過反射獲取資源Id的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)通過反射獲取資源Id的方法,結(jié)合實(shí)例形式分析了Android反射機(jī)制操作資源的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-01-01
Android編程設(shè)計(jì)模式之備忘錄模式詳解
這篇文章主要介紹了Android編程設(shè)計(jì)模式之備忘錄模式,結(jié)合實(shí)例形式詳細(xì)分析了Android備忘錄模式的概念、原理、應(yīng)用場景、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2017-12-12
詳解Android開發(fā)中ContentObserver類的使用
這篇文章主要介紹了詳解Android開發(fā)中ContentObserver類的使用,ContentObserver內(nèi)容觀察者主要用來監(jiān)聽uri的改變請情況,需要的朋友可以參考下2016-04-04

