clean the code, and fix bug service stopped when back pressed
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / MainActivity.java
1 package ai.suanzi.rtmpclient;
2
3 import android.content.IntentFilter;
4 import android.support.design.widget.TextInputEditText;
5 import android.support.v7.app.AppCompatActivity;
6 import android.os.Bundle;
7 import android.util.Log;
8 import android.view.SurfaceHolder;
9 import android.view.SurfaceView;
10 import android.view.View;
11 import android.widget.Button;
12 import android.widget.Toast;
13 import android.content.Context;
14
15 import java.io.File;
16 import android.content.Intent;
17 import de.mindpipe.android.logging.log4j.LogConfigurator;
18 import org.apache.log4j.Level;
19 import org.apache.log4j.Logger;
20 import android.net.wifi.WifiManager;
21 import android.net.wifi.WifiInfo;
22 import android.content.ServiceConnection;
23 import android.content.ComponentName;
24
25 import ai.suanzi.rtmpclient.MyService.LocalBinder;
26 import android.os.IBinder;
27 import android.net.ConnectivityManager;
28
29 //"rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90";
30
31 public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MyService.MyServiceEventListener{
32
33     private static final String TAG = "MainActivity";
34     private Logger gLogger;
35
36     private SurfaceHolder mHolder;
37     private SurfaceView mSufaceView;
38     private Button mBtnStart;
39     private TextInputEditText mTextServer;
40     private TextInputEditText mTextUser;
41     private TextInputEditText mTextCamera;
42     private String mMacAddr = "";
43     private NetworkMonitor networkMonitor;
44     private UsbMonitor mUsbMonitor;
45     private ServiceHealthMonitor mServiceHealthMonitor;
46     private static final int INTERVAL = 2 * 60; // seconds
47
48     boolean mBounded;
49     MyService mServer;
50     Intent mIntent;
51
52     private void configLog(){
53         try {
54             final LogConfigurator logConfigurator = new LogConfigurator();
55             String fname = getExternalFilesDir(null) + File.separator + "log.txt";
56             logConfigurator.setFileName(fname);
57             Log.e(TAG, "Log file is located at: " + fname);
58             logConfigurator.setRootLevel(Level.DEBUG);
59             logConfigurator.setLevel("org.apache", Level.ERROR);
60             logConfigurator.setMaxFileSize(1024 * 1024 * 10);
61             logConfigurator.configure();
62             gLogger = Logger.getLogger(getClass());
63         } catch (Exception e){
64             e.printStackTrace();
65         }
66     }
67
68     private void init(){
69         configLog();
70         gLogger.debug("#######################################");
71         // set config file
72         UserInfo.setConfigPath(getExternalFilesDir(null) + File.separator + "config");
73
74         this.mMacAddr = getMacAddr();
75         mBtnStart = findViewById(R.id.button);
76         mTextServer = findViewById(R.id.textServer);
77         mTextUser = findViewById(R.id.textUser);
78         mTextCamera = findViewById(R.id.textCamera);
79         mSufaceView = findViewById(R.id.surfaceView);
80         mHolder = mSufaceView.getHolder();
81         mHolder.addCallback(this);
82
83         mIntent = new Intent(this, MyService.class);
84         mUsbMonitor = new UsbMonitor(new UsbMonitor.UsbListener() {
85             @Override
86             public void onCameraConnected() {
87                 gLogger.error("onCameraConnected, current Usb Camera count: " + mUsbMonitor.getUsbCameraCount());
88                 doUnbindService();
89                 if(mUsbMonitor.hasUsbCamera()){
90                     doBindService();
91                 }
92             }
93
94             @Override
95             public void onCameraDisconnected() {
96                 gLogger.error("onCameraDisconnected, current camera count: " + mUsbMonitor.getUsbCameraCount());
97                 doUnbindService();
98                 if(mUsbMonitor.hasUsbCamera()){
99                     doBindService();
100                 }
101
102             }
103         }, this);
104
105         networkMonitor = new NetworkMonitor(new NetworkMonitor.NetworkListener() {
106             @Override
107             public void onWifiConnected() {
108                 gLogger.error("onWifiConnected");
109                 doBindService();
110             }
111
112             @Override
113             public void onWifiDisconnected() {
114                 gLogger.error("onWifiDisconnected");
115                 doUnbindService();
116             }
117
118             @Override
119             public void onWifiEnabled() {
120                 gLogger.error("onWifiEnabled");
121             }
122
123             @Override
124             public void onWifiDisabled() {
125                 gLogger.error("onWifiDisabled");
126             }
127         });
128         IntentFilter filter = new IntentFilter();
129         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
130         registerReceiver(networkMonitor, filter);
131
132         mServiceHealthMonitor = new ServiceHealthMonitor(new ServiceHealthMonitor.Callback() {
133             @Override
134             public void onNotHealthy() {
135                 gLogger.error("onNotHealthy, in " + INTERVAL + " seconds, the publishing may stopped or have error ");
136                 doUnbindService();
137                 doBindService();
138
139             }
140         });
141         mServiceHealthMonitor.setInterval(INTERVAL); // 5 minutes
142     }
143
144
145     ServiceConnection mConnection = new ServiceConnection() {
146         @Override
147         public void onServiceDisconnected(ComponentName name) {
148             Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
149             gLogger.error("onServiceDisconnected ---------->");
150             mBounded = false;
151             mServer = null;
152         }
153
154         @Override
155         public void onServiceConnected(ComponentName name, IBinder service) {
156             Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
157             gLogger.error("onServiceConnected ---------->");
158             mBounded = true;
159             LocalBinder mLocalBinder = (LocalBinder)service;
160             mServer = mLocalBinder.getServiceInstance();
161             mServer.setServiceEventListener(MainActivity.this);
162             if(mServer.setRtmpUrl(UserInfo.getConfig().toUrl(mMacAddr))){
163                 mServer.startPreview(mHolder);
164             }
165             gLogger.debug("onServiceConnected - start health monitor thread, interval " + INTERVAL);
166
167         }
168     };
169
170     private void doBindService(){
171         gLogger.debug("doBindService");
172         if(!mBounded && canStartService()) {
173             bindService(mIntent, mConnection, BIND_AUTO_CREATE);
174         }
175     }
176
177     private void doUnbindService() {
178         gLogger.debug("doUnbindService");
179         if(mBounded){
180             unbindService(mConnection);
181             mBounded = false;
182         }
183     }
184
185     @Override
186     protected void onCreate(Bundle savedInstanceState) {
187         super.onCreate(savedInstanceState);
188         setContentView(R.layout.activity_main);
189
190         init();
191         loadConfig();
192
193         if(NetworkMonitor.isNetworkAvailable(this) && mUsbMonitor.hasUsbCamera()){
194             gLogger.error("Current network is available");
195             doBindService();
196
197
198         } else {
199             gLogger.error("Current network is NOT available");
200         }
201
202         mBtnStart.setText("start");
203         mBtnStart.setOnClickListener(new View.OnClickListener(){
204             @Override
205             public void onClick(View view){
206                 gLogger.error("----------> onClick");
207                 saveConfig();
208
209                 //unbindService(mConnection);
210                 bindService(mIntent, mConnection, BIND_AUTO_CREATE);
211                 //doUnbindService();
212                 //doBindService();
213             }
214         });
215
216         if(!mServiceHealthMonitor.isAlive()) {
217             gLogger.debug("mServiceHealthMonitor start");
218             mServiceHealthMonitor.start();
219         }
220     }
221
222     @Override
223     protected void onPause(){
224         super.onPause();
225         gLogger.error("OnPause --------->");
226     }
227
228     @Override
229     protected void onResume() {
230         super.onResume();
231         gLogger.error("OnResume ---------> ");
232     }
233
234     @Override
235     protected void onStop() {
236         super.onStop();
237         gLogger.debug("onStop --------->");
238     }
239
240     @Override
241     protected void onStart(){
242         super.onStart();
243         gLogger.debug("onStart --------->");
244     }
245
246     @Override
247     protected void onDestroy(){
248         super.onDestroy();
249         unregisterReceiver(networkMonitor);
250         gLogger.debug("onDestroy --------->");
251     }
252
253     @Override
254     protected void onRestart(){
255         super.onRestart();
256         gLogger.debug("onRestart ---------->");
257     }
258
259     @Override
260     public void onBackPressed() {
261         gLogger.error("onBackPressed  --------->");
262         Intent intent = new Intent(Intent.ACTION_MAIN);
263         intent.addCategory(Intent.CATEGORY_HOME);
264         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
265         startActivity(intent);
266     }
267
268     // SurfaceHolder.Callback implementation
269     @Override
270     public void surfaceCreated(final SurfaceHolder holder){
271         gLogger.error("SurfacedCreated");
272     }
273
274     @Override
275     public void surfaceChanged(SurfaceHolder holder, int format, int widht, int height){
276         gLogger.error("surfaceChanged");
277         mHolder = holder;
278         if (mServer != null) {
279             mServer.startPreview(holder);
280         }
281     }
282
283     @Override
284     public void surfaceDestroyed(SurfaceHolder holder){ gLogger.debug("surfaceDestroyed");
285     }
286
287     private String getMacAddr() {
288         WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
289         WifiInfo info = manager.getConnectionInfo();
290         return info.getMacAddress().replace(":", ""); //02:00:00:00:00:00 - 020000000000
291     }
292
293     private void loadConfig() {
294         UserInfo info = UserInfo.getConfig();
295         gLogger.error("server is:" + info.server);
296         mTextServer.setText(info.server.equals("") ? "rtmp://gpussh.suanzi.ai:1935/myapp" : info.server);
297         mTextUser.setText(info.user);
298         mTextCamera.setText(info.cameraId);
299         //mMacAddr = info.macAddr.equals("") ?  this.mMacAddr : info.macAddr;
300         gLogger.error("loadConfig - url is :" + info.toUrl(mMacAddr));
301     }
302
303     private void saveConfig() {
304         UserInfo info = UserInfo.getConfig();
305         info.update(mTextServer.getText().toString(), mTextUser.getText().toString(), mMacAddr, mTextCamera.getText().toString());
306         if(info.saveConfig()) {
307             Toast.makeText(getApplicationContext(), "Config saved", Toast.LENGTH_LONG).show();
308         } else {
309             Toast.makeText(getApplicationContext(), "Error: config saved", Toast.LENGTH_LONG).show();
310         }
311         gLogger.error("saveConfig - url: " + info.toUrl(mMacAddr));
312     }
313
314     private boolean canStartService(){
315         return mUsbMonitor.hasUsbCamera() && NetworkMonitor.isNetworkAvailable(this);
316     }
317
318     // MyServiceEventListener
319     @Override
320     public void onCameraError(String msg){
321         gLogger.error("onCameraEvent " + msg);
322         if(mUsbMonitor.hasUsbCamera()){
323             mServer.reopenCamera();
324         }
325     }
326
327     @Override
328     public void onEncoderError(String msg){
329         gLogger.error("onEncoderEvent: " + msg);
330     }
331
332     @Override
333     public void onPublishing(String msg){
334         gLogger.error("onPublishing: " + msg);
335         mServiceHealthMonitor.record();
336     }
337 }