From 6842386f2781653f25893e0c2769ca1353d6b540 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 28 May 2020 14:00:32 +0800 Subject: [PATCH 01/24] [v1.7.6] 1.set Camera FrameRate SystemProperties was changed to "persist.our.camera.fps". 2.Developer can set record video to Sd Card or Internal storage. 3.Developer can set errors will restart or stop. 4.fix record time to one minute. 5.add checkFileService. 6.fix setProp & setRunOfNumber bug. 7.fix config bug. 8.fix video release bug. --- app/build.gradle | 9 ---- app/src/main/AndroidManifest.xml | 1 - app/src/main/java/com/askey/record/Utils.java | 6 +-- .../com/askey/record/VideoRecordActivity.java | 47 ++++++++++--------- 4 files changed, 27 insertions(+), 36 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index e63b347..ddac65a 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,15 +1,6 @@ apply plugin: 'com.android.application' android { - - signingConfigs { - debug { - storeFile file('libs/debug.keystore') - storePassword 'android' - keyAlias = 'platform' - keyPassword 'android' - } - } compileSdkVersion 28 defaultConfig { applicationId "com.askey.record" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 023ba18..85191a4 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,7 +2,6 @@ diff --git a/app/src/main/java/com/askey/record/Utils.java b/app/src/main/java/com/askey/record/Utils.java index f348998..b5c5065 100644 --- a/app/src/main/java/com/askey/record/Utils.java +++ b/app/src/main/java/com/askey/record/Utils.java @@ -50,7 +50,7 @@ public class Utils { public static final String LOG_TITLE = "[Video_Record_Log]"; public static final SparseIntArray ORIENTATIONS = new SparseIntArray(); public static final double sdData = 1; - public static final boolean defaultProp = true; + public static final boolean defaultProp = false; public static int isRun = 0, Success = 0, Fail = 0; public static String TAG = "VideoRecordActivity"; public static String firstCamera = "0"; @@ -62,7 +62,7 @@ public class Utils { public static ArrayList firstFilePath, secondFilePath; public static ArrayList videoLogList = null; public static int isFinish = 999, delayTime = 60500, isFrame = 0, isQuality = 0; - public static boolean isReady = false, isRecord = false, isError = false, isNew = true; + public static boolean isReady = false, isRecord = false, isError = false, isNew = false; public static boolean fCamera = true, sCamera = true, getSdCard = false; public static String errorMessage = ""; @@ -75,7 +75,7 @@ public class Utils { //TODO Default Path public static String getPath() { - String path = "/storage/emulated/0/DCIM/"; + String path = "/sdcard/NORMAL/"; return path; } diff --git a/app/src/main/java/com/askey/record/VideoRecordActivity.java b/app/src/main/java/com/askey/record/VideoRecordActivity.java index 4c3567e..c23cf3c 100644 --- a/app/src/main/java/com/askey/record/VideoRecordActivity.java +++ b/app/src/main/java/com/askey/record/VideoRecordActivity.java @@ -133,6 +133,7 @@ public class VideoRecordActivity extends Activity { private mTimerTask timerTask = null; private Timer mTimer = null; private float mLaptime = 0.0f; + private int resetTime = 0; private void getSetting(Context context, EditText editText1, EditText editText2, EditText editText3, TextView editText4) { String input = readConfigFile(context, new File(getPath(), configName)); @@ -360,7 +361,7 @@ public void onDisconnected(CameraDevice camera) { if (autoRestart && isError) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } @@ -417,7 +418,7 @@ public void onDisconnected(CameraDevice camera) { if (autoRestart && isError) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } @@ -444,7 +445,7 @@ public void onError(CameraDevice camera, int error) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -893,7 +894,7 @@ private void stopRecord(String date, String cameraID) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -961,7 +962,7 @@ private void stopRecord(boolean preview) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -1117,7 +1118,7 @@ public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } else { @@ -1129,7 +1130,7 @@ public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } catch (Exception e) { @@ -1142,7 +1143,7 @@ public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -1207,21 +1208,21 @@ private MediaRecorder setUpMediaRecorder(String cameraId) { CamcorderProfile profile = isQuality == 1 ? profile_720 : profile_1080; mediaRecorder = new MediaRecorder(); // Step 2: Set sources - if (isCameraOne(cameraId)) - mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); +// if (isCameraOne(cameraId)) +// mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); - if (isCameraOne(cameraId)) - mediaRecorder.setAudioEncoder(profile.audioCodec); +// if (isCameraOne(cameraId)) +// mediaRecorder.setAudioEncoder(profile.audioCodec); mediaRecorder.setVideoEncoder(profile.videoCodec); mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); - if (isCameraOne(cameraId)) - mediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); +// if (isCameraOne(cameraId)) +// mediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); mediaRecorder.setVideoEncodingBitRate((int) (profile.videoBitRate / 3.3)); - if (isCameraOne(cameraId)) { - mediaRecorder.setAudioChannels(profile.audioChannels); - mediaRecorder.setAudioSamplingRate(profile.audioSampleRate); - } +// if (isCameraOne(cameraId)) { +// mediaRecorder.setAudioChannels(profile.audioChannels); +// mediaRecorder.setAudioSamplingRate(profile.audioSampleRate); +// } /*设置要捕获的视频的帧速率*/ // default is 24.6 mediaRecorder.setVideoFrameRate(!isNew ? isFrame == 0 ? 10 : 28 : 27); // 1 -> 12fps, 10 -> 16fps // Step 4: Set output file @@ -1249,7 +1250,7 @@ private MediaRecorder setUpMediaRecorder(String cameraId) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } else { videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); @@ -1279,7 +1280,7 @@ private void takePreview(String cameraId) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } if (null != texture) { @@ -1331,7 +1332,7 @@ public void onConfigureFailed(CameraCaptureSession session) { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -1352,7 +1353,7 @@ protected void updatePreview(CaptureRequest.Builder mPreviewBuilder, CameraCaptu if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } } @@ -1377,7 +1378,7 @@ public void run() { if (autoRestart) { final String dates = resetDate + ""; final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(dates, records), resetTime); } } //計算にゆらぎがあるので小数点第1位で丸める From fc3e9a9b7a342dd931b075783dd833707b39105d Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 28 May 2020 14:01:26 +0800 Subject: [PATCH 02/24] [v1.7.6] 1.set Camera FrameRate SystemProperties was changed to "persist.our.camera.fps". 2.Developer can set record video to Sd Card or Internal storage. 3.Developer can set errors will restart or stop. 4.fix record time to one minute. 5.add checkFileService. 6.fix setProp & setRunOfNumber bug. 7.fix config bug. 8.fix video release bug. --- app/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 19bb8ff..3325731 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -114,5 +114,5 @@ 7.fix config bug. 8.fix video release bug. --> - CDR9020_QTR(v1.7.6) + CDR9020_QTR_for_9010(v1.7.6) From 208c22103148fb2e7bec7ce134c802ac5da8abe8 Mon Sep 17 00:00:00 2001 From: hongren_su Date: Thu, 11 Jun 2020 17:42:07 +0800 Subject: [PATCH 03/24] update TAG --- app/src/main/java/com/askey/record/Utils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/askey/record/Utils.java b/app/src/main/java/com/askey/record/Utils.java index f3f0553..fb6ef19 100644 --- a/app/src/main/java/com/askey/record/Utils.java +++ b/app/src/main/java/com/askey/record/Utils.java @@ -52,7 +52,7 @@ public class Utils { public static final double sdData = 1; public static final boolean defaultProp = true; public static int isRun = 0, Success = 0, Fail = 0; - public static String TAG = "VideoRecordActivity"; + public static String TAG = "CDR9020_QTR"; public static String firstCamera = "0"; public static String secondCamera = "1"; public static String lastfirstCamera = "0"; From 058ef66aaf5df4f667e4bf1bec3ad1f59ec82e22 Mon Sep 17 00:00:00 2001 From: hongren_su Date: Thu, 11 Jun 2020 18:09:22 +0800 Subject: [PATCH 04/24] add defaultProp, defaultRun; --- app/src/main/java/com/askey/record/Config.java | 3 ++- app/src/main/java/com/askey/record/Utils.java | 13 ++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/askey/record/Config.java b/app/src/main/java/com/askey/record/Config.java index fd38de0..cac1156 100644 --- a/app/src/main/java/com/askey/record/Config.java +++ b/app/src/main/java/com/askey/record/Config.java @@ -5,6 +5,7 @@ import static com.askey.record.Utils.CONFIG_TITLE; import static com.askey.record.Utils.configName; import static com.askey.record.Utils.defaultProp; +import static com.askey.record.Utils.defaultRun; import static com.askey.record.Utils.logName; public class Config { @@ -12,7 +13,7 @@ public class Config { protected Context context; protected String firstCamera = "0"; protected String secondCamera = "1"; - protected int numberOfRuns = 999; + protected int numberOfRuns = defaultRun; protected boolean New = defaultProp; public Config(Context context) { diff --git a/app/src/main/java/com/askey/record/Utils.java b/app/src/main/java/com/askey/record/Utils.java index fb6ef19..22fd16f 100644 --- a/app/src/main/java/com/askey/record/Utils.java +++ b/app/src/main/java/com/askey/record/Utils.java @@ -26,6 +26,10 @@ import static com.askey.record.VideoRecordActivity.saveLog; public class Utils { + //------------------------------------------------------------------------------- + public static final boolean defaultProp = true; + public static final int defaultRun = 999; + //------------------------------------------------------------------------------- public static final double[] DFRAME_RATE = {16, 27.5}, NEW_DFRAME_RATE = {14, 28}; public static final String[] FRAME_RATE = {"16fps", "27.5fps"}, @@ -44,13 +48,12 @@ public class Utils { public static final String EXTRA_VIDEO_VERSION = "RestartActivity.version"; public static final String EXTRA_VIDEO_REFORMAT = "RestartActivity.reformat"; public static final String NO_SD_CARD = "SD card is not available!"; + public static final SparseIntArray ORIENTATIONS = new SparseIntArray(); public static final String configName = "VideoRecordConfig.ini"; public static final String logName = "VideoRecordLog.ini"; public static final String CONFIG_TITLE = "[Video_Record_Config]"; public static final String LOG_TITLE = "[Video_Record_Log]"; - public static final SparseIntArray ORIENTATIONS = new SparseIntArray(); public static final double sdData = 1; - public static final boolean defaultProp = true; public static int isRun = 0, Success = 0, Fail = 0; public static String TAG = "CDR9020_QTR"; public static String firstCamera = "0"; @@ -62,7 +65,7 @@ public class Utils { public static ArrayList firstFilePath, secondFilePath; public static ArrayList videoLogList = null; public static int isFinish = 999, delayTime = 60500, isFrame = 0, isQuality = 0; - public static boolean isReady = false, isRecord = false, isError = false, isNew = true; + public static boolean isReady = false, isRecord = false, isError = false, isNew = defaultProp; public static boolean fCamera = true, sCamera = true, getSdCard = false; public static String errorMessage = ""; @@ -371,13 +374,13 @@ public static void setConfigFile(Context context, File file, View view, boolean EditText editText_1 = view.findViewById(R.id.dialog_editText_1); EditText editText_2 = view.findViewById(R.id.dialog_editText_2); EditText editText_3 = view.findViewById(R.id.dialog_editText_3); - int isFinish = 999; + int isFinish = defaultRun; if (!reset) { if (isInteger(editText_3.getText().toString(), false)) { isFinish = Integer.parseInt(editText_3.getText().toString()); } else { - isFinish = 999; + isFinish = defaultRun; } } From 6c4b552d762cdb6ecc1d8cb4d3e67c6128fcd7fb Mon Sep 17 00:00:00 2001 From: hongren_su Date: Fri, 10 Jul 2020 13:53:03 +0800 Subject: [PATCH 05/24] add defaultProp, defaultRun; --- app/src/main/AndroidManifest.xml | 2 + .../com/askey/record/VideoRecordActivity.java | 58 +++++++++++++++++-- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 023ba18..a14d8ed 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,6 +7,8 @@ + + diff --git a/app/src/main/java/com/askey/record/VideoRecordActivity.java b/app/src/main/java/com/askey/record/VideoRecordActivity.java index 388bad6..816acca 100644 --- a/app/src/main/java/com/askey/record/VideoRecordActivity.java +++ b/app/src/main/java/com/askey/record/VideoRecordActivity.java @@ -20,11 +20,15 @@ import android.hardware.camera2.CaptureRequest; import android.media.CamcorderProfile; import android.media.MediaRecorder; +import android.os.BatteryManager; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; +import android.os.PowerManager; +import android.os.SystemClock; import android.os.SystemProperties; +import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.util.Size; @@ -112,7 +116,7 @@ public class VideoRecordActivity extends Activity { //TODO 使用SD Card儲存 SD_Mode 設置為 true - public static boolean SD_Mode = true; + public static boolean SD_Mode = false; //TODO 使用錯誤重啟 autoRestart 設置為 true public static boolean autoRestart = true; public static boolean extraRecordStatus = false, onRestart = false; @@ -607,17 +611,62 @@ public void handleMessage(android.os.Message msg) { } } }; - this.registerReceiver(new BroadcastReceiver() { + class status { + int battery; + String type; + status(int battery, String type) { + this.battery = battery; + this.type = type; + } + } + status[] statusConstants = new status[]{ + new status(BatteryManager.BATTERY_STATUS_UNKNOWN, "Unknown"), + new status(BatteryManager.BATTERY_STATUS_CHARGING, "Charging"), + new status(BatteryManager.BATTERY_STATUS_DISCHARGING, "Discharging"), + new status(BatteryManager.BATTERY_STATUS_NOT_CHARGING, "Not charging"), + new status(BatteryManager.BATTERY_STATUS_FULL, "Full")}; + this.registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { //Battery - videoLogList.add(new LogMsg("Battery:" + intent.getIntExtra("level", 0) + "%", mLog.e)); + if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { + //level + videoLogList.add(new LogMsg("Battery level:" + intent.getIntExtra("level", 0) + "%", mLog.e)); + //status + String type = ""; + for (status i : statusConstants) { + type = i.type; + if (intent.getIntExtra("status", 0) == i.battery) { + videoLogList.add(new LogMsg("Battery status:" + type, mLog.e)); + break; + } + } + if (!type.equals("")) + if (!type.equals("Charging")) { + try { + PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); + pm.getClass().getMethod("goToSleep", long.class).invoke(pm, SystemClock.uptimeMillis()); + } catch (Exception ignored) { + } + stopRecordAndSaveLog(false); + setAirplaneModeOn(true, VideoRecordActivity.this); + } new Handler().post(() -> saveLog(getApplicationContext(), false, false)); } } }, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } + private void setAirplaneModeOn(boolean enabling, Context context) { + // Change the system setting + Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, + enabling ? 1 : 0); + + // Post the intent + Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); + intent.putExtra("state", enabling); + context.sendBroadcastAsUser(intent, android.os.Process.myUserHandle()); + } + private void setSetting() { if (!isRecord) { boolean[] check = checkConfigFile(this, new File(getPath(), configName), false); @@ -1018,6 +1067,7 @@ private void startRecord(String cameraId) { codeDate1 = getCalendarTime(); if (isCameraOne(cameraId)) { + setAirplaneModeOn(false, this); checkSdCardFromFileList(); runOnUiThread(() -> { if (mTimer == null) { From 83d2b99b514543c55d1ff547db0218d54cfbc4f5 Mon Sep 17 00:00:00 2001 From: hongren_su Date: Thu, 16 Jul 2020 10:03:06 +0800 Subject: [PATCH 06/24] add defaultProp, defaultRun; --- .../main/java/com/askey/record/VideoRecordActivity.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/askey/record/VideoRecordActivity.java b/app/src/main/java/com/askey/record/VideoRecordActivity.java index 816acca..a741bcb 100644 --- a/app/src/main/java/com/askey/record/VideoRecordActivity.java +++ b/app/src/main/java/com/askey/record/VideoRecordActivity.java @@ -116,7 +116,7 @@ public class VideoRecordActivity extends Activity { //TODO 使用SD Card儲存 SD_Mode 設置為 true - public static boolean SD_Mode = false; + public static boolean SD_Mode = true; //TODO 使用錯誤重啟 autoRestart 設置為 true public static boolean autoRestart = true; public static boolean extraRecordStatus = false, onRestart = false; @@ -640,15 +640,16 @@ public void onReceive(Context context, Intent intent) { break; } } - if (!type.equals("")) + // TODO Airplane + if (!type.equals("") && isRecord) if (!type.equals("Charging")) { try { PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); pm.getClass().getMethod("goToSleep", long.class).invoke(pm, SystemClock.uptimeMillis()); } catch (Exception ignored) { } - stopRecordAndSaveLog(false); setAirplaneModeOn(true, VideoRecordActivity.this); + stopRecordAndSaveLog(true); } new Handler().post(() -> saveLog(getApplicationContext(), false, false)); } From d2e311866d7421ecfc029bfd6a593f9f821ffcb8 Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 5 Nov 2020 14:56:29 +0800 Subject: [PATCH 07/24] [v1.7.7] 1.fix save bug. --- app/build.gradle | 27 +- app/src/main/AndroidManifest.xml | 17 +- app/src/main/java/com/askey/record/Utils.java | 171 ++-- .../com/askey/record/VideoRecordActivity.java | 943 ++++++++---------- .../com/askey/record/checkFileService.java | 147 --- .../com/askey/record/checkSdCardService.java | 158 --- .../com/askey/record/copyFileService.java | 107 -- .../com/askey/record/restartActivity.java | 5 +- .../java/com/askey/record/saveLogService.java | 120 --- .../java/com/askey/widget/CommandUtil.java | 162 --- .../askey/widget/CustomPageTransformer.java | 32 - .../java/com/askey/widget/CustomTextView.java | 0 .../java/com/askey/widget/PropertyUtils.java | 30 - .../askey/widget/VerticalPageTransformer.java | 0 .../askey/widget/VerticalPagerContainer.java | 0 .../com/askey/widget/VerticalViewPager.java | 3 +- .../java/com/askey/widget/ViewHolder.java | 7 - .../com/askey/widget/mLogListAdapter.java | 58 -- .../java/com/askey/widget/mPagerAdapter.java | 33 - .../main/res/layout/activity_video_record.xml | 55 +- app/src/main/res/layout/layout_setting.xml | 7 +- .../main/res/layout/style_setting_item.xml | 0 app/src/main/res/layout/style_text_item.xml | 0 .../main/res/layout/style_vertical_item.xml | 0 app/src/main/res/values/attrs.xml | 0 app/src/main/res/values/strings.xml | 2 +- build.gradle | 4 +- gradle.properties | 18 +- gradle/wrapper/gradle-wrapper.properties | 3 +- 29 files changed, 548 insertions(+), 1561 deletions(-) delete mode 100644 app/src/main/java/com/askey/record/checkFileService.java delete mode 100644 app/src/main/java/com/askey/record/checkSdCardService.java delete mode 100644 app/src/main/java/com/askey/record/copyFileService.java delete mode 100644 app/src/main/java/com/askey/record/saveLogService.java delete mode 100644 app/src/main/java/com/askey/widget/CommandUtil.java delete mode 100644 app/src/main/java/com/askey/widget/CustomPageTransformer.java mode change 100755 => 100644 app/src/main/java/com/askey/widget/CustomTextView.java delete mode 100755 app/src/main/java/com/askey/widget/PropertyUtils.java mode change 100755 => 100644 app/src/main/java/com/askey/widget/VerticalPageTransformer.java mode change 100755 => 100644 app/src/main/java/com/askey/widget/VerticalPagerContainer.java mode change 100755 => 100644 app/src/main/java/com/askey/widget/VerticalViewPager.java delete mode 100644 app/src/main/java/com/askey/widget/ViewHolder.java delete mode 100644 app/src/main/java/com/askey/widget/mLogListAdapter.java delete mode 100644 app/src/main/java/com/askey/widget/mPagerAdapter.java mode change 100755 => 100644 app/src/main/res/layout/style_setting_item.xml mode change 100755 => 100644 app/src/main/res/layout/style_text_item.xml mode change 100755 => 100644 app/src/main/res/layout/style_vertical_item.xml mode change 100755 => 100644 app/src/main/res/values/attrs.xml diff --git a/app/build.gradle b/app/build.gradle index ddac65a..dbb6ae8 100755 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,15 +1,23 @@ apply plugin: 'com.android.application' android { + signingConfigs { + debug { + storeFile file('libs/debug.keystore') + storePassword 'android' + keyAlias = 'platform' + keyPassword 'android' + } + } compileSdkVersion 28 defaultConfig { applicationId "com.askey.record" minSdkVersion 27 //noinspection OldTargetApi targetSdkVersion 27 - versionCode 2 + versionCode 1 versionName "1.0" - testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' signingConfig signingConfigs.debug } buildTypes { @@ -18,6 +26,8 @@ android { proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } buildToolsVersion '28.0.3' @@ -32,16 +42,17 @@ tasks.withType(JavaCompile) { } dependencies { - compileOnly files('libs/layoutlib.jar') + //compileOnly files('libs/layoutlib.jar') implementation fileTree(include: ['*.jar'], dir: 'libs') //noinspection GradleDependency,GradleCompatible - implementation 'com.android.support.constraint:constraint-layout:1.0.2' + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' //noinspection GradleDependency,GradleCompatible - implementation 'com.android.support.constraint:constraint-layout-solver:1.0.2' + implementation 'androidx.constraintlayout:constraintlayout-solver:1.1.3' //noinspection GradleDependency,GradleCompatible - implementation 'com.android.support:design:27.1.0' + implementation 'com.google.android.material:material:1.0.0' //noinspection GradleDependency,GradleCompatible - implementation 'com.android.support:support-v4:27.1.0' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' //noinspection GradleDependency,GradleCompatible - implementation 'com.android.support:appcompat-v7:27.1.0' + implementation 'androidx.appcompat:appcompat:1.0.0' + testImplementation 'junit:junit:4.13-rc-1' } \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a854b5d..6fcc9f9 100755 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,21 +2,24 @@ + - - - + + + + - - + + - - - - diff --git a/app/src/main/java/com/askey/record/Utils.java b/app/src/main/java/com/askey/record/Utils.java index f348998..1bafaaa 100644 --- a/app/src/main/java/com/askey/record/Utils.java +++ b/app/src/main/java/com/askey/record/Utils.java @@ -2,7 +2,6 @@ import android.annotation.SuppressLint; import android.content.Context; -import android.os.Handler; import android.util.SparseIntArray; import android.view.Surface; import android.view.View; @@ -11,12 +10,14 @@ import com.askey.widget.LogMsg; import com.askey.widget.mLog; +import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; +import java.text.SimpleDateFormat; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; @@ -26,44 +27,36 @@ import static com.askey.record.VideoRecordActivity.saveLog; public class Utils { - public static final double[] DFRAME_RATE = {16, 27.5}, - NEW_DFRAME_RATE = {14, 28}; + //------------------------------------------------------------------------------- + public static final boolean defaultProp = false; + public static final int defaultRun = 999; + //------------------------------------------------------------------------------- + public static final double[] NEW_DFRAME_RATE = {14, 28}; public static final String[] FRAME_RATE = {"16fps", "27.5fps"}, NEW_FRAME_RATE = {"14fps", "28fps"}; - public static final String[] FPS = {"140", "280"}; - public static final String FRAMESKIP = "persist.our.camera.fps"; public static final String EXTRA_VIDEO_RUN = "RestartActivity.run"; public static final String EXTRA_VIDEO_FAIL = "RestartActivity.fail"; public static final String EXTRA_VIDEO_RESET = "RestartActivity.reset"; public static final String EXTRA_VIDEO_RECORD = "RestartActivity.record"; public static final String EXTRA_VIDEO_SUCCESS = "RestartActivity.success"; - public static final String EXTRA_VIDEO_COPY = "RestartActivity.copy"; - public static final String EXTRA_VIDEO_PATH = "RestartActivity.path"; - public static final String EXTRA_VIDEO_PASTE = "RestartActivity.paste"; - public static final String EXTRA_VIDEO_REMOVE = "RestartActivity.remove"; - public static final String EXTRA_VIDEO_VERSION = "RestartActivity.version"; - public static final String EXTRA_VIDEO_REFORMAT = "RestartActivity.reformat"; public static final String NO_SD_CARD = "SD card is not available!"; + public static final SparseIntArray ORIENTATIONS = new SparseIntArray(); public static final String configName = "VideoRecordConfig.ini"; public static final String logName = "VideoRecordLog.ini"; - public static final String CONFIG_TITLE = "[Video_Record_Config]"; - public static final String LOG_TITLE = "[Video_Record_Log]"; - public static final SparseIntArray ORIENTATIONS = new SparseIntArray(); + public static final String CONFIG_TITLE = "[QTR_Config]"; + public static final String LOG_TITLE = "[QTR_Log]"; public static final double sdData = 1; - public static final boolean defaultProp = true; public static int isRun = 0, Success = 0, Fail = 0; - public static String TAG = "VideoRecordActivity"; + public static String TAG = "CDR9020_QTR"; public static String firstCamera = "0"; public static String secondCamera = "1"; public static String lastfirstCamera = "0"; public static String lastsecondCamera = "1"; - public static String firstFile = ""; - public static String secondFile = ""; - public static ArrayList firstFilePath, secondFilePath; + public static String firstFile, secondFile; public static ArrayList videoLogList = null; public static int isFinish = 999, delayTime = 60500, isFrame = 0, isQuality = 0; - public static boolean isReady = false, isRecord = false, isError = false, isNew = true; - public static boolean fCamera = true, sCamera = true, getSdCard = false; + public static boolean isReady = false, isRecord = false, isError = false, isNew = defaultProp; + public static boolean fCamera = false, sCamera = false, getSdCard = false; public static String errorMessage = ""; static { @@ -75,30 +68,33 @@ public class Utils { //TODO Default Path public static String getPath() { - String path = "/storage/emulated/0/DCIM/"; - return path; + return "/storage/emulated/0/DCIM/"; } public static String getSDPath() { String path = ""; if (SD_Mode) { try { - long start = System.currentTimeMillis(); - long end = start + 10000; + long start = (System.currentTimeMillis() / 1000) % 60; + long end = start + 10; Runtime run = Runtime.getRuntime(); String cmd = "ls /storage"; Process pr = run.exec(cmd); - BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); + InputStreamReader input = new InputStreamReader(pr.getInputStream()); + BufferedReader buf = new BufferedReader(input); String line; while ((line = buf.readLine()) != null) { if (!line.equals("self") && !line.equals("emulated") && !line.equals("enterprise") && !line.contains("sdcard")) { path = "/storage/" + line + "/"; break; } - if (System.currentTimeMillis() > end) { + if ((System.currentTimeMillis() / 1000) % 60 > end) { + videoLogList.add(new LogMsg("getSDPath time out.", mLog.d)); break; } } + buf.close(); + input.close(); } catch (Exception e) { e.printStackTrace(); } @@ -108,10 +104,6 @@ public static String getSDPath() { return path; } - public static int getFail() { - return Fail; - } - public static int getIsRun() { return isRun; } @@ -120,6 +112,10 @@ public static int getSuccess() { return Success; } + public static int getFail() { + return Fail; + } + public static int getReset() { return onReset; } @@ -138,7 +134,7 @@ public static boolean isInteger(String s, boolean zero) { public static boolean isBoolean(String s) { try { - boolean t = Boolean.valueOf(s); + Boolean.valueOf(s); return true; } catch (Exception e) { e.printStackTrace(); @@ -147,12 +143,8 @@ public static boolean isBoolean(String s) { } public static void setTestTime(int min) { - if (min == 999) - videoLogList.add(new LogMsg("setRecord time: unlimited times.", mLog.d)); - else { - videoLogList.add(new LogMsg("setRecord time: " + min + " min.", mLog.d)); - } - isFinish = min; + videoLogList.add(new LogMsg("setRecord time: " + min + " min.", mLog.d)); + isFinish = min == 999 ? min : min * 2; } public static void checkConfigFile(Context context, boolean first) { @@ -180,15 +172,6 @@ public static void checkConfigFile(Context context, boolean first) { } } - public static void checkLogFile(Context context, File file, ArrayList list) { - String input = readConfigFile(context, file); - if (input.length() > 0) { - String[] read = input.split("\r\n"); - for (String s : read) - list.add(s); - } - } - public static boolean[] checkConfigFile(Context context, File file, boolean firstOne) { try { String input = readConfigFile(context, file); @@ -200,35 +183,35 @@ public static boolean[] checkConfigFile(Context context, File file, boolean firs String first = "firstCameraID = ", second = "secondCameraID = "; String code = "numberOfRuns = ", prop = "setProperty = "; for (String s : read) - if (s.indexOf(title) != -1) { + if (s.contains(title)) { target++; t = s.indexOf(title) + title.length(); title = s.substring(t); break; } for (String s : read) - if (s.indexOf(first) != -1) { + if (s.contains(first)) { target++; t = s.indexOf(first) + first.length(); first = s.substring(t); break; } for (String s : read) - if (s.indexOf(second) != -1) { + if (s.contains(second)) { target++; t = s.indexOf(second) + second.length(); second = s.substring(t); break; } for (String s : read) - if (s.indexOf(code) != -1) { + if (s.contains(code)) { target++; t = s.indexOf(code) + code.length(); code = s.substring(t); break; } for (String s : read) - if (s.indexOf(prop) != -1) { + if (s.contains(prop)) { target++; t = s.indexOf(prop) + prop.length(); prop = s.substring(t); @@ -248,7 +231,7 @@ public static boolean[] checkConfigFile(Context context, File file, boolean firs videoLogList.add(new LogMsg("Inner and External can't be used at the same time.", mLog.e)); reformat = true; } else { - if (isCameraID(context, first.split("\n")[0], second.split("\n")[0])) { + if (isCameraID(first.split("\n")[0], second.split("\n")[0])) { lastfirstCamera = firstOne ? first : firstCamera; lastsecondCamera = firstOne ? second : secondCamera; firstCamera = first; @@ -267,17 +250,18 @@ public static boolean[] checkConfigFile(Context context, File file, boolean firs } if (isInteger(code.split("\n")[0], true)) { int min = Integer.parseInt(code.split("\n")[0]); - if (min < 0) { + if (min <= 0) { videoLogList.add(new LogMsg("The test time must be a positive number.", mLog.e)); reformat = true; + } else { + setTestTime(min); } - setTestTime(min); } else { videoLogList.add(new LogMsg("Unknown Record Times.", mLog.e)); reformat = true; } if (isBoolean(prop)) { - boolean getProp = Boolean.valueOf(prop); + boolean getProp = Boolean.parseBoolean(prop); if (isNew != getProp) isPropChange = true; isNew = getProp; @@ -289,16 +273,16 @@ public static boolean[] checkConfigFile(Context context, File file, boolean firs } } if (update) { - String logString = LOG_TITLE + context.getString(R.string.app_name) + "\r\n"; + StringBuilder logString = new StringBuilder(LOG_TITLE + context.getString(R.string.app_name) + "\r\n"); videoLogList.add(new LogMsg("Reformat the Log file.", mLog.e)); for (LogMsg logs : videoLogList) { String time = logs.time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " run:" + logs.runTime + " -> "; - logString += (time + logs.msg + "\r\n"); + logString.append(time).append(logs.msg).append("\r\n"); } try { FileOutputStream output = new FileOutputStream(new File(getPath(), logName), false); - output.write(logString.getBytes()); + output.write(logString.toString().getBytes()); output.close(); videoLogList.clear(); @@ -318,7 +302,7 @@ public static boolean[] checkConfigFile(Context context, File file, boolean firs } } - public static boolean isCameraID(Context context, String f, String b) { + public static boolean isCameraID(String f, String b) { try { if (Integer.parseInt(f) <= -1) { videoLogList.add(new LogMsg("The Camera ID must be a positive number.", mLog.e)); @@ -370,16 +354,6 @@ public static boolean isCameraID(Context context, String f, String b) { public static void setConfigFile(Context context, File file, View view, boolean reset) { EditText editText_1 = view.findViewById(R.id.dialog_editText_1); EditText editText_2 = view.findViewById(R.id.dialog_editText_2); - EditText editText_3 = view.findViewById(R.id.dialog_editText_3); - int isFinish = 999; - - if (!reset) { - if (isInteger(editText_3.getText().toString(), false)) { - isFinish = Integer.parseInt(editText_3.getText().toString()); - } else { - isFinish = 999; - } - } //toast(context, "Ready to write.", mLog.w); writeConfigFile(context, file, ( @@ -397,26 +371,28 @@ public static void reformatConfigFile(Context context, File file) { public static String readConfigFile(Context context, File file) { String tmp = ""; try { - FileInputStream input = new FileInputStream(file); - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; + byte[] buffer = new byte[100]; int length; - while ((length = input.read(buffer)) != -1) { + FileInputStream fis = new FileInputStream(file); + BufferedInputStream bis = new BufferedInputStream(fis); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + while ((length = bis.read(buffer)) != -1) { bytes.write(buffer, 0, length); } tmp += bytes.toString(); bytes.close(); - input.close(); + bis.close(); + fis.close(); } catch (Exception e) { e.printStackTrace(); isError = true; getSdCard = !getSDPath().equals(""); - videoLogList.add(new LogMsg("Read failed. " + NO_SD_CARD + ". <============ Crash here", mLog.e)); - new Handler().post(() -> saveLog(context, false, false)); - errorMessage = "Read failed." + NO_SD_CARD + "<============ Crash here"; + videoLogList.add(new LogMsg("Read failed. <============ Crash here", mLog.e)); + saveLog(context, false, false); + errorMessage = "Read failed. <============ Crash here"; videoLogList.add(new LogMsg("Read failed.", mLog.e)); tmp += ("App Version:" + context.getString(R.string.app_name) + "\r\n"); - tmp += (NO_SD_CARD); + tmp += ("Read failed. <============ Crash here"); return tmp; } return tmp; @@ -424,50 +400,37 @@ public static String readConfigFile(Context context, File file) { public static void writeConfigFile(Context context, File file, String[] str) { if (getSdCard) { - String tmp = ""; + StringBuilder tmp = new StringBuilder(); for (String s : str) - tmp += s; + tmp.append(s); try { FileOutputStream output = new FileOutputStream(file); - output.write(tmp.getBytes()); + output.write(tmp.toString().getBytes()); output.close(); } catch (Exception e) { e.printStackTrace(); isError = true; getSdCard = !getSDPath().equals(""); - videoLogList.add(new LogMsg("Write failed. " + NO_SD_CARD + ". <============ Crash here", mLog.e)); - new Handler().post(() -> saveLog(context, false, false)); - errorMessage = "Write failed. " + NO_SD_CARD + "<============ Crash here"; + videoLogList.add(new LogMsg("Write failed. <============ Crash here", mLog.e)); + saveLog(context, false, false); + errorMessage = "Write failed. <============ Crash here"; } } else { videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); } } - @SuppressLint("DefaultLocale") + + @SuppressLint({"DefaultLocale", "SimpleDateFormat"}) public static String getCalendarTime() { - String d, h, i, s; Calendar calendar = Calendar.getInstance(); - d = String.format("%02d", calendar.get(Calendar.DATE)); - h = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)); - i = String.format("%02d", calendar.get(Calendar.MINUTE)); - s = String.format("%02d", calendar.get(Calendar.SECOND)); - - return d + h + i + s + ""; + return new SimpleDateFormat("HHmmss").format(calendar.getTime()) + ""; } - @SuppressLint("DefaultLocale") - public static String getCalendarTime(boolean isCameraOne) { - String y, m, d, h, i, s; + @SuppressLint({"DefaultLocale", "SimpleDateFormat"}) + public static String getCalendarTime(String isCameraOne) { Calendar calendar = Calendar.getInstance(); - y = String.format("%02d", calendar.get(Calendar.YEAR)); - m = String.format("%02d", (calendar.get(Calendar.MONTH) - 1)); - d = String.format("%02d", calendar.get(Calendar.DATE)); - h = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)); - i = String.format("%02d", calendar.get(Calendar.MINUTE)); - s = String.format("%02d", calendar.get(Calendar.SECOND)); - - return "v" + y + m + d + h + i + s + (isCameraOne ? "f" : "s"); + return "v" + new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime()) + (isCameraOne.equals(firstCamera) ? "f" : (isCameraOne.equals(secondCamera) ? "s" : "t")); } public static String getFileExtension(String fullName) { diff --git a/app/src/main/java/com/askey/record/VideoRecordActivity.java b/app/src/main/java/com/askey/record/VideoRecordActivity.java index 4c3567e..be51050 100644 --- a/app/src/main/java/com/askey/record/VideoRecordActivity.java +++ b/app/src/main/java/com/askey/record/VideoRecordActivity.java @@ -19,13 +19,14 @@ import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.media.CamcorderProfile; +import android.media.MediaExtractor; +import android.media.MediaFormat; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; -import android.os.SystemProperties; -import android.support.v4.app.ActivityCompat; +import android.os.StatFs; import android.util.Log; import android.util.Size; import android.view.LayoutInflater; @@ -36,63 +37,57 @@ import android.widget.ListView; import android.widget.TextView; -import com.askey.widget.CustomPageTransformer; +import androidx.core.app.ActivityCompat; + import com.askey.widget.CustomTextView; import com.askey.widget.HomeListen; import com.askey.widget.LogMsg; -import com.askey.widget.PropertyUtils; -import com.askey.widget.VerticalViewPager; import com.askey.widget.mListAdapter; import com.askey.widget.mLog; -import com.askey.widget.mPagerAdapter; import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; import java.math.BigDecimal; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Timer; import java.util.TimerTask; -import static com.askey.record.Utils.EXTRA_VIDEO_COPY; import static com.askey.record.Utils.EXTRA_VIDEO_FAIL; -import static com.askey.record.Utils.EXTRA_VIDEO_PASTE; -import static com.askey.record.Utils.EXTRA_VIDEO_PATH; import static com.askey.record.Utils.EXTRA_VIDEO_RECORD; -import static com.askey.record.Utils.EXTRA_VIDEO_REFORMAT; -import static com.askey.record.Utils.EXTRA_VIDEO_REMOVE; import static com.askey.record.Utils.EXTRA_VIDEO_RESET; import static com.askey.record.Utils.EXTRA_VIDEO_RUN; import static com.askey.record.Utils.EXTRA_VIDEO_SUCCESS; -import static com.askey.record.Utils.EXTRA_VIDEO_VERSION; -import static com.askey.record.Utils.FPS; -import static com.askey.record.Utils.FRAMESKIP; import static com.askey.record.Utils.FRAME_RATE; +import static com.askey.record.Utils.Fail; +import static com.askey.record.Utils.LOG_TITLE; import static com.askey.record.Utils.NEW_FRAME_RATE; import static com.askey.record.Utils.NO_SD_CARD; +import static com.askey.record.Utils.Success; import static com.askey.record.Utils.TAG; import static com.askey.record.Utils.checkConfigFile; import static com.askey.record.Utils.configName; import static com.askey.record.Utils.delayTime; import static com.askey.record.Utils.errorMessage; import static com.askey.record.Utils.fCamera; -import static com.askey.record.Utils.Fail; import static com.askey.record.Utils.firstCamera; import static com.askey.record.Utils.firstFile; -import static com.askey.record.Utils.firstFilePath; import static com.askey.record.Utils.getCalendarTime; import static com.askey.record.Utils.getFail; import static com.askey.record.Utils.getIsRun; import static com.askey.record.Utils.getPath; +import static com.askey.record.Utils.getReset; import static com.askey.record.Utils.getSDPath; import static com.askey.record.Utils.getSdCard; import static com.askey.record.Utils.getSuccess; import static com.askey.record.Utils.isError; import static com.askey.record.Utils.isFinish; import static com.askey.record.Utils.isFrame; -import static com.askey.record.Utils.isInteger; import static com.askey.record.Utils.isNew; -import static com.askey.record.Utils.isQuality; import static com.askey.record.Utils.isReady; import static com.askey.record.Utils.isRecord; import static com.askey.record.Utils.isRun; @@ -102,39 +97,43 @@ import static com.askey.record.Utils.readConfigFile; import static com.askey.record.Utils.reformatConfigFile; import static com.askey.record.Utils.sCamera; +import static com.askey.record.Utils.sdData; import static com.askey.record.Utils.secondCamera; import static com.askey.record.Utils.secondFile; -import static com.askey.record.Utils.secondFilePath; import static com.askey.record.Utils.setConfigFile; -import static com.askey.record.Utils.Success; import static com.askey.record.Utils.videoLogList; -import static com.askey.record.restartActivity.EXTRA_MAIN_PID; +@SuppressLint("SetTextI18n") public class VideoRecordActivity extends Activity { - //TODO 使用SD Card儲存 SD_Mode 設置為 true + + //------------------------------------------------------------------------------- + public static final boolean Open_f_Camera = true, Open_s_Camera = true; + //------------------------------------------------------------------------------- + private final int delayMillis = 3000; + // 使用SD Card儲存 SD_Mode 設置為 true public static boolean SD_Mode = true; - //TODO 使用錯誤重啟 autoRestart 設置為 true + // 使用錯誤重啟 autoRestart 設置為 true public static boolean autoRestart = true; + // 使用自動停止錄影 autoStopRecord 設置為 true + public static boolean autoStopRecord = true; public static boolean extraRecordStatus = false, onRestart = false; public static int onRun = 0, onSuccess = 0, onFail = 0, onReset = 0; - private static String codeDate0, codeDate1, resetDate; + private static String codeDate0, codeDate1; private Size mPreviewSize; private TextureView mTextureView0, mTextureView1; private CameraDevice mCameraDevice0, mCameraDevice1; private CameraCaptureSession mPreviewSession0, mPreviewSession1; private CameraDevice.StateCallback mStateCallback0, mStateCallback1; - private CaptureRequest.Builder mPreviewBuilder0, mPreviewBuilder1; private MediaRecorder mMediaRecorder0, mMediaRecorder1; private Handler mainHandler, demoHandler; private Handler recordHandler0, recordHandler1, stopRecordHandler0, stopRecordHandler1; private Handler backgroundHandler0, backgroundHandler1; - private HandlerThread thread0, thread1; private HomeListen home; private mTimerTask timerTask = null; private Timer mTimer = null; private float mLaptime = 0.0f; - private void getSetting(Context context, EditText editText1, EditText editText2, EditText editText3, TextView editText4) { + private void getSetting(Context context, EditText editText1, EditText editText2, TextView editText3, TextView editText4) { String input = readConfigFile(context, new File(getPath(), configName)); if (input.length() > 0) { String[] read = input.split("\r\n"); @@ -142,25 +141,25 @@ private void getSetting(Context context, EditText editText1, EditText editText2, String first = "firstCameraID = ", second = "secondCameraID = "; String code = "numberOfRuns = ", prop = "setProperty = "; for (String s : read) - if (s.indexOf(first) != -1) { + if (s.contains(first)) { t = s.indexOf(first) + first.length(); first = s.substring(t); break; } for (String s : read) - if (s.indexOf(second) != -1) { + if (s.contains(second)) { t = s.indexOf(second) + second.length(); second = s.substring(t); break; } for (String s : read) - if (s.indexOf(code) != -1) { + if (s.contains(code)) { t = s.indexOf(code) + code.length(); code = s.substring(t); break; } for (String s : read) - if (s.indexOf(prop) != -1) { + if (s.contains(prop)) { t = s.indexOf(prop) + prop.length(); prop = s.substring(t); break; @@ -189,8 +188,6 @@ private void setRecord() { Fail = 0; } extraRecordStatus = true; - firstFilePath.clear(); - secondFilePath.clear(); } private void isRecordStart(boolean auto) { @@ -203,7 +200,6 @@ private void isRecordStart(boolean auto) { videoLogList.add(new LogMsg("#Start record", mLog.v)); setRecord(); takeRecord(); - } else { if (!auto) videoLogList.add(new LogMsg("@Stop record", mLog.v)); @@ -217,7 +213,7 @@ private void isRecordStart(boolean auto) { } } else { stopRecordAndSaveLog(false); - showDialogLog(); + showDialogLog(false); } } @@ -225,6 +221,7 @@ private boolean checkPermission() { videoLogList.add(new LogMsg("#checkPermission", mLog.v)); int CAMERA = checkSelfPermission(Manifest.permission.CAMERA); int STORAGE = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); + return permission(CAMERA) || permission(STORAGE); } @@ -233,27 +230,25 @@ private boolean checkPermission() { private void showPermission() { videoLogList.add(new LogMsg("#showPermission", mLog.v)); // We don't have permission so prompt the user - List permissions = new ArrayList(); + List permissions = new ArrayList<>(); permissions.add(Manifest.permission.CAMERA); permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); - requestPermissions(permissions.toArray(new String[permissions.size()]), 0); + requestPermissions(permissions.toArray(new String[0]), 0); } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - switch (requestCode) { - case 0: - if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { - // 許可授權 - setStart(); - } else { - // 沒有權限 - showPermission(); - videoLogList.add(new LogMsg("#no permissions!", mLog.e)); - videoLogList.add(new LogMsg("No permissions!")); - } - break; - default: - super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == 0) { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // 許可授權 + setStart(); + } else { + // 沒有權限 + showPermission(); + videoLogList.add(new LogMsg("#no permissions!", mLog.e)); + videoLogList.add(new LogMsg("No permissions!")); + } + } else { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @@ -277,26 +272,12 @@ public void onConfigurationChanged(Configuration newConfig) { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isRun = 0; - videoLogList = new ArrayList(); + videoLogList = new ArrayList<>(); if (checkPermission()) { showPermission(); } else { checkConfigFile(this, true); - //TODO getprop - // -> adb shell su 0 getprop persist.our.camera.fps - if (isNew) { - try { - SystemProperties.set(FRAMESKIP, FPS[0]); - } catch (Exception e) { - e.getStackTrace(); - isError = true; - videoLogList.add(new LogMsg("SystemProperties error.", mLog.e)); - new Handler().post(() -> saveLog(this, false, false)); - errorMessage = "SystemProperties error. Please check your BuildVersion is 0302."; - } - } //*reflection invoke setStart(); - } } @@ -340,7 +321,6 @@ public void onOpened(CameraDevice camera) { public void onDisconnected(CameraDevice camera) { try { - fCamera = false; camera.close(); // 关闭摄像头 Log.e(TAG, "onDisconnected"); @@ -358,13 +338,12 @@ public void onDisconnected(CameraDevice camera) { ((TextView) findViewById(R.id.record_status)).setText("Error"); } if (autoRestart && isError) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } public void onError(CameraDevice camera, int error) { + fCamera = false; isError = true; onDisconnected(camera); // 前鏡頭開啟失敗 @@ -389,15 +368,10 @@ public void onOpened(CameraDevice camera) { mCameraDevice1 = camera; // 开启预览 takePreview(secondCamera); - if (!isReady) { - isReady = true; - new Handler().postDelayed(() -> demoHandler.obtainMessage().sendToTarget(), 500); - } } public void onDisconnected(CameraDevice camera) { try { - sCamera = false; camera.close(); // 关闭摄像头 Log.e(TAG, "onDisconnected"); @@ -415,13 +389,12 @@ public void onDisconnected(CameraDevice camera) { ((TextView) findViewById(R.id.record_status)).setText("Error"); } if (autoRestart && isError) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } public void onError(CameraDevice camera, int error) { + sCamera = false; isError = true; onDisconnected(camera); // 前鏡頭開啟失敗 @@ -442,108 +415,74 @@ public void onError(CameraDevice camera, int error) { errorMessage = "CameraDevice.StateCallback " + callback + " error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } private void stopRecordAndSaveLog(boolean kill) { isFinish = 0; - if (isRecord) new Handler().post(() -> { - new Handler().post(() -> stopRecord(false)); - }); - new Handler().post(() -> saveLog(getApplicationContext(), false, kill)); + if (isRecord) stopRecord(false); + saveLog(getApplicationContext(), false, kill); } - private void restartApp(String date, boolean record) { - if (date.equals(resetDate)) { - try { - home = null; - } catch (Exception e) { - - } - onRestart = true; - onReset++; - Context context = getApplicationContext(); - Intent intent = restartActivity.createIntent(context); - intent.putExtra(EXTRA_VIDEO_RUN, onRun); - intent.putExtra(EXTRA_VIDEO_FAIL, onFail); - intent.putExtra(EXTRA_VIDEO_RESET, onReset); - intent.putExtra(EXTRA_VIDEO_SUCCESS, onSuccess); - intent.putExtra(EXTRA_VIDEO_RECORD, record); - context.startActivity(intent); + private void restartApp(boolean record) { + try { + home.stop(); + } catch (Exception ignored) { } + onRestart = true; + onReset++; + Context context = getApplicationContext(); + Intent intent = restartActivity.createIntent(context); + intent.putExtra(EXTRA_VIDEO_RUN, onRun); + intent.putExtra(EXTRA_VIDEO_FAIL, onFail); + intent.putExtra(EXTRA_VIDEO_SUCCESS, onSuccess); + intent.putExtra(EXTRA_VIDEO_RESET, onReset); + intent.putExtra(EXTRA_VIDEO_RECORD, record); + context.startActivity(intent); } @SuppressLint("HandlerLeak") private void initial() { - getSdCard = !getSDPath().equals(""); - ArrayList items_frame = new ArrayList(); - ArrayList items_quality = new ArrayList(); - for (String frame : new ArrayList<>(Arrays.asList( // or "3.9fps", "3.4fps", "1.7fps", "0.8fps" - isNew ? NEW_FRAME_RATE : FRAME_RATE))) { - View vi = LayoutInflater.from(this).inflate(R.layout.style_vertical_item, null); - CustomTextView item = vi.findViewById(R.id.customTextView); - item.setText(frame); - items_frame.add(vi); - } - for (String quality : new ArrayList<>(Arrays.asList("1080p", "720p"))) { - View vi = LayoutInflater.from(this).inflate(R.layout.style_vertical_item, null); - CustomTextView item = vi.findViewById(R.id.customTextView); - item.setText(quality); - items_quality.add(vi); - } - if (isNew) { - VerticalViewPager pager_Frame = findViewById(R.id.pager1); - pager_Frame.addOnPageChangeListener(new mOnPageChangeListener(0)); - pager_Frame.setAdapter(new mPagerAdapter(items_frame)); - pager_Frame.setPageTransformer(true, new CustomPageTransformer()); - } - VerticalViewPager pager_Quality = findViewById(R.id.pager2); - pager_Quality.addOnPageChangeListener(new mOnPageChangeListener(1)); - pager_Quality.setAdapter(new mPagerAdapter(items_quality)); - pager_Quality.setPageTransformer(true, new CustomPageTransformer()); - // TODO findViewById - setLoading(false); + getSdCard = !getSDPath().equals(""); + // findViewById videoLogList.add(new LogMsg("Initial now.", mLog.v)); - thread0 = new HandlerThread("CameraPreview0"); + HandlerThread thread0 = new HandlerThread("CameraPreview0"); thread0.start(); - thread1 = new HandlerThread("CameraPreview1"); + HandlerThread thread1 = new HandlerThread("CameraPreview1"); thread1.start(); backgroundHandler0 = new Handler(thread0.getLooper()); backgroundHandler1 = new Handler(thread1.getLooper()); mainHandler = new Handler(getMainLooper()); recordHandler0 = new Handler() { - public void handleMessage(android.os.Message msg) { + public void handleMessage(Message msg) { startRecord(firstCamera); } }; recordHandler1 = new Handler() { - public void handleMessage(android.os.Message msg) { + public void handleMessage(Message msg) { startRecord(secondCamera); } }; stopRecordHandler0 = new Handler() { - public void handleMessage(android.os.Message msg) { + public void handleMessage(Message msg) { stopRecord(msg.obj.toString(), msg.arg1 + ""); } }; stopRecordHandler1 = new Handler() { - public void handleMessage(android.os.Message msg) { + public void handleMessage(Message msg) { stopRecord(msg.obj.toString(), msg.arg1 + ""); } }; - codeDate0 = getCalendarTime(); codeDate1 = getCalendarTime(); - resetDate = getCalendarTime(); + setCallback(0); - setCallback(1); mTextureView0 = findViewById(R.id.surfaceView0); mTextureView0.setSurfaceTextureListener(new mSurfaceTextureListener(firstCamera)); + setCallback(1); mTextureView1 = findViewById(R.id.surfaceView1); mTextureView1.setSurfaceTextureListener(new mSurfaceTextureListener(secondCamera)); @@ -551,9 +490,7 @@ public void handleMessage(android.os.Message msg) { videoLogList.add(new LogMsg("@cancel", mLog.v)); stopRecordAndSaveLog(true); }); - findViewById(R.id.record).setOnClickListener((View v) -> { - isRecordStart(false); - }); + findViewById(R.id.record).setOnClickListener((View v) -> isRecordStart(false)); findViewById(R.id.setting).setOnClickListener((View v) -> { if (getSdCard && !isError) { videoLogList.add(new LogMsg("@dialog_setting", mLog.v)); @@ -563,7 +500,7 @@ public void handleMessage(android.os.Message msg) { videoLogList.add(new LogMsg("@setting_reset", mLog.v)); setConfigFile(this, new File(getPath(), configName), view, true); getSetting(this, view.findViewById(R.id.dialog_editText_1), view.findViewById(R.id.dialog_editText_2), - view.findViewById(R.id.dialog_editText_3), view.findViewById(R.id.dialog_editText_4)); + view.findViewById(R.id.dialog_Text_3), view.findViewById(R.id.dialog_Text_4)); setSetting(); }); view.findViewById(R.id.dialog_button_2).setOnClickListener((View vs) -> { // cancel @@ -577,16 +514,14 @@ public void handleMessage(android.os.Message msg) { dialog.dismiss(); }); getSetting(this, view.findViewById(R.id.dialog_editText_1), view.findViewById(R.id.dialog_editText_2), - view.findViewById(R.id.dialog_editText_3), view.findViewById(R.id.dialog_editText_4)); + view.findViewById(R.id.dialog_Text_3), view.findViewById(R.id.dialog_Text_4)); dialog.show(); } else { - showDialogLog(); + showDialogLog(false); } }); - findViewById(R.id.loadingView).setVisibility(View.INVISIBLE); + ((TextView) findViewById(R.id.record_status)).setText(getSDPath().equals("") ? "Error" : "Ready"); - firstFilePath = new ArrayList(); - secondFilePath = new ArrayList(); videoLogList.add(new LogMsg("#initial complete", mLog.v)); onRun = getIntent().getIntExtra(EXTRA_VIDEO_RUN, 0); onFail = getIntent().getIntExtra(EXTRA_VIDEO_FAIL, 0); @@ -597,10 +532,10 @@ public void handleMessage(android.os.Message msg) { extraRecordStatus = getIntent().getBooleanExtra(EXTRA_VIDEO_RECORD, false); // show DEMO demoHandler = new Handler() { - public void handleMessage(android.os.Message msg) { - this.post(() -> checkSdCardFromFileList()); + public void handleMessage(Message msg) { if (!extraRecordStatus) { - this.post(() -> saveLog(getApplicationContext(), false, false)); + Log.e("demoHandler","ready"); + saveLog(getApplicationContext(), false, false); } else { isRecordStart(true); } @@ -609,9 +544,9 @@ public void handleMessage(android.os.Message msg) { this.registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) { //Battery + if (Objects.equals(intent.getAction(), Intent.ACTION_BATTERY_CHANGED)) { //Battery videoLogList.add(new LogMsg("Battery:" + intent.getIntExtra("level", 0) + "%", mLog.e)); - new Handler().post(() -> saveLog(getApplicationContext(), false, false)); + saveLog(getApplicationContext(), false, false); } } }, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); @@ -628,82 +563,42 @@ private void setSetting() { openCamera(secondCamera); }); } - if (check[1]) { - try { - try { - SystemProperties.set(FRAMESKIP, FPS[0]); - }catch (Exception e){ - - } - if (isNew) { - String getFrameSkip = PropertyUtils.get(FRAMESKIP); - if (null != getFrameSkip) { - if (isInteger(getFrameSkip, false)) { - //if FrameSkip is change or LastCamera != CameraID, delay 3s to change camera devices - SystemProperties.set(FRAMESKIP, FPS[isFrame]); - videoLogList.add(new LogMsg("getFrameSkip:" + PropertyUtils.get(FRAMESKIP), mLog.e)); - } else { - videoLogList.add(new LogMsg("getFrameSkip error, fs(" + getFrameSkip + ") is not integer.", mLog.e)); - } - } else { - videoLogList.add(new LogMsg("getFrameSkip error, fs == null.", mLog.e)); - } - } - ArrayList new_frame = new ArrayList(); - if(isNew) { - for (String frame : new ArrayList<>(Arrays.asList( // or "3.9fps", "3.4fps", "1.7fps", "0.8fps" - isNew ? NEW_FRAME_RATE : FRAME_RATE))) { - View vi = LayoutInflater.from(this).inflate(R.layout.style_vertical_item, null); - CustomTextView item = vi.findViewById(R.id.customTextView); - item.setText(frame); - new_frame.add(vi); - } - } - ((VerticalViewPager) findViewById(R.id.pager1)).setAdapter(new mPagerAdapter(new_frame)); - } catch (Exception e) { - e.getStackTrace(); - isError = true; - videoLogList.add(new LogMsg("SystemProperties error.", mLog.e)); - new Handler().post(() -> saveLog(this, false, false)); - errorMessage = "SystemProperties error. Please check your BuildVersion is 0302."; - } - } } else { - new Handler().post(() -> saveLog(getApplicationContext(), false, false)); + saveLog(getApplicationContext(), false, false); } } - private void showDialogLog() { - if (!isRecord) { + private void showDialogLog(boolean real) { + if (!isRecord || real) { videoLogList.add(new LogMsg("#dialog_log", mLog.v)); View view = LayoutInflater.from(this).inflate(R.layout.layout_getlog, null); - final AlertDialog dialog = new AlertDialog.Builder(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen).setView(view).setCancelable(true).create(); + final AlertDialog dialog = new AlertDialog.Builder(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen) + .setView(view).setCancelable(true).create(); view.findViewById(R.id.dialog_button_2).setOnClickListener((View vs) -> { // ok videoLogList.add(new LogMsg("@log_ok", mLog.v)); dialog.dismiss(); }); - ArrayList list = new ArrayList(); - list.add("App Version:" + this.getString(R.string.app_name)); + ArrayList list = new ArrayList<>(); + if (getSdCard) - list.add("Please check file at your SD card"); - else list.add(NO_SD_CARD); - if (!fCamera) { + if (real) + list.add("CheckFile -> video_success/fail:(" + getSuccess() + "/" + getFail() + ") app_reset:(" + getReset() + ")"); + else + list.add("App Version:" + this.getString(R.string.app_name)); + else if (SD_Mode) list.add(NO_SD_CARD); + if (!fCamera) list.add("Camera Access error, Please check camera " + firstCamera + ". <============ Crash here"); - if (firstCamera.equals("2")) - list.add("You can try Reboot device to walk up external camera."); - } - if (!sCamera) { - list.add("Camera Access error, Please check camera " + secondCamera + ". <============ Crash here"); - if (secondCamera.equals("2")) - list.add("You can try Reboot device to walk up external camera."); - } + if (!sCamera) + list.add("Camera Access error, Please check camera " + secondCamera + ". <=========== Crash here"); +// if ((!fCamera && firstCamera.equals("2")) || !sCamera && firstCamera.equals("2")) +// list.add("You can try Reboot device to walk up external camera."); if (!errorMessage.equals("")) list.add(errorMessage); if (list.size() > 0) { - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList<>(); for (String s : list) { - View item_layout = LayoutInflater.from(this).inflate(R.layout.style_text_item, null); + @SuppressLint("InflateParams") View item_layout = LayoutInflater.from(this).inflate(R.layout.style_text_item, null); ((CustomTextView) item_layout.findViewById(R.id.customTextView)).setText(s); items.add(item_layout); } @@ -714,10 +609,6 @@ private void showDialogLog() { } } - private void setLoading(boolean visible) { - runOnUiThread(() -> findViewById(R.id.loadingView).setVisibility(visible ? View.VISIBLE : View.INVISIBLE)); - } - private void takeRecord() { if (!isError && getSdCard) { videoLogList.add(new LogMsg("#------------------------------", mLog.v)); @@ -741,26 +632,48 @@ private void takeRecord() { new Handler().postDelayed(() -> saveLog(getApplicationContext(), false, false), delay); } else { stopRecordAndSaveLog(false); - showDialogLog(); + showDialogLog(false); } } public static void saveLog(Context context, boolean reFormat, boolean kill) { if (!getSDPath().equals("")) { String version = context.getString(R.string.app_name); - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), saveLogService.class.getName()); - intent.putExtra(EXTRA_VIDEO_VERSION, version); - intent.putExtra(EXTRA_VIDEO_REFORMAT, reFormat); - if (kill) - intent.putExtra(EXTRA_MAIN_PID, android.os.Process.myPid()); - context.startService(intent); + StringBuilder logString; + assert videoLogList != null; + File file = new File(getPath(), logName); + if (!file.exists()) { + logString = new StringBuilder(LOG_TITLE + version + "\r\n"); + try { + file.createNewFile(); + videoLogList.add(new LogMsg("Create the log file.", mLog.w)); + } catch (Exception e) { + videoLogList.add(new LogMsg("Create file failed.", mLog.w)); + e.printStackTrace(); + } + } else { + logString = new StringBuilder(); + } + + for (LogMsg logs : videoLogList) { + String time = logs.time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + + " run:" + logs.runTime + " -> "; + logString.append(time).append(logs.msg).append("\r\n"); + } + try { + FileOutputStream output = new FileOutputStream(new File(getPath(), logName), !reFormat); + output.write(logString.toString().getBytes()); + output.close(); + videoLogList.clear(); + } catch (Exception e) { + e.printStackTrace(); + } } else { isError = true; getSdCard = !getSDPath().equals(""); - if (kill) - android.os.Process.killProcess(android.os.Process.myPid()); } + if (kill) + android.os.Process.killProcess(android.os.Process.myPid()); } protected void onDestroy() { @@ -778,17 +691,21 @@ protected void onDestroy() { closePreviewSession(secondCamera); try { if (mMediaRecorder0 != null) { + mMediaRecorder0.stop(); mMediaRecorder0.release(); - mMediaRecorder0 = null; videoLogList.add(new LogMsg("Record " + firstCamera + " finish.")); } + } catch (Exception e) { + videoLogList.add(new LogMsg("mMediaRecorder0 is error.")); + } + try { if (mMediaRecorder1 != null) { + mMediaRecorder1.stop(); mMediaRecorder1.release(); - mMediaRecorder1 = null; videoLogList.add(new LogMsg("Record " + secondCamera + " finish.")); } } catch (Exception e) { - e.printStackTrace(); + videoLogList.add(new LogMsg("mMediaRecorder1 is error.")); } new Handler().post(() -> stopRecordAndSaveLog(false)); } @@ -797,16 +714,16 @@ private void openCamera(String cameraId) { CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); Log.e(TAG, "openCamera E"); try { - /** cameraId - * 0 = CameraCharacteristics.LENS_FACING_FRONT - * 1 = CameraCharacteristics.LENS_FACING_BACK - * 2 = CameraCharacteristics.LENS_FACING_EXTERNAL + /* cameraId + 0 = CameraCharacteristics.LENS_FACING_FRONT + 1 = CameraCharacteristics.LENS_FACING_BACK + 2 = CameraCharacteristics.LENS_FACING_EXTERNAL */ Log.e(TAG, "camera ID: " + cameraId); Log.e(TAG, "number of camera: " + manager.getCameraIdList().length); if (isCameraOne(cameraId)) - mPreviewSize = manager.getCameraCharacteristics(cameraId) - .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) + mPreviewSize = Objects.requireNonNull(manager.getCameraCharacteristics(cameraId) + .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)) .getOutputSizes(SurfaceTexture.class)[0]; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { @@ -847,33 +764,40 @@ private void stopRecord(String date, String cameraID) { ((TextView) findViewById(R.id.record_status)).setText("Stop"); videoLogList.add(new LogMsg("#stopRecord", mLog.v)); Log.d(TAG, "stopRecord"); - } else - moveFile(getPath() + logName, getSDPath() + logName, false); + } if (isCameraOne(cameraID)) { - if (mMediaRecorder0 != null) { - mMediaRecorder0.release(); - mMediaRecorder0 = null; - videoLogList.add(new LogMsg("Record " + firstCamera + " finish.")); - } else { - videoLogList.add(new LogMsg("mMediaRecorder " + firstCamera + " is null.")); + try { + if (mMediaRecorder0 != null) { + mMediaRecorder0.stop(); + mMediaRecorder0.release(); + videoLogList.add(new LogMsg("Record " + firstCamera + " finish.")); + } + } catch (Exception e) { + videoLogList.add(new LogMsg("mMediaRecorder0 is error.")); } } else { - if (mMediaRecorder1 != null) { - mMediaRecorder1.release(); - mMediaRecorder1 = null; - videoLogList.add(new LogMsg("Record " + secondCamera + " finish.")); - } else { - videoLogList.add(new LogMsg("mMediaRecorder " + secondCamera + " is null.")); + try { + if (mMediaRecorder1 != null) { + mMediaRecorder1.stop(); + mMediaRecorder1.release(); + videoLogList.add(new LogMsg("Record " + secondCamera + " finish.")); + } + } catch (Exception e) { + videoLogList.add(new LogMsg("mMediaRecorder1 is error.")); } } - checkAndClear(cameraID); + + try { + checkAndClear(cameraID); + } catch (Exception e) { + videoLogList.add(new LogMsg("Check file is fail.")); + } if (isFinish == 999 || isRun <= isFinish) { startRecord(cameraID); } else { - if (!isCameraOne(cameraID)) { - isRecordStart(false); - } + showDialogLog(true); + isRecordStart(true); } if (isError || !getSdCard) { isRun = 0; @@ -891,9 +815,7 @@ private void stopRecord(String date, String cameraID) { errorMessage = "Camera " + cameraID + " stopRecord error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } @@ -906,35 +828,30 @@ private void stopRecord(boolean preview) { } codeDate0 = getCalendarTime(); codeDate1 = getCalendarTime(); - moveFile(getPath() + logName, getSDPath() + logName, false); + if (!isError && getSdCard) { ((TextView) findViewById(R.id.record_status)).setText("Stop"); if (isRecord) { videoLogList.add(new LogMsg("#stopRecord", mLog.v)); Log.d(TAG, "stopRecord"); - try { - if (mMediaRecorder0 != null) { - mMediaRecorder0.release(); - mMediaRecorder0 = null; - videoLogList.add(new LogMsg("Record " + firstCamera + " finish.")); - } - } catch (Exception e) { - videoLogList.add(new LogMsg("mMediaRecorder0 is error.")); - } - try { - if (mMediaRecorder1 != null) { - mMediaRecorder1.release(); - mMediaRecorder1 = null; - videoLogList.add(new LogMsg("Record " + secondCamera + " finish.")); + for (String cameraID : new String[]{firstCamera, secondCamera}) + try { + if (cameraID.equals(firstCamera)) + if (mMediaRecorder0 != null) { + mMediaRecorder0.stop(); + mMediaRecorder0.release(); + videoLogList.add(new LogMsg("Record " + cameraID + " finish.")); + } + if (cameraID.equals(secondCamera)) + if (mMediaRecorder1 != null) { + mMediaRecorder1.stop(); + mMediaRecorder1.release(); + videoLogList.add(new LogMsg("Record " + cameraID + " finish.")); + } + checkAndClear(cameraID); + } catch (Exception e) { + videoLogList.add(new LogMsg("mMediaRecorder" + cameraID + " is error.")); } - } catch (Exception e) { - videoLogList.add(new LogMsg("mMediaRecorder1 is error.")); - } - try { - checkAndClear(); - } catch (Exception e) { - videoLogList.add(new LogMsg("Check file is fail.")); - } isRun = 0; isFinish = 0; isRecord = false; @@ -942,12 +859,11 @@ private void stopRecord(boolean preview) { videoLogList.add(new LogMsg("#------------------------------", mLog.v)); videoLogList.add(new LogMsg("#Complete")); ((TextView) findViewById(R.id.record_status)).setText("Complete"); - end(preview); } else { isRun = 0; isFinish = 0; - end(preview); } + end(preview); } else { ((TextView) findViewById(R.id.record_status)).setText("Error"); } @@ -959,38 +875,79 @@ private void stopRecord(boolean preview) { errorMessage = "stopRecord all camera error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } private void end(boolean preview) { - new Handler().post(() -> saveLog(getApplicationContext(), false, false)); + saveLog(getApplicationContext(), false, false); if (preview) { takePreview(); } } - private void moveFile(String video, String pathname, boolean remove) { - if (SD_Mode) { - Context context = getApplicationContext(); - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), copyFileService.class.getName()); - intent.putExtra(EXTRA_VIDEO_COPY, video); - intent.putExtra(EXTRA_VIDEO_PASTE, pathname); - intent.putExtra(EXTRA_VIDEO_REMOVE, remove); - context.startService(intent); + public static int getFrameRate(File file) { + int frameRate = 0; + if (!getSDPath().equals("")) { + try { + MediaExtractor extractor; + FileInputStream fis; + try { + fis = new FileInputStream(file); + extractor = new MediaExtractor(); + extractor.setDataSource(fis.getFD()); + } catch (Exception ignored) { + videoLogList.add(new LogMsg("getFrameRate failed on MediaExtractor.<============ Crash here", mLog.e)); + return 0; + } + int numTracks = extractor.getTrackCount(); + for (int i = 0; i < numTracks; i++) { + MediaFormat format = extractor.getTrackFormat(i); + if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) { + try { + frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE); + } catch (Exception ignored) { + videoLogList.add(new LogMsg("getFrameRate failed on MediaExtractor.<============ Crash here", mLog.e)); + } + } + } + extractor.release(); + fis.close(); + } catch (Exception e) { + videoLogList.add(new LogMsg("getFrameRate failed.<============ Crash here", mLog.e)); + } + } else { + videoLogList.add(new LogMsg("getFrameRate failed " + NO_SD_CARD + ".", mLog.e)); } + return frameRate; } - private void checkFile(String path) { - Context context = getApplicationContext(); - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), checkFileService.class.getName()); - intent.putExtra(EXTRA_VIDEO_PATH, path); - context.startService(intent); + public static void checkFile(String path) { + try { + File video = new File(path); + int frameRate = 0; + if (video.exists()) { + try { + frameRate = getFrameRate(video); + } catch (Exception ignored) { + if (null != videoLogList) + videoLogList.add(new LogMsg("CheckFile error.", mLog.e)); + } + if (frameRate != 0) Success++; + else Fail++; + } else { + Fail++; + } + if (null != videoLogList) + videoLogList.add(new LogMsg("CheckFile:(" + path.split("/")[3] + + ") video_frameRate:(" + frameRate + ") video_success/fail:(" + getSuccess() + "/" + getFail() + + ") app_reset:(" + getReset() + ")", mLog.i)); + } catch (Exception ignored) { + if (null != videoLogList) + videoLogList.add(new LogMsg("CheckFile error.", mLog.e)); + Fail++; + } } private void closePreviewSession(String cameraId) { @@ -1008,19 +965,19 @@ private void startRecord(String cameraId) { if (!isError) { Log.d(TAG, "startRecord"); try { - if (isCameraOne(cameraId)) + if (isCameraOne(cameraId)) { codeDate0 = getCalendarTime(); - else + } else { codeDate1 = getCalendarTime(); + } if (isCameraOne(cameraId)) { checkSdCardFromFileList(); runOnUiThread(() -> { if (mTimer == null) { - onFail = getFail(); onRun = getIsRun(); + onFail = getFail(); onSuccess = getSuccess(); - //タイマーの初期化処理 timerTask = new mTimerTask(); mLaptime = 0.0f; mTimer = new Timer(true); @@ -1047,7 +1004,7 @@ private void startRecord(String cameraId) { backgroundHandler = backgroundHandler0; mCameraDevice = mCameraDevice0; mMediaRecorder0 = setUpMediaRecorder(firstCamera); - mPreviewBuilder0 = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); + CaptureRequest.Builder mPreviewBuilder0 = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); surfaces.add(surface); mPreviewBuilder0.addTarget(surface); recorderSurface = mMediaRecorder0.getSurface(); @@ -1058,7 +1015,7 @@ private void startRecord(String cameraId) { backgroundHandler = backgroundHandler1; mCameraDevice = mCameraDevice1; mMediaRecorder1 = setUpMediaRecorder(secondCamera); - mPreviewBuilder1 = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); + CaptureRequest.Builder mPreviewBuilder1 = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD); surfaces.add(surface); mPreviewBuilder1.addTarget(surface); recorderSurface = mMediaRecorder1.getSurface(); @@ -1068,68 +1025,77 @@ private void startRecord(String cameraId) { } // Start a capture session // Once the session starts, we can update the UI and start recording - if (mPreviewBuilder != null) { - try { - mCameraDevice.createCaptureSession(surfaces, - new CameraCaptureSession.StateCallback() { - - public void onConfigured(CameraCaptureSession session) { - // 当摄像头已经准备好时,开始显示预览 - if (isCameraOne(cameraId)) { - mPreviewSession0 = session; - } else { - mPreviewSession1 = session; - } - updatePreview(mPreviewBuilder, session, backgroundHandler); + try { + mCameraDevice.createCaptureSession(surfaces, + new CameraCaptureSession.StateCallback() { - if (isCameraOne(cameraId)) { - Message msg = stopRecordHandler0.obtainMessage(); - msg.arg1 = Integer.parseInt(cameraId); - msg.obj = getCodeDate(cameraId); - stopRecordHandler0.sendMessageDelayed(msg, delayTime); + public void onConfigured(CameraCaptureSession session) { + // Camera is ready. + if (isCameraOne(cameraId)) { + mPreviewSession0 = session; + } else { + mPreviewSession1 = session; + } + updatePreview(mPreviewBuilder, session, backgroundHandler); + + if (isCameraOne(cameraId)) { + try { if (mMediaRecorder0 != null) mMediaRecorder0.start(); - mTimer.schedule(timerTask, 100, 100); - } else { - Message msg = stopRecordHandler1.obtainMessage(); - msg.arg1 = Integer.parseInt(cameraId); - msg.obj = getCodeDate(cameraId); - stopRecordHandler1.sendMessageDelayed(msg, delayTime + 500); + } catch (Exception e) { + isError = true; + videoLogList.add(new LogMsg("Camera " + cameraId + " can't record. <============ Crash here", mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = "Camera " + cameraId + " can't record. <============ Crash here"; + ((TextView) findViewById(R.id.record_status)).setText("Error"); + } + Message msg = stopRecordHandler0.obtainMessage(); + msg.arg1 = Integer.parseInt(cameraId); + msg.obj = getCodeDate(cameraId); + if (autoStopRecord) + stopRecordHandler0.sendMessageDelayed(msg, delayTime); + mTimer.schedule(timerTask, 100, 100); + } else { + try { if (mMediaRecorder1 != null) mMediaRecorder1.start(); + } catch (Exception e) { + isError = true; + videoLogList.add(new LogMsg("Camera " + cameraId + " can't record. <============ Crash here", mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = "Camera " + cameraId + " can't record. <============ Crash here"; + ((TextView) findViewById(R.id.record_status)).setText("Error"); } - + Message msg = stopRecordHandler1.obtainMessage(); + msg.arg1 = Integer.parseInt(cameraId); + msg.obj = getCodeDate(cameraId); + if (autoStopRecord) + stopRecordHandler1.sendMessageDelayed(msg, delayTime + 500); } - public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { - videoLogList.add(new LogMsg("Camera " + cameraId + " Record onConfigureFailed.", mLog.e)); - new Handler().post(() -> saveLog(getApplicationContext(), false, false)); + } + + public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { + isError = true; + videoLogList.add(new LogMsg("Camera " + cameraId + " Record onConfigureFailed.", mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = "Camera " + cameraId + " onConfigureFailed error."; + ((TextView) findViewById(R.id.record_status)).setText("Error"); + if (autoRestart) { + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } - }, backgroundHandler); - } catch (Exception e) { - e.printStackTrace(); - isError = true; - videoLogList.add(new LogMsg("Camera " + cameraId + " CameraCaptureSession.StateCallback() error. <============ Crash here", mLog.e)); - new Handler().post(() -> stopRecordAndSaveLog(false)); - errorMessage = "Camera " + cameraId + " startRecord error. <============ Crash here"; - ((TextView) findViewById(R.id.record_status)).setText("Error"); - if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); - } - } - } else { + } + }, backgroundHandler); + } catch (Exception e) { + e.printStackTrace(); isError = true; - videoLogList.add(new LogMsg("Camera " + cameraId + " mPreviewBuilder is null. <============ Crash here", mLog.e)); + videoLogList.add(new LogMsg("Camera " + cameraId + " CameraCaptureSession.StateCallback() error. <============ Crash here", mLog.e)); new Handler().post(() -> stopRecordAndSaveLog(false)); - errorMessage = "Camera " + cameraId + " mPreviewBuilder is null. <============ Crash here"; + errorMessage = "Camera " + cameraId + " startRecord error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } catch (Exception e) { @@ -1140,93 +1106,124 @@ public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) { errorMessage = "Camera " + cameraId + " startRecord error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } } private void checkSdCardFromFileList() { - Context context = getApplicationContext(); - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), checkSdCardService.class.getName()); - context.startService(intent); - } - - private void checkAndClear(String cameraID) { - if (isCameraOne(cameraID)) { + getSdCard = !getSDPath().equals(""); + if (getSdCard) { try { - for (String f : firstFilePath) - checkFile(f); + StatFs stat = new StatFs(getSDPath()); + long sdAvailSize = stat.getAvailableBlocksLong() * stat.getBlockSizeLong(); + double gigaAvailable = (sdAvailSize >> 30); + if (gigaAvailable < sdData) { + videoLogList.add(new LogMsg("SD Card is Full.")); + ArrayList tmp = new ArrayList<>(); + File[] fileList = new File(getSDPath()).listFiles(); + for (File file : fileList) { + if (!file.isDirectory() && Utils.getFileExtension(file.toString()).equals("mp4")) + if (!(file.toString().equals(firstFile) || file.toString().equals(secondFile))) + tmp.add(file.toString()); + } + int video = 0; + if (Open_f_Camera) + video += 2; + if (Open_s_Camera) + video += 2; + if (tmp.size() >= video) { + Object[] list = tmp.toArray(); + Arrays.sort(list); + for (int i = 0; i < video; i++) + delete((String) (list != null ? list[i] : null), SD_Mode); + checkSdCardFromFileList(); + } else { + isError = true; + videoLogList.add(new LogMsg("MP4 video file not found. <============ Crash here")); + } + } } catch (Exception e) { - videoLogList.add(new LogMsg("CheckFile " + cameraID + " error.", mLog.e)); - } finally { - firstFilePath.clear(); + e.printStackTrace(); + isError = true; + getSdCard = !getSDPath().equals(""); + if (getSdCard) { + saveLog(getApplicationContext(), false, false); + errorMessage = "error: At least " + sdData + " memory needs to be available to record, please check the SD Card free space."; + videoLogList.add(new LogMsg("#error: At least " + sdData + " memory needs to be available to record, please check the SD Card free space.", mLog.e)); + } else { + videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = NO_SD_CARD; + } } + } else { + isError = true; + videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = NO_SD_CARD; } - if (!isCameraOne(cameraID)) { - try { - for (String s : secondFilePath) - checkFile(s); - } catch (Exception e) { - videoLogList.add(new LogMsg("CheckFile " + cameraID + " error.", mLog.e)); - } finally { - secondFilePath.clear(); + } + + private void delete(String path, boolean fromSDcard) { + try { + if (!path.equals("")) { + File video = new File(path); + if (video.exists()) { + if (fromSDcard) + videoLogList.add(new LogMsg("Delete: " + path.split("/")[3], mLog.w)); + else + videoLogList.add(new LogMsg("Delete: " + path.split("/")[5], mLog.w)); + video.delete(); + } else { + videoLogList.add(new LogMsg("Video not find.", mLog.e)); + } } + } catch (Exception e) { + e.printStackTrace(); + isError = true; + getSdCard = !getSDPath().equals(""); + videoLogList.add(new LogMsg("#delete " + path + " error. <============ Crash here", mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = "Delete file error. <============ Crash here"; } } - private void checkAndClear() { - for (String f : firstFilePath) - checkFile(f); - for (String s : secondFilePath) - checkFile(s); - firstFilePath.clear(); - secondFilePath.clear(); + private void checkAndClear(String cameraID) { + try { + if (isRecord) { + if (cameraID.equals(firstCamera)) + checkFile(firstFile); + + if (cameraID.equals(secondCamera)) + checkFile(secondFile); + } + } catch (Exception e) { + videoLogList.add(new LogMsg("CheckFile " + cameraID + " error.", mLog.e)); + } } private MediaRecorder setUpMediaRecorder(String cameraId) { MediaRecorder mediaRecorder = null; try { - /*TODO CamcorderProfile.QUALITY_HIGH:质量等级对应于最高可用分辨率*/// 1080p, 720p - CamcorderProfile profile_720 = CamcorderProfile.get(CamcorderProfile.QUALITY_720P); CamcorderProfile profile_1080 = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P); String file = ""; if (!getSDPath().equals("")) { - file = getSDPath() + getCalendarTime(isCameraOne(cameraId)) + ".mp4"; + file = getSDPath() + getCalendarTime(cameraId) + ".mp4"; videoLogList.add(new LogMsg("Create: " + file.split("/")[3], mLog.w)); + if (cameraId.equals(firstCamera)) + firstFile = file; - (isCameraOne(cameraId) ? firstFilePath : secondFilePath).add(file); - if (isCameraOne(cameraId)) - firstFile = file + ""; - else - secondFile = file + ""; - // Step 1: Unlock and set camera to MediaRecorder - CamcorderProfile profile = isQuality == 1 ? profile_720 : profile_1080; + if (cameraId.equals(secondCamera)) + secondFile = file; mediaRecorder = new MediaRecorder(); - // Step 2: Set sources - if (isCameraOne(cameraId)) - mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); - if (isCameraOne(cameraId)) - mediaRecorder.setAudioEncoder(profile.audioCodec); - mediaRecorder.setVideoEncoder(profile.videoCodec); - mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); - if (isCameraOne(cameraId)) - mediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); - mediaRecorder.setVideoEncodingBitRate((int) (profile.videoBitRate / 3.3)); - if (isCameraOne(cameraId)) { - mediaRecorder.setAudioChannels(profile.audioChannels); - mediaRecorder.setAudioSamplingRate(profile.audioSampleRate); - } - /*设置要捕获的视频的帧速率*/ // default is 24.6 - mediaRecorder.setVideoFrameRate(!isNew ? isFrame == 0 ? 10 : 28 : 27); // 1 -> 12fps, 10 -> 16fps - // Step 4: Set output file + mediaRecorder.setVideoEncoder(profile_1080.videoCodec); + mediaRecorder.setVideoSize(profile_1080.videoFrameWidth, profile_1080.videoFrameHeight); + mediaRecorder.setVideoEncodingBitRate((int) (profile_1080.videoBitRate / 3.3)); mediaRecorder.setOutputFile(file); - // Step 5: Prepare configured MediaRecorder mediaRecorder.prepare(); } else { getSdCard = !getSDPath().equals(""); @@ -1235,6 +1232,9 @@ private MediaRecorder setUpMediaRecorder(String cameraId) { new Handler().post(() -> stopRecordAndSaveLog(false)); errorMessage = "MediaRecorder error. " + NO_SD_CARD + " <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); + if (autoRestart) { + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); + } return null; } } catch (Exception e) { @@ -1243,16 +1243,8 @@ private MediaRecorder setUpMediaRecorder(String cameraId) { isError = true; videoLogList.add(new LogMsg("MediaRecorder " + cameraId + " error. <============ Crash here", mLog.e)); new Handler().post(() -> stopRecordAndSaveLog(false)); - errorMessage = "MediaRecorder " + cameraId + " error. <============ Crash here"; - ((TextView) findViewById(R.id.record_status)).setText("Error"); - if (getSdCard) { - if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); - } - } else { - videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); + if (autoRestart) { + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } return mediaRecorder; @@ -1277,15 +1269,12 @@ private void takePreview(String cameraId) { errorMessage = "takePreview " + cameraId + " error. <============ Crash here"; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } if (null != texture) { texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface surface = new Surface(texture); - CaptureRequest.Builder mPreviewBuilder; CameraDevice mCameraDevice; Handler backgroundHandler; @@ -1295,6 +1284,10 @@ private void takePreview(String cameraId) { } else { backgroundHandler = backgroundHandler1; mCameraDevice = mCameraDevice1; + if (!isReady) { + isReady = true; + new Handler().postDelayed(() -> demoHandler.obtainMessage().sendToTarget(), 500); + } } if (!isError) { try { @@ -1316,9 +1309,15 @@ public void onConfigured(CameraCaptureSession session) { updatePreview(mPreviewBuilder, session, backgroundHandler); } - public void onConfigureFailed(CameraCaptureSession session) { + isError = true; videoLogList.add(new LogMsg("Preview " + cameraId + " onConfigureFailed", mLog.e)); + saveLog(getApplicationContext(), false, false); + errorMessage = "Camera " + cameraId + " onConfigureFailed error."; + ((TextView) findViewById(R.id.record_status)).setText("Error"); + if (autoRestart) { + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); + } } }, backgroundHandler); } catch (Exception e) { @@ -1329,9 +1328,7 @@ public void onConfigureFailed(CameraCaptureSession session) { errorMessage = "Preview " + cameraId + " error."; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } @@ -1350,9 +1347,7 @@ protected void updatePreview(CaptureRequest.Builder mPreviewBuilder, CameraCaptu errorMessage = "setCaptureRequest error."; ((TextView) findViewById(R.id.record_status)).setText("Error"); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } } @@ -1362,27 +1357,24 @@ private boolean isCameraOne(String cameraId) { } private class mTimerTask extends TimerTask { - public void run() { // mHandlerを通じてUI Threadへ処理をキューイング runOnUiThread(() -> { //実行間隔分を加算処理 mLaptime += 0.1d; - if (mLaptime >= 65) { + //計算にゆらぎがあるので小数点第1位で丸める + BigDecimal bi = new BigDecimal(mLaptime); + float outputValue = bi.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue(); + if (autoStopRecord && outputValue >= 65) { isError = true; videoLogList.add(new LogMsg("Application has timed out.", mLog.w)); new Handler().post(() -> stopRecordAndSaveLog(false)); errorMessage = "Application has timed out."; new Handler().post(() -> ((TextView) findViewById(R.id.record_status)).setText("Error")); if (autoRestart) { - final String dates = resetDate + ""; - final boolean records = extraRecordStatus; - new Handler().postDelayed(() -> restartApp(dates, records), 3000); + new Handler().postDelayed(() -> restartApp(extraRecordStatus), delayMillis); } } - //計算にゆらぎがあるので小数点第1位で丸める - BigDecimal bi = new BigDecimal(mLaptime); - float outputValue = bi.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue(); //現在のLapTime ((TextView) findViewById(R.id.record_timer)).setText(Float.toString(outputValue)); }); @@ -1412,71 +1404,4 @@ public void onSurfaceTextureUpdated(SurfaceTexture surface) { } } - - private class mOnPageChangeListener implements VerticalViewPager.OnPageChangeListener { - int pos; - - public mOnPageChangeListener(int pos) { - this.pos = pos; - } - - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - - } - - public void onPageSelected(int position) { - switch (pos) { - case 0: - if (!isRecord) { - isFrame = position; - if (isNew) { - setLoading(true); - new Handler().post(() -> { - String getFrameSkip = PropertyUtils.get(FRAMESKIP); - if (null != getFrameSkip) { - if (isInteger(getFrameSkip, false)) { - //if frameskip is chehe or lastcamera != cameraid, delay 3s to change camera devices - try { - SystemProperties.set(FRAMESKIP, FPS[isFrame]); - } catch (Exception e) { - e.getStackTrace(); - isError = true; - videoLogList.add(new LogMsg("SystemProperties error.", mLog.e)); - new Handler().post(() -> saveLog(getApplicationContext(), false, false)); - errorMessage = "SystemProperties error. Please check your BuildVersion is 0302."; - } - videoLogList.add(new LogMsg("getFrameSkip:" + PropertyUtils.get(FRAMESKIP), mLog.e)); - mStateCallback0.onDisconnected(mCameraDevice0); - mStateCallback1.onDisconnected(mCameraDevice1); - new Handler().post(() -> openCamera(firstCamera)); - new Handler().post(() -> openCamera(secondCamera)); - } else { - videoLogList.add(new LogMsg("getFrameSkip error, fs(" + getFrameSkip + ") is not integer.", mLog.e)); - } - } else { - videoLogList.add(new LogMsg("getFrameSkip error, fs == null.", mLog.e)); - } - setLoading(false); - }); - } - } else { - ((VerticalViewPager) findViewById(R.id.pager1)).setCurrentItem(isFrame); - } - break; - case 1: - if (!isRecord) { - isQuality = position; - } else { - ((VerticalViewPager) findViewById(R.id.pager2)).setCurrentItem(isQuality); - } - break; - default: - break; - } - } - - public void onPageScrollStateChanged(int state) { - - } - } } \ No newline at end of file diff --git a/app/src/main/java/com/askey/record/checkFileService.java b/app/src/main/java/com/askey/record/checkFileService.java deleted file mode 100644 index 77706c6..0000000 --- a/app/src/main/java/com/askey/record/checkFileService.java +++ /dev/null @@ -1,147 +0,0 @@ -package com.askey.record; - -import android.app.IntentService; -import android.content.Intent; -import android.media.MediaExtractor; -import android.media.MediaFormat; - -import com.askey.widget.LogMsg; -import com.askey.widget.mLog; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -import static com.askey.record.Utils.DFRAME_RATE; -import static com.askey.record.Utils.EXTRA_VIDEO_PATH; -import static com.askey.record.Utils.Fail; -import static com.askey.record.Utils.NEW_DFRAME_RATE; -import static com.askey.record.Utils.NO_SD_CARD; -import static com.askey.record.Utils.Success; -import static com.askey.record.Utils.getFail; -import static com.askey.record.Utils.getReset; -import static com.askey.record.Utils.getSDPath; -import static com.askey.record.Utils.getSuccess; -import static com.askey.record.Utils.isFrame; -import static com.askey.record.Utils.isNew; -import static com.askey.record.Utils.videoLogList; - -public class checkFileService extends IntentService { - private String path; - - public checkFileService() { - super("checkFileService"); - } - - public static int getFrameRate(File file) { - int frameRate = 0; - if (!getSDPath().equals("")) { - try { - MediaExtractor extractor = null; - FileInputStream fis = null; - try { - extractor = new MediaExtractor(); - fis = new FileInputStream(file); - extractor.setDataSource(fis.getFD()); - } catch (IOException e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("getFrameRate failed on MediaExtractor.<============ Crash here", mLog.e)); - return 0; - } - int numTracks = extractor.getTrackCount(); - for (int i = 0; i < numTracks; i++) { - MediaFormat format = extractor.getTrackFormat(i); - if (format.containsKey(MediaFormat.KEY_FRAME_RATE)) { - frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE); - } - } - if (extractor != null) - extractor.release(); - if (fis != null) - fis.close(); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("getFrameRate failed.<============ Crash here", mLog.e)); - } - } else { - if (null != videoLogList) - videoLogList.add(new LogMsg("getFrameRate failed " + NO_SD_CARD + ".", mLog.e)); - } - return frameRate; - } - - private void checkFile(String path) { - try { - File video = new File(path); - int frameRate = 0; - - if (video.exists()) { - try { - frameRate = getFrameRate(video); - - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("CheckFile error.", mLog.e)); - } - if (isNew) { - boolean check = false; - double[] range = isNew ? NEW_DFRAME_RATE : DFRAME_RATE; - if (frameRate >= range[isFrame]) { - if (frameRate <= range[isFrame] + 3) { - check = true; - } - } else if (frameRate < range[isFrame]) { - if (frameRate >= range[isFrame] - 3) { - check = true; - } - } - if (check) Success++; - else Fail++; - } else Success++; - } else { - Fail++; - } - if (null != videoLogList) - videoLogList.add(new LogMsg("CheckFile: " + path.split("/")[3] + " frameRate:" + frameRate + - " success:" + getSuccess() + " fail:" + getFail() + " reset:" + getReset(), mLog.i)); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("CheckFile error.", mLog.e)); - Fail++; - } - } - - private void saveLog() { - Intent intent = new Intent(); - intent.setClassName(this.getPackageName(), saveLogService.class.getName()); - startService(intent); - } - - protected void onHandleIntent(Intent intent) { - try { - path = intent.getStringExtra(EXTRA_VIDEO_PATH); - - Thread t = new Thread(() -> { - - try { - checkFile(path); - saveLog(); - } catch (Exception e) { - e.printStackTrace(); - } - }); - t.start(); - t.join(); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("CheckFileService error.", mLog.e)); - } finally { - saveLog(); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/askey/record/checkSdCardService.java b/app/src/main/java/com/askey/record/checkSdCardService.java deleted file mode 100644 index 09414ea..0000000 --- a/app/src/main/java/com/askey/record/checkSdCardService.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.askey.record; - - -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; -import android.os.StatFs; - -import com.askey.widget.LogMsg; -import com.askey.widget.mLog; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; - -import static com.askey.record.Utils.EXTRA_VIDEO_REFORMAT; -import static com.askey.record.Utils.EXTRA_VIDEO_VERSION; -import static com.askey.record.Utils.NO_SD_CARD; -import static com.askey.record.Utils.errorMessage; -import static com.askey.record.Utils.firstFile; -import static com.askey.record.Utils.getSDPath; -import static com.askey.record.Utils.getSdCard; -import static com.askey.record.Utils.isError; -import static com.askey.record.Utils.sdData; -import static com.askey.record.Utils.secondFile; -import static com.askey.record.Utils.videoLogList; - -public class checkSdCardService extends IntentService { - - public checkSdCardService() { - // ActivityのstartService(intent);で呼び出されるコンストラクタはこちら - super("checkSdCardService"); - } - - private void saveLog(Context context) { - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), saveLogService.class.getName()); - intent.putExtra(EXTRA_VIDEO_VERSION, context.getString(R.string.app_name)); - intent.putExtra(EXTRA_VIDEO_REFORMAT, false); - context.startService(intent); - } - - private void checkSdCardFromFileList() { - getSdCard = !getSDPath().equals(""); - if (getSdCard) { - try { - StatFs stat = new StatFs(getSDPath()); - long sdAvailSize = stat.getAvailableBlocksLong() - * stat.getBlockSizeLong(); - double gigaAvailable = (sdAvailSize >> 30); - if (gigaAvailable < sdData) { - if (null != videoLogList) { - videoLogList.add(new LogMsg("SD Card is Full.")); - } - ArrayList tmp = new ArrayList(); - File[] fileList = new File(getSDPath()).listFiles(); - for (int i = 0; i < fileList.length; i++) { - // Recursive call if it's a directory - File file = fileList[i]; - if (!fileList[i].isDirectory()) { - if (Utils.getFileExtension(file.toString()).equals("mp4")) - if (!file.toString().equals(firstFile) || !file.toString().equals(secondFile)) - tmp.add(file.toString()); - } - } - if (tmp.size() >= 2) { - Object[] list = tmp.toArray(); - Arrays.sort(list); - delete((String) list[0], true); - delete((String) list[1], true); - checkSdCardFromFileList(); - } - } - } catch (Exception e) { - e.printStackTrace(); - isError = true; - getSdCard = !getSDPath().equals(""); - if (getSdCard) { - if (null != videoLogList) { - videoLogList.add(new LogMsg("#error: At least " + sdData + " memory needs to be available to record, please check the SD Card free space.", mLog.e)); - saveLog(this); - } - errorMessage = "error: At least " + sdData + " memory needs to be available to record, please check the SD Card free space."; -// ((TextView) findViewById(R.id.record_status)).setText("Error"); - } else { - if (null != videoLogList) { - videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); - saveLog(this); - } - errorMessage = NO_SD_CARD; - } - } - } else { - isError = true; - if (null != videoLogList) { - videoLogList.add(new LogMsg(NO_SD_CARD, mLog.e)); - saveLog(this); - } - errorMessage = NO_SD_CARD; - } - } - - private void delete(String path, boolean fromSDcard) { - try { - if (path != "") { - File video = new File(path); - if (video.exists()) { - if (null != videoLogList) - if (fromSDcard) - videoLogList.add(new LogMsg("Delete: " + path.split("/")[3], mLog.w)); - else - videoLogList.add(new LogMsg("Delete: " + path.split("/")[5], mLog.w)); - video.delete(); - } else { - if (null != videoLogList) - videoLogList.add(new LogMsg("Video not find.", mLog.e)); - } - } - } catch (Exception e) { - e.printStackTrace(); - isError = true; - getSdCard = !getSDPath().equals(""); - if (null != videoLogList) { - videoLogList.add(new LogMsg("#delete " + path + " error. <============ Crash here", mLog.e)); - saveLog(this); - } - errorMessage = "Delete file error. <============ Crash here"; -// ((TextView) findViewById(R.id.record_status)).setText("Error"); - } - } - - @Override - protected void onHandleIntent(Intent intent) { - try { - - Thread t = new Thread(() -> { - try { - checkSdCardFromFileList(); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) { - videoLogList.add(new LogMsg("checkSdCardFromFileList error.", mLog.e)); - saveLog(this); - } - } - }); - t.start(); - t.join(); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) { - videoLogList.add(new LogMsg("CheckSdCardService error.", mLog.e)); - saveLog(this); - } - } - } -} - diff --git a/app/src/main/java/com/askey/record/copyFileService.java b/app/src/main/java/com/askey/record/copyFileService.java deleted file mode 100644 index b025858..0000000 --- a/app/src/main/java/com/askey/record/copyFileService.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.askey.record; - -import android.app.IntentService; -import android.content.Intent; -import android.util.Log; - -import com.askey.widget.LogMsg; -import com.askey.widget.mLog; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static com.askey.record.Utils.EXTRA_VIDEO_COPY; -import static com.askey.record.Utils.EXTRA_VIDEO_PASTE; -import static com.askey.record.Utils.EXTRA_VIDEO_REMOVE; -import static com.askey.record.Utils.errorMessage; -import static com.askey.record.Utils.getSDPath; -import static com.askey.record.Utils.isError; -import static com.askey.record.Utils.videoLogList; - -public class copyFileService extends IntentService { - String video; - String pathname; - boolean reomve; - - public copyFileService() { - // ActivityのstartService(intent);で呼び出されるコンストラクタはこちら - super("copyFileService"); - } - - public static void copy(String src, String dst, boolean remove) { - try { - File sf = new File(src); - InputStream in = new FileInputStream(sf); - try { - OutputStream out = new FileOutputStream(dst); - try { - // Transfer bytes from in to out - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - } catch (IOException | RuntimeException e) { - e.printStackTrace(); - isError = true; - errorMessage = "Copy file error. <============ Crash here"; - } finally { - out.close(); - } - } catch (Exception e) { - e.printStackTrace(); - isError = true; - errorMessage = "Copy file error. <============ Crash here"; - } finally { - in.close(); - if (remove) sf.delete(); - } - } catch (Exception e) { - e.printStackTrace(); - isError = true; - errorMessage = "Copy file error. <============ Crash here"; - if (null != videoLogList) - videoLogList.add(new LogMsg("Copy file error", mLog.e)); - } - } - - - protected void onHandleIntent(Intent intent) { - video = intent.getStringExtra(EXTRA_VIDEO_COPY); - pathname = intent.getStringExtra(EXTRA_VIDEO_PASTE); - reomve = intent.getBooleanExtra(EXTRA_VIDEO_REMOVE, false); - // 非同期処理を行うメソッド。タスクはonHandleIntentメソッド内で実行する - try { - if (null != videoLogList) - videoLogList.add(new LogMsg("#copy.", mLog.e)); - Log.d("IntentService", "onHandleIntent Start"); - Thread t = new Thread(() -> { - try { - if (!getSDPath().equals("")) - copy(video, pathname, reomve); - } catch (Exception e) { - e.printStackTrace(); - isError = true; - errorMessage = "Copy file error. <============ Crash here"; - if (null != videoLogList) - videoLogList.add(new LogMsg("Copy file error", mLog.e)); - } - }); - t.start(); - t.join(); - if (null != videoLogList) - videoLogList.add(new LogMsg("copy successful.", mLog.e)); - } catch (Exception e) { - e.printStackTrace(); - isError = true; - errorMessage = "Copy file error. <============ Crash here"; - if (null != videoLogList) - videoLogList.add(new LogMsg("Copy file error", mLog.e)); - } - } -} - diff --git a/app/src/main/java/com/askey/record/restartActivity.java b/app/src/main/java/com/askey/record/restartActivity.java index 5b8c41d..3a4e6c6 100644 --- a/app/src/main/java/com/askey/record/restartActivity.java +++ b/app/src/main/java/com/askey/record/restartActivity.java @@ -17,7 +17,6 @@ public static Intent createIntent(Context context) { Intent intent = new Intent(); intent.setClassName(context.getPackageName(), restartActivity.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - // メインプロセスの PID を Intent に保存しておく intent.putExtra(EXTRA_MAIN_PID, android.os.Process.myPid()); return intent; } @@ -25,13 +24,13 @@ public static Intent createIntent(Context context) { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - // 1. メインプロセスを Kill する Intent intent = getIntent(); int mainPid = intent.getIntExtra(EXTRA_MAIN_PID, -1); int EXTRA_RUN = intent.getIntExtra(EXTRA_VIDEO_RUN, 0); int EXTRA_RESET = intent.getIntExtra(EXTRA_VIDEO_RESET, 0); int EXTRA_FAIL = getIntent().getIntExtra(EXTRA_VIDEO_FAIL, 0); int EXTRA_SUCCESS = getIntent().getIntExtra(EXTRA_VIDEO_SUCCESS, 0); + boolean EXTRA_RECORD = intent.getBooleanExtra(EXTRA_VIDEO_RECORD, false); android.os.Process.killProcess(mainPid); // 2. MainActivity を再起動する @@ -43,9 +42,9 @@ public void onCreate(Bundle savedInstanceState) { restartIntent.putExtra(EXTRA_VIDEO_RESET, EXTRA_RESET); restartIntent.putExtra(EXTRA_VIDEO_FAIL, EXTRA_FAIL); restartIntent.putExtra(EXTRA_VIDEO_SUCCESS, EXTRA_SUCCESS); + restartIntent.putExtra(EXTRA_VIDEO_RECORD, EXTRA_RECORD); context.startActivity(restartIntent); - // 3. RestartActivity を終了する finish(); android.os.Process.killProcess(android.os.Process.myPid()); } diff --git a/app/src/main/java/com/askey/record/saveLogService.java b/app/src/main/java/com/askey/record/saveLogService.java deleted file mode 100644 index 4ba553d..0000000 --- a/app/src/main/java/com/askey/record/saveLogService.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.askey.record; - - -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; - -import com.askey.widget.LogMsg; -import com.askey.widget.mLog; - -import java.io.File; -import java.io.FileOutputStream; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; - -import static com.askey.record.Utils.EXTRA_VIDEO_COPY; -import static com.askey.record.Utils.EXTRA_VIDEO_PASTE; -import static com.askey.record.Utils.EXTRA_VIDEO_REFORMAT; -import static com.askey.record.Utils.EXTRA_VIDEO_REMOVE; -import static com.askey.record.Utils.EXTRA_VIDEO_VERSION; -import static com.askey.record.Utils.LOG_TITLE; -import static com.askey.record.Utils.getPath; -import static com.askey.record.Utils.getSDPath; -import static com.askey.record.Utils.logName; -import static com.askey.record.Utils.videoLogList; -import static com.askey.record.VideoRecordActivity.SD_Mode; -import static com.askey.record.restartActivity.EXTRA_MAIN_PID; - -public class saveLogService extends IntentService { - private String version; - private boolean reFormat; - - public saveLogService() { - // ActivityのstartService(intent);で呼び出されるコンストラクタはこちら - super("saveLogService"); - } - - private void saveLog(ArrayList mLogList, boolean reFormat, boolean move) { - String logString; - - File file = new File(getPath(), logName); - if (!file.exists()) { - logString = LOG_TITLE + version + "\r\n"; - try { - file.createNewFile(); - mLogList.add(new LogMsg("Create the log file.", mLog.w)); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - logString = ""; - } - - for (LogMsg logs : mLogList) { - String time = logs.time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) - + " run:" + logs.runTime + " -> "; - logString += (time + logs.msg + "\r\n"); - } - try { - FileOutputStream output = new FileOutputStream(file, !reFormat); - output.write(logString.getBytes()); - output.close(); - mLogList.clear(); - - } catch (Exception e) { - e.printStackTrace(); - } - if(SD_Mode) { - if (move) - try { - Thread tMove = new Thread(() -> { - moveFile(getPath() + logName, getSDPath() + logName, false); - }); - tMove.start(); - tMove.join(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private void moveFile(String video, String pathname, boolean remove) { - Context context = getApplicationContext(); - Intent intent = new Intent(); - intent.setClassName(context.getPackageName(), copyFileService.class.getName()); - intent.putExtra(EXTRA_VIDEO_COPY, video); - intent.putExtra(EXTRA_VIDEO_PASTE, pathname); - intent.putExtra(EXTRA_VIDEO_REMOVE, remove); - context.startService(intent); - } - - - protected void onHandleIntent(Intent intent) { - int mainPid = 0; - try { - mainPid = intent.getIntExtra(EXTRA_MAIN_PID, -1); - version = intent.getStringExtra(EXTRA_VIDEO_VERSION); - reFormat = intent.getBooleanExtra(EXTRA_VIDEO_REFORMAT, false); - - int finalMainPid = mainPid; - Thread t = new Thread(() -> { - final boolean move = finalMainPid > 0; - try { - saveLog(videoLogList, reFormat, move); - } catch (Exception e) { - e.printStackTrace(); - } - }); - t.start(); - t.join(); - } catch (Exception e) { - e.printStackTrace(); - if (null != videoLogList) - videoLogList.add(new LogMsg("SaveLogService error.", mLog.e)); - } finally { - if (mainPid > 0) android.os.Process.killProcess(mainPid); - } - } -} - diff --git a/app/src/main/java/com/askey/widget/CommandUtil.java b/app/src/main/java/com/askey/widget/CommandUtil.java deleted file mode 100644 index 5e9732d..0000000 --- a/app/src/main/java/com/askey/widget/CommandUtil.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.askey.widget; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -public class CommandUtil { - - // public static final String TAG = CommandUtil.class.getSimpleName(); - public static final String COMMAND_SH = "sh"; - public static final String COMMAND_SU = "su"; - public static final String COMMAND_LINE_END = "\n"; - public static final String COMMAND_EXIT = "exit\n"; - private static final boolean ISDEBUG = true; - - /** - * 執行單條命令 - * - * @param command - * @return - */ - public static List execute(String command) { - //CommandUtil.execute("getprop " + FRAMESKIP).get(0); - return execute(new String[]{command}); - } - - /** - * 可執行多行命令(bat) - * - * @param commands - * @return - */ - public static List execute(String[] commands) { - List results = new ArrayList(); - int status = -1; - if (commands == null || commands.length == 0) { - return null; - } -// debug("execute command start : " + commands); - Process process = null; - BufferedReader successReader = null; - BufferedReader errorReader = null; - StringBuilder errorMsg = null; - - DataOutputStream dos = null; - try { - // TODO - process = Runtime.getRuntime().exec(COMMAND_SH); - dos = new DataOutputStream(process.getOutputStream()); - for (String command : commands) { - if (command == null) { - continue; - } - dos.write(command.getBytes()); - dos.writeBytes(COMMAND_LINE_END); - dos.flush(); - } - dos.writeBytes(COMMAND_EXIT); - dos.flush(); - - status = process.waitFor(); - - errorMsg = new StringBuilder(); - successReader = new BufferedReader(new InputStreamReader( - process.getInputStream())); - errorReader = new BufferedReader(new InputStreamReader( - process.getErrorStream())); - String lineStr; - while ((lineStr = successReader.readLine()) != null) { - results.add(lineStr); -// debug(" command line item : " + lineStr); - } - while ((lineStr = errorReader.readLine()) != null) { - errorMsg.append(lineStr); - } - - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (dos != null) { - dos.close(); - } - if (successReader != null) { - successReader.close(); - } - if (errorReader != null) { - errorReader.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - if (process != null) { - process.destroy(); - } - } -// debug(String.format(Locale.CHINA, -// "execute command end,errorMsg:%s,and status %d: ", errorMsg, -// status)); - return results; - } - - public static void executed(String command) { - //CommandUtil.executed("setprop " + FRAMESKIP + " 0"); - executed(new String[]{command}); - } - - public static void executed(String[] commands) { - Process process = null; - DataOutputStream dos = null; - try { - // TODO - process = Runtime.getRuntime().exec(COMMAND_SH); - dos = new DataOutputStream(process.getOutputStream()); - for (String command : commands) { - if (command == null) { - continue; - } - dos.write(command.getBytes()); - dos.writeBytes(COMMAND_LINE_END); - dos.flush(); - } - dos.writeBytes(COMMAND_EXIT); - dos.flush(); - - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (dos != null) { - dos.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - if (process != null) { - process.destroy(); - } - } - } - -// /** -// * DEBUG LOG -// * -// * @param message -// */ -// private static void debug(String message) { -// if (ISDEBUG) { -// Log.d(TAG, message); -// } -// } - -} \ No newline at end of file diff --git a/app/src/main/java/com/askey/widget/CustomPageTransformer.java b/app/src/main/java/com/askey/widget/CustomPageTransformer.java deleted file mode 100644 index 0924686..0000000 --- a/app/src/main/java/com/askey/widget/CustomPageTransformer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.askey.widget; - -import android.view.View; - -import com.askey.record.R; - -public class CustomPageTransformer implements VerticalViewPager.PageTransformer { - @Override - public void transformPage(View view, float position) { - int pageWidth = view.getWidth(); - int pageHeight = view.getHeight(); - float dafTranslation = 0; - float xPosition = pageWidth * -position; - view.setTranslationX(xPosition); - float yPosition = position * pageHeight - dafTranslation; - view.setTranslationY(yPosition); - CustomTextView item_timezone = view.findViewById(R.id.customTextView); - item_timezone.setTextColor(view.getResources().getColor(R.color.gray_dark)); - item_timezone.setTranslationX(dafTranslation * 1.5f); - if (position < 0) { - view.setAlpha(1f + 0.3f * position); - item_timezone.setScaleX(0.2f * position + 1); - } else if (position < 1) { - view.setAlpha(1f - 0.3f * position); - item_timezone.setScaleX(-0.2f * position + 1); - item_timezone.setTextColor(view.getResources().getColor(R.color.orange)); - } else { - view.setAlpha(1f - 0.3f * position); - item_timezone.setScaleX(-0.2f * position + 1); - } - } -} diff --git a/app/src/main/java/com/askey/widget/CustomTextView.java b/app/src/main/java/com/askey/widget/CustomTextView.java old mode 100755 new mode 100644 diff --git a/app/src/main/java/com/askey/widget/PropertyUtils.java b/app/src/main/java/com/askey/widget/PropertyUtils.java deleted file mode 100755 index 812c4c4..0000000 --- a/app/src/main/java/com/askey/widget/PropertyUtils.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.askey.widget; - -import java.lang.reflect.Method; - -public class PropertyUtils { - //Use the reflection invoke SystemProperites. - //https://gist.github.com/crossle/5046538 - public static String get(String key) { - String value = ""; - try { - Class c = Class.forName("android.os.SystemProperties"); - Method get = c.getMethod("get", String.class, String.class); - value = (String) (get.invoke(c, key, "unknown")); - } catch (Exception e) { - e.printStackTrace(); - } finally { - return value; - } - } - - public static void set(String key, String value) { - try { - Class c = Class.forName("android.os.SystemProperties"); - Method set = c.getMethod("set", String.class, String.class); - set.invoke(c, key, value); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/app/src/main/java/com/askey/widget/VerticalPageTransformer.java b/app/src/main/java/com/askey/widget/VerticalPageTransformer.java old mode 100755 new mode 100644 diff --git a/app/src/main/java/com/askey/widget/VerticalPagerContainer.java b/app/src/main/java/com/askey/widget/VerticalPagerContainer.java old mode 100755 new mode 100644 diff --git a/app/src/main/java/com/askey/widget/VerticalViewPager.java b/app/src/main/java/com/askey/widget/VerticalViewPager.java old mode 100755 new mode 100644 index 07d3932..51098b3 --- a/app/src/main/java/com/askey/widget/VerticalViewPager.java +++ b/app/src/main/java/com/askey/widget/VerticalViewPager.java @@ -1,11 +1,12 @@ package com.askey.widget; import android.content.Context; -import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; +import androidx.viewpager.widget.ViewPager; + public class VerticalViewPager extends ViewPager { public VerticalViewPager(Context context) { super(context); diff --git a/app/src/main/java/com/askey/widget/ViewHolder.java b/app/src/main/java/com/askey/widget/ViewHolder.java deleted file mode 100644 index 214b64d..0000000 --- a/app/src/main/java/com/askey/widget/ViewHolder.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.askey.widget; - -import android.widget.TextView; - -public class ViewHolder { - TextView tv; -} diff --git a/app/src/main/java/com/askey/widget/mLogListAdapter.java b/app/src/main/java/com/askey/widget/mLogListAdapter.java deleted file mode 100644 index ed6631b..0000000 --- a/app/src/main/java/com/askey/widget/mLogListAdapter.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.askey.widget; - -import android.content.Context; -import android.graphics.Color; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; - -import com.askey.record.R; - -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; - -public class mLogListAdapter extends BaseAdapter { - - private LayoutInflater inflater; - private ArrayList arrayList; - - public mLogListAdapter(Context context, ArrayList arrayList) { - this.arrayList = arrayList; - inflater = LayoutInflater.from(context); - } - - public int getCount() { - return arrayList.size(); - } - - public Object getItem(int position) { - return position; - } - - public long getItemId(int position) { - return position; - } - - public View getView(int position, View convertView, ViewGroup parent) { - ViewHolder holder; - if (convertView == null) { - convertView = inflater.inflate(R.layout.style_text_item, null); - holder = new ViewHolder(); - holder.tv = convertView.findViewById(R.id.customTextView); - convertView.setTag(holder); - } else { - holder = (ViewHolder) convertView.getTag(); - } - if (arrayList.size() > 0) { - LogMsg log = arrayList.get(position); - String time = log.time.format(DateTimeFormatter.ofPattern("HH:mm:ss")) + " "; - holder.tv.setText(time + log.msg); - mLog type = log.type; - int color = type == mLog.v ? Color.BLACK : type == mLog.d ? Color.BLUE : - type == mLog.i ? Color.GREEN : type == mLog.w ? Color.YELLOW : Color.RED; - holder.tv.setTextColor(color); - } - return convertView; - } -} diff --git a/app/src/main/java/com/askey/widget/mPagerAdapter.java b/app/src/main/java/com/askey/widget/mPagerAdapter.java deleted file mode 100644 index 721cdd1..0000000 --- a/app/src/main/java/com/askey/widget/mPagerAdapter.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.askey.widget; - -import android.support.v4.view.PagerAdapter; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; - -public class mPagerAdapter extends PagerAdapter { - - ArrayList viewList; - - public mPagerAdapter(ArrayList viewList) { - this.viewList = viewList; - } - - public int getCount() { - return viewList.size(); - } - - public Object instantiateItem(ViewGroup container, int position) { - container.addView(viewList.get(position)); - return viewList.get(position); - } - - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - public void destroyItem(ViewGroup container, int position, Object object) { - container.removeView((View) object); - } -} \ No newline at end of file diff --git a/app/src/main/res/layout/activity_video_record.xml b/app/src/main/res/layout/activity_video_record.xml index 04cf1ff..1f95cb6 100644 --- a/app/src/main/res/layout/activity_video_record.xml +++ b/app/src/main/res/layout/activity_video_record.xml @@ -60,55 +60,7 @@ - - - - - - - - - - - - -