1 package ai.suanzi.rtmpclient;
3 import android.app.Service;
4 import android.content.Intent;
5 import android.hardware.Camera;
6 import android.os.Handler;
7 import android.os.HandlerThread;
8 import android.os.IBinder;
9 import android.view.SurfaceHolder;
10 import android.widget.Toast;
11 import android.support.v4.app.NotificationCompat;
12 import android.graphics.BitmapFactory;
13 import android.app.Notification;
14 import org.apache.log4j.Logger;
15 import android.os.Binder;
19 public class MyService extends Service implements Camera.PreviewCallback, Camera.ErrorCallback {
21 private static Logger gLogger = Logger.getLogger("MyService");
22 private Camera mCamera = null;
23 IBinder mBinder = new LocalBinder();
24 //private String rtmpUrl;
25 private long frameCount = 0;
27 // Preferred picture Size of the camera;
28 private int width = 0;
29 private int height = 0;
32 private MyServiceEventListener mListener;
33 public void setServiceEventListener(MyServiceEventListener listener){
37 public class LocalBinder extends Binder {
38 public MyService getServiceInstance(){
39 return MyService.this;
43 public Camera getCameraInstance() {
44 if (mCamera == null) {
45 CameraHandlerThread mThread = new CameraHandlerThread("camera thread");
46 synchronized (mThread) {
53 private void openCameraOriginal() {
55 gLogger.error("openCameraOriginal");
56 Camera.CameraInfo info = new Camera.CameraInfo();
57 int numCameras = Camera.getNumberOfCameras();
61 gLogger.debug("Number of Cameras is " + numCameras);
62 for(int i = 0; i < numCameras; i++){
63 Camera.getCameraInfo(i, info);
64 if(info.facing == Camera.CameraInfo.CAMERA_FACING_BACK){
65 gLogger.debug("CAMERA_FACING_BACK id is " + i);
67 } else if(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
68 gLogger.debug("CAMERA_FACING_FRONT id is " + i);
72 if(frontId != -1) camerId = frontId;
73 else if(backId != -1) camerId = backId;
74 gLogger.debug("openCameraOriginal - camera id " + camerId);
75 mCamera = Camera.open(1);
76 } catch (Exception e) {
77 gLogger.error("openCameraOriginal - camera is not available. error: " + e.getMessage());
78 if(mListener != null) mListener.onCameraError("openCamera - error: " + e.getMessage());
82 private class CameraHandlerThread extends HandlerThread {
85 public CameraHandlerThread(String name) {
87 gLogger.error("CameraHandlerThread: " + name);
89 mHandler = new Handler(getLooper());
92 synchronized void notifyCameraOpened() {
97 mHandler.post(new Runnable() {
100 openCameraOriginal();
101 notifyCameraOpened();
106 } catch (InterruptedException e) {
107 gLogger.error("wait was interrupted, " + e.getMessage());
112 private static final int NOTIFICATION_DOWNLOAD_PROGRESS_ID = 0x0001; //id不可设置为0,否则不能设置为前台service
113 private void createNotification(){
114 gLogger.debug("createNotification");
115 NotificationCompat.Builder builder=new NotificationCompat.Builder(this); //使用兼容版本
116 builder.setSmallIcon(R.mipmap.ic_launcher); //设置状态栏的通知图标
117 builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background)); //设置通知栏横条的图标
118 builder.setAutoCancel(false); //禁止用户点击删除按钮删除
119 builder.setOngoing(true); //禁止滑动删除
120 builder.setShowWhen(true); //右上角的时间显示
121 builder.setContentTitle("Rtmp Foreground Service!!!"); //设置通知栏的标题内容
122 Notification notification = builder.build(); //创建通知
123 startForeground(NOTIFICATION_DOWNLOAD_PROGRESS_ID,notification); //设置为前台服务
127 public IBinder onBind(Intent intent) {
132 public void onCreate() {
134 gLogger.error("onCreate ---> ");
135 createNotification();
136 Toast.makeText(this, "Started to Publish!", Toast.LENGTH_LONG).show();
137 mCamera = getCameraInstance();
139 configCamera(mCamera);
140 mCamera.setErrorCallback(this);
146 public void onDestroy() {
147 stopForeground(true);
149 gLogger.error( "onDestroy --------->");
150 Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
153 mCamera.stopPreview();
156 } catch (Exception e){
157 gLogger.error("onDestroy - error " + e.getMessage());
165 public int onStartCommand(Intent intent, int flags, int startId) {
166 gLogger.error("onStartCommand");
171 public void onLowMemory(){
173 gLogger.error("onLowMemory");
176 // Camera.PreviewCallback
178 public void onPreviewFrame(final byte[] data, Camera camera){
179 if(frameCount % (15 * 60) == 0) {
180 gLogger.error("onPreviewFrame");
182 if(FfmpegHelper.processFrame(data) != 0){
183 gLogger.error("onPreviewFrame, processFrame close");
184 FfmpegHelper.close();
185 if(mListener != null) mListener.onEncoderError("processFrame");
187 if(frameCount % (15 * 60) == 0){
188 if(mListener != null) mListener.onPublishing("processFrame OK");
194 public void startPreview (SurfaceHolder holder){
195 gLogger.debug("startPreview");
197 mCamera.setPreviewDisplay(holder);
198 mCamera.startPreview();
199 } catch (Exception e){
200 gLogger.error("startPreview - error: " + e.getMessage());
202 if(mListener != null) mListener.onCameraError("setPreviewDisplay - " + e.getMessage());
206 public void reopenCamera() {
207 gLogger.debug("reopenCamera");
209 mCamera.stopPreview();
213 openCameraOriginal();
216 public boolean setRtmpUrl (String url){
217 //this.rtmpUrl = url;
219 gLogger.error("setRtmpUrl, error mCamera is null");
222 gLogger.error("setRtmpUrl - size: " + width + "x" + height + ". url: " + url);
223 int ret = FfmpegHelper.initEncoder(width, height, url);
225 gLogger.error("setRtmpUrl, initEncoder error");
227 return ret == 0 ? true : false;
230 private void configCamera(Camera camera){
231 Camera.Parameters paras = null;
233 paras = camera.getParameters();
234 } catch (RuntimeException e){
235 gLogger.error("configCamera - " + e.getMessage());
236 if(mListener != null) mListener.onCameraError("getParameters - " + e.getMessage());
239 gLogger.error("Supported Picture Sizes:");
240 Camera.Size preferredSize = paras.getSupportedPictureSizes().get(0);
241 for (Camera.Size cc : paras.getSupportedPictureSizes()){
242 if (cc.width == 640) // chose 640 x 480 if exists
244 gLogger.error(cc.width + "x" + cc.height);
246 gLogger.error("Supported Preview fps range:");
247 for(int[] i : paras.getSupportedPreviewFpsRange()){
248 gLogger.error("[" + i[0] + "," + i[1] + "]");
250 width = preferredSize.width;
251 height = preferredSize.height;
252 paras.setPictureSize(preferredSize.width, preferredSize.height); // use 640x480 preferred
253 camera.setParameters(paras);
254 camera.setDisplayOrientation(0);
255 gLogger.error("Preview Format: " + paras.getPreviewFormat() + ". Size: " + paras.getPreviewSize().width + "x" + paras.getPreviewSize().height);
256 gLogger.error("Picture Format: " + paras.getPictureFormat() + ". Size: " + paras.getPictureSize().width + "x" + paras.getPictureSize().height);
257 camera.setPreviewCallback(this);
260 // Camaer.onError callback
262 public void onError(int error, Camera camera){
263 gLogger.error("Camera.OnError, " + error);
265 case Camera.CAMERA_ERROR_SERVER_DIED:
266 gLogger.error("CAMERA_ERROR_SERVER_DIED");
268 case Camera.CAMERA_ERROR_UNKNOWN:
269 gLogger.error("CAMERA_ERROR_UNKNOWN");
273 if(mListener != null) mListener.onCameraError("OnError, " + error);
277 public interface MyServiceEventListener {
278 void onCameraError(String err);
279 void onEncoderError(String msg);
280 //void onIsPreviewing(String msg); // notify mainActivity if preview is running well
281 void onPublishing(String msg); // notify main activity if encoder is running well;