Add auto Update
[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.hardware.Camera;
5 import android.net.Uri;
6 import android.support.design.widget.TextInputEditText;
7 import android.support.v7.app.ActionBar;
8 import android.support.v7.app.AppCompatActivity;
9 import android.os.Bundle;
10 import android.util.DisplayMetrics;
11 import android.util.Log;
12 import android.view.SurfaceHolder;
13 import android.view.SurfaceView;
14 import android.view.View;
15 import android.view.Window;
16 import android.view.WindowManager;
17 import android.widget.Button;
18 import android.widget.Toast;
19 import android.content.Context;
20
21 import java.io.File;
22 import android.content.Intent;
23 import de.mindpipe.android.logging.log4j.LogConfigurator;
24 import org.apache.log4j.Level;
25 import org.apache.log4j.Logger;
26 import android.net.wifi.WifiManager;
27 import android.net.wifi.WifiInfo;
28 import android.content.ServiceConnection;
29 import android.content.ComponentName;
30
31 import ai.suanzi.rtmpclient.MyService.LocalBinder;
32 import android.os.IBinder;
33 import android.net.ConnectivityManager;
34 import android.view.ViewGroup;
35
36 public class MainActivity extends AppCompatActivity implements MyService.MyServiceEventListener, CameraView.Callback {
37
38     private Logger gLogger;
39     private NetworkMonitor networkMonitor;
40     private UsbMonitor mUsbMonitor;
41     private ServiceHealthMonitor mServiceHealthMonitor;
42     private static final int INTERVAL = 3 * 60; // seconds
43
44     boolean mBounded = false;
45     MyService mServer;
46     Intent mIntent;
47
48     private CameraView mCameraView;
49
50     private void init(){
51
52         mIntent = new Intent(this, MyService.class);
53         mUsbMonitor = new UsbMonitor(new UsbMonitor.UsbListener() {
54             @Override
55             public void onCameraConnected() {
56                 gLogger.error("onCameraConnected, current Usb Camera count: " + mUsbMonitor.getUsbCameraCount());
57                 doUnbindService();
58                 if(mUsbMonitor.hasUsbCamera()){
59                     doBindService();
60                 }
61             }
62
63             @Override
64             public void onCameraDisconnected() {
65                 gLogger.error("onCameraDisconnected, current camera count: " + mUsbMonitor.getUsbCameraCount());
66                 doUnbindService();
67                 if(mUsbMonitor.hasUsbCamera()){
68                     doBindService();
69                 }
70             }
71         }, this);
72
73         networkMonitor = new NetworkMonitor(new NetworkMonitor.NetworkListener() {
74             @Override
75             public void onWifiConnected() {
76                 gLogger.error("onWifiConnected");
77                 doBindService();
78             }
79
80             @Override
81             public void onWifiDisconnected() {
82                 gLogger.error("onWifiDisconnected");
83                 doUnbindService();
84             }
85
86             @Override
87             public void onWifiEnabled() {
88                 gLogger.error("onWifiEnabled");
89             }
90
91             @Override
92             public void onWifiDisabled() {
93                 gLogger.error("onWifiDisabled");
94             }
95         });
96         IntentFilter filter = new IntentFilter();
97         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
98         registerReceiver(networkMonitor, filter);
99
100         mServiceHealthMonitor = new ServiceHealthMonitor(new ServiceHealthMonitor.Callback() {
101             @Override
102             public void onNotHealthy() {
103                 gLogger.error("onNotHealthy, in " + INTERVAL + " seconds, the publishing may stopped or have error ");
104                 doUnbindService();
105                 doBindService();
106             }
107         });
108         mServiceHealthMonitor.setInterval(INTERVAL);
109     }
110
111
112     ServiceConnection mConnection = new ServiceConnection() {
113         @Override
114         public void onServiceDisconnected(ComponentName name) {
115             Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
116             gLogger.error("onServiceDisconnected ---------->");
117             mBounded = false;
118             mServer = null;
119         }
120
121         @Override
122         public void onServiceConnected(ComponentName name, IBinder service) {
123             Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
124             gLogger.error("onServiceConnected ---------->");
125             mBounded = true;
126             LocalBinder mLocalBinder = (LocalBinder)service;
127             mServer = mLocalBinder.getServiceInstance();
128             mServer.setServiceEventListener(MainActivity.this);
129             if(mServer.setRtmpUrl(UserInfo.toUrl())){
130                 mServer.startPreview(mCameraView.getHolder());
131                 Camera.Size cs = mServer.getBestPictureSize();
132                 mCameraView.setLayout(cs.width, cs.height);
133             }
134
135
136         }
137     };
138
139     private void doBindService(){
140         gLogger.debug("doBindService");
141         if(!mBounded && canStartService()) {
142             gLogger.debug("Start service --------->");
143             bindService(mIntent, mConnection, BIND_AUTO_CREATE);
144         }
145     }
146
147     private void doUnbindService() {
148         gLogger.debug("doUnbindService");
149         if(mBounded){
150             gLogger.debug("Stop service <---------");
151             unbindService(mConnection);
152             mBounded = false;
153         }
154     }
155
156     private void initCameraView (){
157         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
158         requestWindowFeature(Window.FEATURE_NO_TITLE);
159         getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
160         ///setContentView(R.layout.activity_main);
161
162         ActionBar actionBar = getSupportActionBar();
163         actionBar.hide();
164
165         DisplayMetrics outMetrics = new DisplayMetrics();
166         this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
167
168         CameraView.SCREEN_WIDTH = outMetrics.widthPixels;
169         CameraView.SCREEN_HEIGHT = outMetrics.heightPixels;
170         gLogger.debug("Screen size is w: " + CameraView.SCREEN_WIDTH  + ", h: " + CameraView.SCREEN_HEIGHT);
171
172
173
174         mCameraView = new CameraView(getApplicationContext(), this);
175         setContentView(R.layout.activity_main);
176
177         ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(640, 480);
178         addContentView(mCameraView, lp);
179         //setContentView(mCameraView);
180     }
181     @Override
182     protected void onCreate(Bundle savedInstanceState) {
183         super.onCreate(savedInstanceState);
184         LogUtil.config(this);
185         gLogger = Logger.getLogger(getClass());
186         gLogger.error("onCreate ---------> ");
187         UserInfo.readConfig(getExternalFilesDir(null) + File.separator + "config", getMacAddr());
188         initCameraView();
189         init();
190
191         if(canStartService()){
192             gLogger.error("Current network is available");
193             doBindService();
194         } else {
195             gLogger.error("Current network NOT available or no USB Camera connected");
196         }
197
198         if(!mServiceHealthMonitor.isAlive()) {
199             gLogger.debug("mServiceHealthMonitor start, interval " + INTERVAL);
200             mServiceHealthMonitor.start();
201         }
202         ////////// LogUtil.sendLogs();  /// Log test
203         //LogUtil.sendLogs();
204
205         new CheckVersionInfoTask(MainActivity.this).execute();
206     }
207
208     @Override
209     protected void onPause(){
210         super.onPause();
211         gLogger.error("OnPause --------->");
212     }
213
214     @Override
215     protected void onResume() {
216         super.onResume();
217         gLogger.error("OnResume ---------> ");
218     }
219
220     @Override
221     protected void onStop() {
222         super.onStop();
223         gLogger.debug("onStop --------->");
224     }
225
226     @Override
227     protected void onStart(){
228         super.onStart();
229         gLogger.debug("onStart --------->");
230     }
231
232     @Override
233     protected void onDestroy(){
234         super.onDestroy();
235         mUsbMonitor.unregisterReceiver();
236         unregisterReceiver(networkMonitor);
237         unbindService(mConnection);
238         gLogger.debug("onDestroy --------->");
239     }
240
241     @Override
242     protected void onRestart(){
243         super.onRestart();
244         gLogger.debug("onRestart ---------->");
245     }
246
247     @Override
248     public void onBackPressed() {
249         gLogger.error("onBackPressed  --------->");
250         Intent intent = new Intent(Intent.ACTION_MAIN);
251         intent.addCategory(Intent.CATEGORY_HOME);
252         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
253         startActivity(intent);
254     }
255
256     private String getMacAddr() {
257         WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
258         WifiInfo info = manager.getConnectionInfo();
259         gLogger.debug("Mac Address is " + info.getMacAddress());
260         return info.getMacAddress().replace(":", ""); //02:00:00:00:00:00 - 020000000000
261     }
262
263     private boolean canStartService(){
264
265         if(System.getProperty("os.arch").equals("i686")){
266             return  true;
267         }
268         return mUsbMonitor.hasUsbCamera() && NetworkMonitor.isNetworkAvailable(this);
269     }
270
271     // MyServiceEventListener
272     @Override
273     public void onCameraError(String msg){
274         gLogger.error("onCameraEvent " + msg);
275         //if(mUsbMonitor.hasUsbCamera()){
276             //mServer.reopenCamera();
277         //}
278     }
279
280     @Override
281     public void onEncoderError(String msg){
282         gLogger.error("onEncoderError: " + msg);
283         doUnbindService();
284         doBindService();
285     }
286
287     @Override
288     public void onPublishing(String msg){
289         mServiceHealthMonitor.record();
290     }
291
292     @Override
293     public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height){
294         if(mServer != null){
295             mServer.startPreview(holder);
296         }
297     }
298
299     private void restartApplication() {
300         final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
301         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
302         startActivity(intent);
303     }
304 }