Add NetworkMonitor
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / MyService.java
1 package ai.suanzi.rtmpclient;
2
3 import android.app.Service;
4 import android.content.Intent;
5 import android.graphics.SurfaceTexture;
6 import android.hardware.Camera;
7 import android.os.Handler;
8 import android.os.HandlerThread;
9 import android.os.IBinder;
10 import android.os.Looper;
11 import android.util.Log;
12 import android.view.SurfaceHolder;
13 import android.view.SurfaceView;
14 import android.view.WindowManager;
15 import android.widget.Toast;
16 import android.support.v4.app.NotificationCompat;
17 import android.graphics.BitmapFactory;
18 import android.app.Notification;
19 import android.os.Message;
20 import org.apache.log4j.Level;
21 import org.apache.log4j.Logger;
22 import android.hardware.Camera.PreviewCallback;
23 import android.os.IBinder;
24 import android.os.Binder;
25 import android.content.Context;
26 import android.graphics.PixelFormat;
27 import java.io.IOException;
28 import android.view.Gravity;
29
30 public class MyService extends Service  implements Camera.PreviewCallback {
31
32     private static Logger gLogger = Logger.getLogger("MyService");
33     private static String TAG = "MyService";
34
35     //private Ffmpeg ffmpeg = Ffmpeg.getInstance();
36     private  Boolean isRunning = false;
37     private Camera mCamera = null;
38     IBinder mBinder = new LocalBinder();
39     private String rtmpUrl;
40     private long frameCount = 0;
41
42
43     public class LocalBinder extends Binder {
44         public MyService getServiceInstance(){
45             return MyService.this;
46         }
47     }
48
49     public Camera getCameraInstance() {
50         if (mCamera == null) {
51             CameraHandlerThread mThread = new CameraHandlerThread("camera thread");
52             synchronized (mThread) {
53                 mThread.openCamera();
54             }
55         }
56         if (mCamera == null){
57             gLogger.error("getCameraInstance, camera is null");
58         }
59         return mCamera;
60     }
61
62     private void openCameraOriginal() {
63         try {
64             gLogger.error("openCameraOriginal");
65             mCamera = Camera.open(1);
66         } catch (Exception e) {
67             gLogger.error("camera is not available. error: " + e.getMessage());
68         }
69     }
70
71     private class CameraHandlerThread extends HandlerThread {
72         Handler mHandler;
73
74         public CameraHandlerThread(String name) {
75             super(name);
76             gLogger.error("CameraHandlerThread: " + name);
77             start();
78             mHandler = new Handler(getLooper());
79         }
80
81         synchronized void notifyCameraOpened() {
82             notify();
83         }
84
85         void openCamera() {
86             mHandler.post(new Runnable() {
87                 @Override
88                 public void run() {
89                     openCameraOriginal();
90                     notifyCameraOpened();
91                 }
92             });
93             try {
94                 wait();
95             } catch (InterruptedException e) {
96                 gLogger.error("wait was interrupted");
97             }
98         }
99     }
100
101     private static final int NOTIFICATION_DOWNLOAD_PROGRESS_ID = 0x0001;                                        //id不可设置为0,否则不能设置为前台service
102     private void createNotification(){
103         gLogger.debug("createNotification");
104         NotificationCompat.Builder builder=new NotificationCompat.Builder(this);                        //使用兼容版本
105         builder.setSmallIcon(R.mipmap.ic_launcher);                                                             //设置状态栏的通知图标
106         builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher_background));   //设置通知栏横条的图标
107         builder.setAutoCancel(false);                                                                           //禁止用户点击删除按钮删除
108         builder.setOngoing(true);                                                                               //禁止滑动删除
109         builder.setShowWhen(true);                                                                              //右上角的时间显示
110         builder.setContentTitle("Rtmp Foreground Service!!!");                                                  //设置通知栏的标题内容
111         Notification notification = builder.build();                                                            //创建通知
112         startForeground(NOTIFICATION_DOWNLOAD_PROGRESS_ID,notification);                                        //设置为前台服务
113     }
114
115     @Override
116     public IBinder onBind(Intent intent) {
117         return mBinder;
118     }
119
120     @Override
121     public void onCreate() {
122         super.onCreate();
123         gLogger.error("onCreate ---> ");
124         createNotification();
125         Toast.makeText(this, "Video stream pushed to " + this.rtmpUrl, Toast.LENGTH_LONG).show();
126         mCamera = getCameraInstance();
127         configCamera(mCamera);
128     }
129
130     @Override
131     public void onDestroy() {
132         stopForeground(true);
133         super.onDestroy();
134         gLogger.error( "onDestroy --------->");
135         Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
136         if(mCamera != null){
137             mCamera.stopPreview();
138             mCamera.release();
139         }
140         FfmpegHelper.close();
141     }
142
143
144     @Override
145     public int onStartCommand(Intent intent, int flags, int startId) {
146         gLogger.error("onStartCommand");
147         return START_STICKY;
148     }
149
150     @Override
151     public void onLowMemory(){
152         super.onLowMemory();
153         gLogger.error("onLowMemory");
154     }
155
156     // Camera.PreviewCallback
157     @Override
158     public void  onPreviewFrame(final byte[] data, Camera camera){
159         if(frameCount % (15 * 60) == 0) {
160             gLogger.error("onPreviewFrame");
161         }
162         frameCount++;
163         if(FfmpegHelper.processFrame(data) != 0){
164             gLogger.error("FfmpegHelper.processFrame error. close");
165             FfmpegHelper.close();
166         }
167     }
168
169     public void startPreview (SurfaceHolder holder){
170         gLogger.error("startPreview");
171         if (mCamera == null){
172             gLogger.error("startPreview - error: camera is null");
173             return;
174         }
175         try {
176             mCamera.setPreviewDisplay(holder);
177             mCamera.startPreview();
178         } catch (Exception e){
179             gLogger.error("startPreview - error: " + e.getMessage());
180             e.printStackTrace();
181         }
182     }
183
184     public boolean setRtmpUrl (String url){
185         this.rtmpUrl = url;
186         Camera.Parameters param = mCamera.getParameters();
187         int width = param.getPictureSize().width;
188         int height = param.getPictureSize().height;
189         gLogger.error("setRtmpUrl - size: " +  width + "x" + height + ". url: " + url);
190         int ret = FfmpegHelper.initEncoder(width, height, url);
191         return ret == 0 ? true : false;
192     }
193
194     private void configCamera(Camera camera){
195         if(mCamera == null){
196             gLogger.error("configCamera - camera is null");
197             return;
198         }
199         Camera.Parameters paras = camera.getParameters();
200         gLogger.error("Supported Picture Sizes:");
201         Camera.Size preferredSize = paras.getSupportedPictureSizes().get(0);
202         for (Camera.Size cc : paras.getSupportedPictureSizes()){
203             if (cc.width == 640)
204                 preferredSize = cc;
205             gLogger.error(cc.width + "x" + cc.height);
206         }
207         gLogger.error("Supported Preview fps range:");
208         for(int[] i : paras.getSupportedPreviewFpsRange()){
209             gLogger.error("[" + i[0] + "," + i[1] + "]");
210         }
211         paras.setPictureSize(preferredSize.width, preferredSize.height); // use 640x480 preferred
212         camera.setParameters(paras);
213         camera.setDisplayOrientation(0);
214         gLogger.error("Preview Format: " + paras.getPreviewFormat() + ". Size: " + paras.getPreviewSize().width + "x" + paras.getPreviewSize().height);
215         gLogger.error("Picture Format: " + paras.getPictureFormat() + ". Size: " + paras.getPictureSize().width + "x" + paras.getPictureSize().height);
216         camera.setPreviewCallback(this);
217     }
218 }