Add MailUtil and send log mail
[rtmpclient.git] / app / src / main / java / ai / suanzi / rtmpclient / MainActivity.java
index 1ad33b4..a0b4cc1 100644 (file)
@@ -1,13 +1,18 @@
 package ai.suanzi.rtmpclient;
 
 import android.content.IntentFilter;
+import android.hardware.Camera;
 import android.support.design.widget.TextInputEditText;
+import android.support.v7.app.ActionBar;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
+import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
+import android.view.Window;
+import android.view.WindowManager;
 import android.widget.Button;
 import android.widget.Toast;
 import android.content.Context;
@@ -25,60 +30,32 @@ import android.content.ComponentName;
 import ai.suanzi.rtmpclient.MyService.LocalBinder;
 import android.os.IBinder;
 import android.net.ConnectivityManager;
+import android.view.ViewGroup;
 
 //"rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90";
 
-public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MyService.MyServiceEventListener{
+public class MainActivity extends AppCompatActivity implements MyService.MyServiceEventListener, CameraView.Callback {
 
-    private static final String TAG = "MainActivity";
+    //private static final String TAG = "MainActivity";
     private Logger gLogger;
 
-    private SurfaceHolder mHolder;
-    private SurfaceView mSufaceView;
-    private Button mBtnStart;
-    private TextInputEditText mTextServer;
-    private TextInputEditText mTextUser;
-    private TextInputEditText mTextCamera;
     private String mMacAddr = "";
     private NetworkMonitor networkMonitor;
     private UsbMonitor mUsbMonitor;
     private ServiceHealthMonitor mServiceHealthMonitor;
-    private static final int INTERVAL = 2 * 60; // seconds
+    private static final int INTERVAL = 3 * 60; // seconds
 
-    boolean mBounded;
+    boolean mBounded = false;
     MyService mServer;
     Intent mIntent;
 
-    private void configLog(){
-        try {
-            final LogConfigurator logConfigurator = new LogConfigurator();
-            String fname = getExternalFilesDir(null) + File.separator + "log.txt";
-            logConfigurator.setFileName(fname);
-            Log.e(TAG, "Log file is located at: " + fname);
-            logConfigurator.setRootLevel(Level.DEBUG);
-            logConfigurator.setLevel("org.apache", Level.ERROR);
-            logConfigurator.setMaxFileSize(1024 * 1024 * 10);
-            logConfigurator.configure();
-            gLogger = Logger.getLogger(getClass());
-        } catch (Exception e){
-            e.printStackTrace();
-        }
-    }
+    private CameraView mCameraView;
 
     private void init(){
-        configLog();
-        gLogger.debug("#######################################");
         // set config file
         UserInfo.setConfigPath(getExternalFilesDir(null) + File.separator + "config");
 
         this.mMacAddr = getMacAddr();
-        mBtnStart = findViewById(R.id.button);
-        mTextServer = findViewById(R.id.textServer);
-        mTextUser = findViewById(R.id.textUser);
-        mTextCamera = findViewById(R.id.textCamera);
-        mSufaceView = findViewById(R.id.surfaceView);
-        mHolder = mSufaceView.getHolder();
-        mHolder.addCallback(this);
 
         mIntent = new Intent(this, MyService.class);
         mUsbMonitor = new UsbMonitor(new UsbMonitor.UsbListener() {
@@ -98,7 +75,6 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
                 if(mUsbMonitor.hasUsbCamera()){
                     doBindService();
                 }
-
             }
         }, this);
 
@@ -135,10 +111,9 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
                 gLogger.error("onNotHealthy, in " + INTERVAL + " seconds, the publishing may stopped or have error ");
                 doUnbindService();
                 doBindService();
-
             }
         });
-        mServiceHealthMonitor.setInterval(INTERVAL); // 5 minutes
+        mServiceHealthMonitor.setInterval(INTERVAL);
     }
 
 
@@ -160,9 +135,11 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
             mServer = mLocalBinder.getServiceInstance();
             mServer.setServiceEventListener(MainActivity.this);
             if(mServer.setRtmpUrl(UserInfo.getConfig().toUrl(mMacAddr))){
-                mServer.startPreview(mHolder);
+                mServer.startPreview(mCameraView.getHolder());
+                Camera.Size cs = mServer.getBestPictureSize();
+                mCameraView.setLayout(cs.width, cs.height);
             }
-            gLogger.debug("onServiceConnected - start health monitor thread, interval " + INTERVAL);
+
 
         }
     };
@@ -170,6 +147,7 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
     private void doBindService(){
         gLogger.debug("doBindService");
         if(!mBounded && canStartService()) {
+            gLogger.debug("Start service --------->");
             bindService(mIntent, mConnection, BIND_AUTO_CREATE);
         }
     }
@@ -177,44 +155,58 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
     private void doUnbindService() {
         gLogger.debug("doUnbindService");
         if(mBounded){
+            gLogger.debug("Stop service <---------");
             unbindService(mConnection);
             mBounded = false;
         }
     }
 
