Add auto Update
authorPeng Li <seudut@gmail.com>
Mon, 28 May 2018 08:02:09 +0000 (16:02 +0800)
committerPeng Li <seudut@gmail.com>
Mon, 28 May 2018 08:02:09 +0000 (16:02 +0800)
app/build.gradle
app/src/main/AndroidManifest.xml
app/src/main/java/ai/suanzi/rtmpclient/CheckVersionInfoTask.java [new file with mode: 0644]
app/src/main/java/ai/suanzi/rtmpclient/DownloadApkService.java [new file with mode: 0644]
app/src/main/java/ai/suanzi/rtmpclient/LogUtil.java
app/src/main/java/ai/suanzi/rtmpclient/MainActivity.java
app/src/main/java/ai/suanzi/rtmpclient/MyService.java
app/src/main/java/ai/suanzi/rtmpclient/UsbMonitor.java
app/src/main/java/ai/suanzi/rtmpclient/UserInfo.java

index dbdae8b..49dfb20 100644 (file)
@@ -6,7 +6,7 @@ android {
         applicationId "ai.suanzi.rtmpclient"
         minSdkVersion 17
         targetSdkVersion 17
-        versionCode 1
+        versionCode 32
         versionName "v0.3.2"
         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
         buildConfigField "String", "GIT_REVISION", "\"${getGitVersion()}\""
index 6c2a7f8..75f68c3 100644 (file)
                 <action android:name="ai.suanzi.rtmpclient.service" />
             </intent-filter>
         </service>
+        <service android:name=".DownloadApkService">
+
+        </service>
+
         <activity android:name=".MainActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/app/src/main/java/ai/suanzi/rtmpclient/CheckVersionInfoTask.java b/app/src/main/java/ai/suanzi/rtmpclient/CheckVersionInfoTask.java
new file mode 100644 (file)
index 0000000..a8795d6
--- /dev/null
@@ -0,0 +1,111 @@
+package ai.suanzi.rtmpclient;
+
+import android.content.Context;
+import android.os.AsyncTask;
+import org.apache.log4j.Logger;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import android.content.Intent;
+
+
+public class CheckVersionInfoTask extends AsyncTask<Void, Void, String> {
+
+    private static Logger gLogger = Logger.getLogger("CheckVersionInfoTask");
+    private Context mContext;
+
+    private static final String VERSION_INFO_URL = "http://downloads.suanzi.ai/RtmpClient/update.json";
+
+    public CheckVersionInfoTask(Context context){
+        this.mContext = context;
+    }
+
+    @Override
+    protected String doInBackground(Void... params){
+        gLogger.debug("doInBackground");
+        return getVersionInfo(VERSION_INFO_URL);
+    }
+
+    @Override
+    protected void onPreExecute(){
+        gLogger.debug("onPreExecute");
+    }
+
+    @Override
+    protected void onPostExecute(String result) {
+        gLogger.debug("onPostExecute, update.json " + result);
+        parseJson(result);
+
+    }
+
+    private String getVersionInfo(String urlStr) {
+        HttpURLConnection urlConnection = null;
+        InputStream is = null;
+        BufferedReader buffer = null;
+        String result = null;
+        try {
+            URL url = new URL(urlStr);
+            urlConnection = (HttpURLConnection) url.openConnection();
+            is = urlConnection.getInputStream();
+            buffer = new BufferedReader(new InputStreamReader(is));
+            StringBuilder strBuilder = new StringBuilder();
+            String line;
+            while ((line = buffer.readLine()) != null) {
+                strBuilder.append(line);
+            }
+            result = strBuilder.toString();
+        } catch (Exception e){
+            gLogger.error("getVersionInfo - error: " + e.getMessage());
+            e.printStackTrace();
+        } finally {
+            if (buffer != null) {
+                try {
+                    buffer.close();
+                } catch (IOException e){
+                    e.printStackTrace();
+                }
+            }
+            if (urlConnection != null){
+                urlConnection.disconnect();
+            }
+        }
+        return result;
+    }
+
+    private void parseJson(String result) {
+        try {
+            JSONObject obj = new JSONObject(result);
+            String apkUrl = obj.getString("url");
+            String updateMessage = obj.getString("updateMessage");
+            int apkCode = obj.getInt("versionCode");
+            int versionCode = getCurrentVersionCode();
+            gLogger.error("apkUrl: " + apkUrl);
+            gLogger.error("UpdateMessage: " + updateMessage);
+            gLogger.error("apkCode: " + apkCode);
+            gLogger.error("versionCode: " + versionCode);
+            if(apkCode > versionCode){
+                gLogger.debug("Found new version, current is " + versionCode + ", will update to " + apkCode);
+                goToDownloadApk(apkUrl);
+            }
+        } catch (JSONException e){
+            gLogger.error("parseJson - error " + e.getMessage());
+            e.printStackTrace();
+        }
+    }
+
+    private int getCurrentVersionCode(){
+        return BuildConfig.VERSION_CODE;
+    }
+
+    private void goToDownloadApk(String downloadUrl){
+        Intent intent = new Intent(mContext, DownloadApkService.class);
+        intent.putExtra("apkUrl", downloadUrl);
+        mContext.startService(intent);
+    }
+}
diff --git a/app/src/main/java/ai/suanzi/rtmpclient/DownloadApkService.java b/app/src/main/java/ai/suanzi/rtmpclient/DownloadApkService.java
new file mode 100644 (file)
index 0000000..09bfe43
--- /dev/null
@@ -0,0 +1,126 @@
+package ai.suanzi.rtmpclient;
+
+import android.app.IntentService;
+import org.apache.log4j.Logger;
+
+import android.content.Context;
+import android.content.Intent;
+import android.app.NotificationManager;
+import android.net.Uri;
+import android.support.v4.app.NotificationCompat;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.io.File;
+
+
+public class DownloadApkService extends IntentService {
+
+    private static final int BUFFER_SIZE = 10 * 1024;
+    private Logger gLogger = Logger.getLogger("DownloadApkService");
+
+    private static final int NOTIFICATION_ID = 0;
+    private NotificationManager mNotifyManager;
+    private NotificationCompat.Builder mBuilder;
+
+
+
+    public DownloadApkService() {
+        super("DownloadApkService");
+    }
+
+    @Override
+    protected void onHandleIntent(Intent intent) {
+        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+        mBuilder = new NotificationCompat.Builder(this);
+        String appName = getString(getApplicationInfo().labelRes);
+        int icon = getApplicationInfo().icon;
+        mBuilder.setContentTitle(appName).setSmallIcon(icon);
+
+        String urlStr = intent.getStringExtra("apkUrl");
+        gLogger.debug("onHandleIntent - " + urlStr);
+        InputStream in = null;
+        FileOutputStream out = null;
+        try{
+            URL url = new URL(urlStr);
+            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
+            urlConnection.setRequestMethod("GET");
+            urlConnection.setDoOutput(false);
+            urlConnection.setConnectTimeout(10 * 1000);
+            urlConnection.setReadTimeout(10 * 1000);
+            urlConnection.setRequestProperty("Connection", "Keep-Alive");
+            urlConnection.setRequestProperty("Charset", "UTF-8");
+            urlConnection.setRequestProperty("Accept-Encoding", "gzip, defalte");
+            urlConnection.connect();
+
+            long bytetotal = urlConnection.getContentLength();
+            int bytesum = 0;
+            int byteread = 0;
+            in = urlConnection.getInputStream();
+            File dir = this.getExternalCacheDir();
+            String apkName = urlStr.substring(urlStr.lastIndexOf("/") + 1, urlStr.length());
+            File apkFile = new File(dir, apkName);
+            out = new FileOutputStream(apkFile);
+            byte[] buffer = new byte[BUFFER_SIZE];
+
+            int limit = 0;
+            int oldProgress = 0;
+            while((byteread = in.read(buffer)) != -1){
+                bytesum += byteread;
+                out.write(buffer, 0, byteread);
+                int progress = (int) (bytesum * 100L / bytetotal);
+                if(progress != oldProgress){
+                    updateProgress(progress);
+                }
+                oldProgress = progress;
+            }
+            installApk(apkFile);
+            gLogger.debug("onHandleIntent, download apk finish");
+            mNotifyManager.cancel(NOTIFICATION_ID);
+        } catch (Exception e){
+            gLogger.error("download apk file error, " + e.getMessage());
+            e.printStackTrace();
+        } finally {
+            if (out != null){
+                try {
+                    out.close();
+                } catch (IOException e){
+                    gLogger.error(e.getMessage());
+                }
+            }
+            if (in != null) {
+                try {
+                    in.close();
+                } catch (IOException e){
+                    gLogger.error(e.getMessage());
+                }
+            }
+        }
+    }
+
+    private void updateProgress(int progress){
+        if((progress % 5) == 0)
+            gLogger.debug("updateProgress - " + progress + "%");
+    }
+
+    private void installApk(File apkFile) {
+
+        gLogger.debug("installApk - " + apkFile.toString());
+        Intent intent = new Intent(Intent.ACTION_VIEW);
+//        try {
+//            String[] command = { "chmod", "777", apkFile.toString() };
+//            ProcessBuilder builder = new ProcessBuilder(command);
+//            gLogger.error("installApk - start");
+//            builder.start();
+//        } catch (IOException e){
+//            gLogger.error(e.getMessage());
+//            e.printStackTrace();
+//        }
+        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // "application/vnd.android.package-archive"
+        startActivity(intent);
+    }
+}
index 789f518..e91b735 100644 (file)
@@ -18,6 +18,7 @@ import javax.mail.internet.MimeMultipart;
 
 import java.util.Date;
 
+import android.content.Context;
 import android.os.AsyncTask;
 import android.os.StrictMode;
 
@@ -36,14 +37,15 @@ public class LogUtil {
     private static final String FILE_NAME = "log.txt";
     private static final long MAX_SIZE = 1024 * 1024 * 10; // 10M
     private static String logFile = "";
-    private static File DIR;
+    //private static File DIR;
+    private static Context mContext;
 
 
-    public static void config(File dir) {
+    public static void config(Context context) {
         try {
             final LogConfigurator logConfigurator = new LogConfigurator();
-            DIR = dir;
-            logFile = dir + File.separator + FILE_NAME;
+            mContext = context;
+            logFile = context.getExternalFilesDir(null) + File.separator + FILE_NAME;
             logConfigurator.setFileName(logFile);
             logConfigurator.setRootLevel(Level.DEBUG);
             logConfigurator.setLevel("org.apache", Level.ERROR);
@@ -70,7 +72,8 @@ public class LogUtil {
 
         AsyncTask<Void, Integer, Boolean> mailTask = new AsyncTask<Void, Integer, Boolean>() {
 
-            private String zfile = DIR + File.separator + "log.zip";
+            //private String zfile = DIR + File.separator + "log.zip";
+            private String zfile = mContext.getExternalCacheDir() + File.separator + "log.zip";
 
 
 
index 3b86065..33ac4a6 100644 (file)
@@ -2,6 +2,7 @@ package ai.suanzi.rtmpclient;
 
 import android.content.IntentFilter;
 import android.hardware.Camera;
+import android.net.Uri;
 import android.support.design.widget.TextInputEditText;
 import android.support.v7.app.ActionBar;
 import android.support.v7.app.AppCompatActivity;
@@ -180,7 +181,7 @@ public class MainActivity extends AppCompatActivity implements MyService.MyServi
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        LogUtil.config(getExternalFilesDir(null));
+        LogUtil.config(this);
         gLogger = Logger.getLogger(getClass());
         gLogger.error("onCreate ---------> ");
         UserInfo.readConfig(getExternalFilesDir(null) + File.separator + "config", getMacAddr());
@@ -200,6 +201,8 @@ public class MainActivity extends AppCompatActivity implements MyService.MyServi
         }
         ////////// LogUtil.sendLogs();  /// Log test
         //LogUtil.sendLogs();
+
+        new CheckVersionInfoTask(MainActivity.this).execute();
     }
 
     @Override
index 3a21e5e..ae41a41 100644 (file)
@@ -151,6 +151,7 @@ public class MyService extends Service  implements Camera.PreviewCallback, Camer
         if(mCamera != null){
             try {
                 mCamera.stopPreview();
+                mCamera.setPreviewCallback(null);
                 mCamera.release();
                 mCamera = null;
             } catch (Exception e){
@@ -228,7 +229,7 @@ public class MyService extends Service  implements Camera.PreviewCallback, Camer
         if(ret != 0){
             gLogger.error("setRtmpUrl, initEncoder error");
         }
-        return ret == 0 ? true : false;
+        return ret == 0;
     }
 
     private void configCamera(Camera camera){
index 9076a9b..c874ba5 100644 (file)
@@ -28,10 +28,6 @@ public class UsbMonitor {
         mContext = context;
         mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
 
-        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
-        gLogger.error("device list size : " + deviceList.size());
-        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
-        //PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
         IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
         mContext.registerReceiver(mUsbReceiver, filter);
         filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
@@ -39,6 +35,17 @@ public class UsbMonitor {
         filter = new IntentFilter(ACTION_USB_PERMISSION);
         mContext.registerReceiver(mUsbReceiver, filter);
 
+        HashMap<String, UsbDevice> deviceList;
+        try {
+            deviceList = mUsbManager.getDeviceList();
+        } catch (NullPointerException e) {
+            gLogger.error(e.getMessage());
+            e.printStackTrace();
+            return;
+        }
+        gLogger.error("device list size : " + deviceList.size());
+        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
+        //PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
         while (deviceIterator.hasNext()) {
             UsbDevice device = deviceIterator.next();
             gLogger.error(device.toString());
@@ -49,16 +56,16 @@ public class UsbMonitor {
 
     public void unregisterReceiver (){
         mContext.unregisterReceiver(mUsbReceiver);
-
     }
 
     private boolean isUvcCamera(UsbDevice device){
+        if((device == null) || (device.getProductName() == null)) return false;
         return device.getProductName().toLowerCase().contains("camera") || (device.getDeviceProtocol() == 1);
     }
 
     public boolean hasUsbCamera(){
         gLogger.error("hasUsbCamera - size: " + mUsbCameraList.size());
-        return (mUsbCameraList.size() > 0 ? true : false);
+        return mUsbCameraList.size() > 0;
     }
 
     public int getUsbCameraCount(){
index 8bb20b9..403e506 100644 (file)
@@ -59,7 +59,8 @@ public class UserInfo {
             }
             cameraId = jobj.getString("cameraId");
         } catch (JSONException e){
-            gLogger.error("getConfig - error: " + e.getMessage());
+            gLogger.error("readConfig - error: " + e.getMessage());
+            macAddr = addr;
             e.printStackTrace();
         }
     }