+    private void initCameraView (){
+        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
+        requestWindowFeature(Window.FEATURE_NO_TITLE);
+        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+        ///setContentView(R.layout.activity_main);
+
+        ActionBar actionBar = getSupportActionBar();
+        actionBar.hide();
+
+        DisplayMetrics outMetrics = new DisplayMetrics();
+        this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
+
+        CameraView.SCREEN_WIDTH = outMetrics.widthPixels;
+        CameraView.SCREEN_HEIGHT = outMetrics.heightPixels;
+        gLogger.debug("Screen size is w: " + CameraView.SCREEN_WIDTH  + ", h: " + CameraView.SCREEN_HEIGHT);
+
+
+
+        mCameraView = new CameraView(getApplicationContext(), this);
+        setContentView(R.layout.activity_main);
+
+        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(640, 480);
+        addContentView(mCameraView, lp);
+        //setContentView(mCameraView);
+    }
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_main);
-
+        LogUtil.config(getExternalFilesDir(null));
+        gLogger = Logger.getLogger(getClass());
+        gLogger.error("#######################################");
+        //configLog();
+        initCameraView();
         init();
         loadConfig();
 
+
         if(NetworkMonitor.isNetworkAvailable(this) && mUsbMonitor.hasUsbCamera()){
             gLogger.error("Current network is available");
             doBindService();
-
-
         } else {
-            gLogger.error("Current network is NOT available");
+            gLogger.error("Current network NOT available or no USB Camera connected");
         }
 
-        mBtnStart.setText("start");
-        mBtnStart.setOnClickListener(new View.OnClickListener(){
-            @Override
-            public void onClick(View view){
-                gLogger.error("----------> onClick");
-                saveConfig();
-
-                //unbindService(mConnection);
-                bindService(mIntent, mConnection, BIND_AUTO_CREATE);
-                //doUnbindService();
-                //doBindService();
-            }
-        });
-
         if(!mServiceHealthMonitor.isAlive()) {
-            gLogger.debug("mServiceHealthMonitor start");
+            gLogger.debug("mServiceHealthMonitor start, interval " + INTERVAL);
             mServiceHealthMonitor.start();
         }
     }
@@ -246,7 +238,9 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
     @Override
     protected void onDestroy(){
         super.onDestroy();
+        mUsbMonitor.unregisterReceiver();
         unregisterReceiver(networkMonitor);
+        unbindService(mConnection);
         gLogger.debug("onDestroy --------->");
     }
 
@@ -265,44 +259,25 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
         startActivity(intent);
     }
 
-    // SurfaceHolder.Callback implementation
-    @Override
-    public void surfaceCreated(final SurfaceHolder holder){
-        gLogger.error("SurfacedCreated");
-    }
-
-    @Override
-    public void surfaceChanged(SurfaceHolder holder, int format, int widht, int height){
-        gLogger.error("surfaceChanged");
-        mHolder = holder;
-        if (mServer != null) {
-            mServer.startPreview(holder);
-        }
-    }
-
-    @Override
-    public void surfaceDestroyed(SurfaceHolder holder){ gLogger.debug("surfaceDestroyed");
-    }
-
     private String getMacAddr() {
         WifiManager manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
         WifiInfo info = manager.getConnectionInfo();
+        gLogger.debug("Mac Address is " + info.getMacAddress());
         return info.getMacAddress().replace(":", ""); //02:00:00:00:00:00 - 020000000000
     }
 
     private void loadConfig() {
-        UserInfo info = UserInfo.getConfig();
-        gLogger.error("server is:" + info.server);
-        mTextServer.setText(info.server.equals("") ? "rtmp://gpussh.suanzi.ai:1935/myapp" : info.server);
-        mTextUser.setText(info.user);
-        mTextCamera.setText(info.cameraId);
-        //mMacAddr = info.macAddr.equals("") ?  this.mMacAddr : info.macAddr;
-        gLogger.error("loadConfig - url is :" + info.toUrl(mMacAddr));
+//        UserInfo info = UserInfo.getConfig();
+//        gLogger.error("server is:" + info.server);
+//        mTextServer.setText(info.server.equals("") ? "rtmp://gpussh.suanzi.ai:1935/myapp" : info.server);
+//        mTextUser.setText(info.user);
+//        //mMacAddr = info.macAddr.equals("") ?  this.mMacAddr : info.macAddr;
+//        gLogger.error("loadConfig - url is :" + info.toUrl(mMacAddr));
     }
 
     private void saveConfig() {
         UserInfo info = UserInfo.getConfig();
-        info.update(mTextServer.getText().toString(), mTextUser.getText().toString(), mMacAddr, mTextCamera.getText().toString());
+        //info.update(mTextServer.getText().toString(), mTextUser.getText().toString(), mMacAddr, mTextCamera.getText().toString());
         if(info.saveConfig()) {
             Toast.makeText(getApplicationContext(), "Config saved", Toast.LENGTH_LONG).show();
         } else {
@@ -319,19 +294,33 @@ public class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal
     @Override
     public void onCameraError(String msg){
         gLogger.error("onCameraEvent " + msg);
-        if(mUsbMonitor.hasUsbCamera()){
-            mServer.reopenCamera();
-        }
+        //if(mUsbMonitor.hasUsbCamera()){
+            //mServer.reopenCamera();
+        //}
     }
 
     @Override
     public void onEncoderError(String msg){
-        gLogger.error("onEncoderEvent: " + msg);
+        gLogger.error("onEncoderError: " + msg);
+        doUnbindService();
+        doBindService();
     }
 
     @Override
     public void onPublishing(String msg){
-        gLogger.error("onPublishing: " + msg);
         mServiceHealthMonitor.record();
     }
+
+    @Override
+    public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height){
+        if(mServer != null){
+            mServer.startPreview(holder);
+        }
+    }
+
+    private void restartApplication() {
+        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        startActivity(intent);
+    }
 }