diff --git a/app/build.gradle b/app/build.gradle index 81e54c11..cc8107e1 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -5,7 +5,7 @@ plugins { // 10,00,000 major-minor-build def AppMajorVersion = 1 def AppMinorVersion = 0 -def AppBuildNumber = 121 +def AppBuildNumber = 131 def AppVersionName = AppMajorVersion + "." + AppMinorVersion + "." + AppBuildNumber def AppVersionCode = AppMajorVersion * 100000 + AppMinorVersion * 1000 + AppBuildNumber @@ -24,7 +24,7 @@ android { defaultConfig { applicationId "com.xypower.mpapp" - minSdk 25 + minSdk COMPILE_MIN_SDK_VERSION as int //noinspection ExpiredTargetSdkVersion targetSdk 28 versionCode AppVersionCode diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 40112dff..f2000d40 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -80,6 +80,7 @@ android:requestLegacyExternalStorage="true" android:supportsRtl="true" android:theme="@style/Theme.MicroPhoto" + android:extractNativeLibs="true" tools:targetApi="28"> SetListener(pTerminal); device->UpdateSignalLevel(signalLevel); + device->UpdateSimcard(simcardStr); pTerminal->InitServerInfo(appPathStr, cmdidStr, ipStr, port, udpOrTcp, encryptData); // pTerminal->SetPacketSize(1 * 1024); // 1K diff --git a/app/src/main/cpp/PhoneDevice.cpp b/app/src/main/cpp/PhoneDevice.cpp index f4f2bac8..3ab9e626 100644 --- a/app/src/main/cpp/PhoneDevice.cpp +++ b/app/src/main/cpp/PhoneDevice.cpp @@ -369,29 +369,40 @@ bool CPhoneDevice::QuerySystemProperties(std::map& pro __system_property_get("ro.build.date.utc", value); it->second = value; } - else if (it->first == PROP_SN) + else if (it->first == PROP_SN || it->first == PROP_BS_ID) { __system_property_get("ro.serialno", value); it->second = value; } else if (it->first == PROP_IMEI) { - __system_property_get("phone.imei", value); - it->second = value; + if (m_simcard.empty()) + { + __system_property_get("phone.imei", value); + it->second = value; + } + else + { + it->second = m_simcard; + } } else if (it->first == PROP_OPERATION_TEMP) { it->second = QueryCpuTemperature(); } - else if (it->first == PROP_BS_ID) - { - it->second = "SHXY"; - } else if (it->first == PROP_FREE_ROM) { fs::space_info si = fs::space("/data"); it->second = std::to_string(si.available); // Unit: M } + else if (it->first == PROP_FREE_ROM_PERCENT) + { + fs::space_info si = fs::space("/data"); + double fr = ((double)si.available * 100.0f) / ((double)si.capacity); + char buf[12] = { 0 }; + snprintf(buf, sizeof(buf), "%d%%", (int)fr); + it->second = buf; + } else if (it->first == PROP_TOTAL_ROM) { fs::space_info si = fs::space("/data"); @@ -399,12 +410,19 @@ bool CPhoneDevice::QuerySystemProperties(std::map& pro } else if (it->first == PROP_FREE_MEMORY) { - fs::space_info si = fs::space("/data"); it->second = std::to_string(android_os_Process_getFreeMemory()); // Unit: M } + else if (it->first == PROP_FREE_MEMORY_PERCENT) + { + long fm = android_os_Process_getFreeMemory(); + long tm = android_os_Process_getTotalMemory(); + double fmp = ((double)fm * 100.0f) / ((double)tm); + char buf[12] = { 0 }; + snprintf(buf, sizeof(buf), "%d%%", (int)fmp); + it->second = buf; // Unit: M + } else if (it->first == PROP_TOTAL_MEMORY) { - fs::space_info si = fs::space("/data"); it->second = std::to_string(android_os_Process_getTotalMemory()); // Unit: M } else if (it->first == (PROP_CHARGING_VOLTAGE)) @@ -909,6 +927,7 @@ bool CPhoneDevice::TakePhoto(const IDevice::PHOTO_INFO& photoInfo, const vector< params.focusTimeout = mPhotoInfo.focusTimeout * 1000; params.exposureTime = mPhotoInfo.exposureTime; params.sensibility = mPhotoInfo.sensibility; + params.compensation = mPhotoInfo.compensation; params.orientation = mPhotoInfo.orientation; params.zoom = mPhotoInfo.zoom; params.zoomRatio = mPhotoInfo.zoomRatio; @@ -1204,8 +1223,8 @@ bool CPhoneDevice::OnImageReady(cv::Mat& mat) unsigned int extime = (captureResult.exposureTime >= 1000000) ? ((unsigned int)(captureResult.exposureTime / 1000000)) : ((unsigned int)(captureResult.exposureTime / 1000)); strcpy(extimeunit, (captureResult.exposureTime >= 1000000) ? "ms" : "ns"); char str[128] = { 0 }; - snprintf(str, sizeof(str), "AE=%u EXPS=%u%s ISO=%d AF=%u LDR=%d AFS=%u AES=%u SCENE=%d AWB=%u %0.1fx", captureResult.autoExposure, - extime, extimeunit, + snprintf(str, sizeof(str), "AE=%u EXPS=%u%s(%d) ISO=%d AF=%u LDR=%d AFS=%u AES=%u SCENE=%d AWB=%u %0.1fx", captureResult.autoExposure, + extime, extimeunit, captureResult.compensation, captureResult.sensitibity, captureResult.autoFocus, // isnan(captureResult.FocusDistance) ? 0 : captureResult.FocusDistance, @@ -1430,4 +1449,9 @@ void CPhoneDevice::UpdateSignalLevel(int signalLevel) { m_signalLevel = signalLevel; m_signalLevelUpdateTime = time(NULL); +} + +void CPhoneDevice::UpdateSimcard(const std::string& simcard) +{ + m_simcard = simcard; } \ No newline at end of file diff --git a/app/src/main/cpp/PhoneDevice.h b/app/src/main/cpp/PhoneDevice.h index b3b550e5..e05a10f2 100644 --- a/app/src/main/cpp/PhoneDevice.h +++ b/app/src/main/cpp/PhoneDevice.h @@ -202,6 +202,7 @@ public: void UpdatePosition(double lon, double lat, double radius, time_t ts); bool OnVideoReady(bool result, const char* path, unsigned int photoId); void UpdateSignalLevel(int signalLevel); + void UpdateSimcard(const std::string& simcard); protected: @@ -298,6 +299,8 @@ protected: int m_signalLevel; time_t m_signalLevelUpdateTime; + std::string m_simcard; + }; diff --git a/app/src/main/cpp/PhoneDevice2.cpp b/app/src/main/cpp/PhoneDevice2.cpp index 9408115a..4dd6341e 100644 --- a/app/src/main/cpp/PhoneDevice2.cpp +++ b/app/src/main/cpp/PhoneDevice2.cpp @@ -26,7 +26,7 @@ // #include // #include -#include +// #include #include #include diff --git a/app/src/main/cpp/camera2/ndkcamera.cpp b/app/src/main/cpp/camera2/ndkcamera.cpp index 18b8419b..ca0ff101 100644 --- a/app/src/main/cpp/camera2/ndkcamera.cpp +++ b/app/src/main/cpp/camera2/ndkcamera.cpp @@ -135,6 +135,8 @@ NdkCamera::NdkCamera(int32_t width, int32_t height, const NdkCamera::CAMERA_PARA capture_session_output = 0; capture_session = 0; captureSequenceId = 0; + + mResult = { 0 }; } NdkCamera::~NdkCamera() @@ -282,9 +284,21 @@ int NdkCamera::open(const std::string& cameraId) { ACameraMetadata_const_entry e = {0}; status = ACameraMetadata_getConstEntry(camera_metadata,ACAMERA_CONTROL_AF_AVAILABLE_MODES, &e); // AASSERT(status == ACAMERA_OK, "ACameraMetadata_getConstEntry::ACAMERA_CONTROL_AF_AVAILABLE_MODES return error, %d", status); +#ifdef _DEBUG + for (int idx = 0; idx < e.count; idx++) + { + unsigned int m = e.data.u8[idx]; + XYLOG(XYLOG_SEVERITY_DEBUG, "Available AF Mode %u", m); + } +#endif afSupported = (status == ACAMERA_OK) && !(e.count == 0 || (e.count == 1 && e.data.u8[0] == ACAMERA_CONTROL_AF_MODE_OFF)); } + if (!afSupported) + { + XYLOG(XYLOG_SEVERITY_ERROR, "AF not Supported"); + } + { ACameraMetadata_const_entry val = {0}; status = ACameraMetadata_getConstEntry(camera_metadata,ACAMERA_SENSOR_INFO_EXPOSURE_TIME_RANGE, &val); @@ -343,6 +357,8 @@ int NdkCamera::open(const std::string& cameraId) { { aeCompensationRange.min_ = val.data.i32[0]; aeCompensationRange.max_ = val.data.i32[1]; + + XYLOG(XYLOG_SEVERITY_DEBUG, "AE_COMPENSATION_RANGE %d-%d", aeCompensationRange.min_, aeCompensationRange.max_); } else { @@ -351,6 +367,17 @@ int NdkCamera::open(const std::string& cameraId) { } } + { + ACameraMetadata_const_entry val = {0}; + status = ACameraMetadata_getConstEntry(camera_metadata, ACAMERA_CONTROL_AE_COMPENSATION_STEP, &val); + if (status == ACAMERA_OK) + { + aeCompensationStep = val.data.r[0]; + + XYLOG(XYLOG_SEVERITY_DEBUG, "AE_COMPENSATION_RANGE num=%d den=%d", aeCompensationStep.numerator, aeCompensationStep.denominator); + } + } + { ACameraMetadata_const_entry val = {0}; status = ACameraMetadata_getConstEntry(camera_metadata,ACAMERA_SENSOR_INFO_SENSITIVITY_RANGE, &val); @@ -421,6 +448,16 @@ int NdkCamera::open(const std::string& cameraId) { m_imagesCaptured = 0; + // capture request + { + ACameraDevice_request_template templateId = ((afSupported && m_params.autoFocus) || + m_params.autoExposure) ? TEMPLATE_PREVIEW + : TEMPLATE_STILL_CAPTURE; + status = ACameraDevice_createCaptureRequest(camera_device, templateId, &capture_request); + + int32_t fpsRange[2] = {1,1}; + status = ACaptureRequest_setEntry_i32(capture_request, ACAMERA_CONTROL_AE_TARGET_FPS_RANGE,2,fpsRange); + } if (afSupported && m_params.autoFocus) { // uint8_t afMode = ACAMERA_CONTROL_AF_MODE_CONTINUOUS_VIDEO; @@ -430,8 +467,11 @@ int NdkCamera::open(const std::string& cameraId) { if (!m_params.zoom) { - uint8_t trig = ACAMERA_CONTROL_AF_TRIGGER_START; - status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AF_TRIGGER, 1, &trig); + uint8_t trig = ACAMERA_CONTROL_AF_TRIGGER_CANCEL; + // status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AF_TRIGGER, 1, &trig); + + trig = ACAMERA_CONTROL_AF_TRIGGER_START; + // status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AF_TRIGGER, 1, &trig); } if (status == ACAMERA_OK) { @@ -446,19 +486,39 @@ int NdkCamera::open(const std::string& cameraId) { } // std::this_thread::sleep_for(std::chrono::milliseconds(128)); - // capture request - { - ACameraDevice_request_template templateId = ((afSupported && m_params.autoFocus) || m_params.autoExposure) ? TEMPLATE_PREVIEW : TEMPLATE_STILL_CAPTURE; - status = ACameraDevice_createCaptureRequest(camera_device, templateId, &capture_request); - int32_t fpsRange[2] = {1,1}; - status = ACaptureRequest_setEntry_i32(capture_request, ACAMERA_CONTROL_AE_TARGET_FPS_RANGE,2,fpsRange); + + { + if (m_params.sceneMode != 0) + { + uint8_t sceneMode = m_params.sceneMode; + status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_SCENE_MODE, 1, &sceneMode); + } if (m_params.autoExposure) { uint8_t aeMode = ACAMERA_CONTROL_AE_MODE_ON; status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_MODE, 1, &aeMode); // ACaptureRequest_setEntry_i32(capture_request, ACAMERA_SENSOR_SENSITIVITY, 1, &sensitivity_); + if ((aeCompensationRange.min_ != 0 || aeCompensationRange.max_ != 0) && m_params.compensation != 0) + { + int32_t compensation = m_params.compensation; + if (compensation < aeCompensationRange.min_) + { + compensation = aeCompensationRange.min_; + } + if (compensation > aeCompensationRange.max_) + { + compensation = aeCompensationRange.max_; + } + // int32_t aeCompensation = aeCompensationRange.max_; + status = ACaptureRequest_setEntry_i32(capture_request, ACAMERA_CONTROL_AE_EXPOSURE_COMPENSATION, 1, &compensation); + if (status != ACAMERA_OK) + { + int aa = 0; + } + } + uint8_t aePrecatureTrigger = ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER_START; status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER, 1, &aePrecatureTrigger); if (status == ACAMERA_OK) @@ -468,15 +528,19 @@ int NdkCamera::open(const std::string& cameraId) { uint8_t aeLockOff = ACAMERA_CONTROL_AE_LOCK_OFF; // ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_LOCK, 1, &aeLockOff); - } else { + } + else + { uint8_t aeMode = ACAMERA_CONTROL_AE_MODE_OFF; status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_MODE, 1, &aeMode); - if (m_params.sensibility > 0) { + if (m_params.sensibility > 0) + { int32_t sensitivity = m_params.sensibility; status = ACaptureRequest_setEntry_i32(capture_request, ACAMERA_SENSOR_SENSITIVITY, 1, &sensitivity); } - if (m_params.exposureTime > 0) { + if (m_params.exposureTime > 0) + { int64_t exposureTime = ((int64_t)m_params.exposureTime) * 1000000; status = ACaptureRequest_setEntry_i64(capture_request, ACAMERA_SENSOR_EXPOSURE_TIME, 1, &exposureTime); } @@ -487,11 +551,6 @@ int NdkCamera::open(const std::string& cameraId) { uint8_t awbMode = ACAMERA_CONTROL_AWB_MODE_AUTO; status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AWB_MODE, 1, &awbMode); - if (m_params.sceneMode != 0) { - uint8_t sceneMode = m_params.sceneMode; - status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_SCENE_MODE, 1, &sceneMode); - } - status = ACameraOutputTarget_create(image_reader_surface, &image_reader_target); status = ACaptureRequest_addTarget(capture_request, image_reader_target); } @@ -949,18 +1008,19 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque if (afSupported && (m_params.autoFocus != 0)) { + // if (mResult.afState == ACAMERA_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED || mResult.afState == ACAMERA_CONTROL_AF_STATE_PASSIVE_UNFOCUSED) if (mResult.afState == ACAMERA_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) { - uint8_t aePrecatureTrigger = ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL; - status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER, 1, &aePrecatureTrigger); + // uint8_t aePrecatureTrigger = ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL; + // status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER, 1, &aePrecatureTrigger); - aePrecatureTrigger = ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER_START; - status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER, 1, &aePrecatureTrigger); - XYLOG(XYLOG_SEVERITY_INFO, "onCaptureCompleted New Focus Trigger AFS=%u AES=%u Time=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); + // aePrecatureTrigger = ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER_START; + // status = ACaptureRequest_setEntry_u8(capture_request, ACAMERA_CONTROL_AE_PRECAPTURE_TRIGGER, 1, &aePrecatureTrigger); + // XYLOG(XYLOG_SEVERITY_INFO, "onCaptureCompleted New Focus Trigger AFS=%u AES=%u Time=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); return; } - ALOGD("onCaptureCompleted AFS=%u AES=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); + ALOGD("onCaptureCompleted 1 AFS=%u AES=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); if (mResult.afState == ACAMERA_CONTROL_AF_STATE_PASSIVE_FOCUSED || mResult.afState == ACAMERA_CONTROL_AF_STATE_FOCUSED_LOCKED) // if (afState != ACAMERA_CONTROL_AF_STATE_INACTIVE) { @@ -1014,11 +1074,13 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque mResult.zoomRatio = *val.data.f; } + /* val = { 0 }; status = ACameraMetadata_getConstEntry(result, ACAMERA_CONTROL_AF_STATE, &val); mResult.afState = *(val.data.u8); + */ - ALOGD("onCaptureCompleted AFS=%u AES=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); + ALOGD("onCaptureCompleted 2 AFS=%u AES=%u", (unsigned int)mResult.afState, (unsigned int)mResult.aeState); val = {0}; status = ACameraMetadata_getConstEntry(result, ACAMERA_SENSOR_SENSITIVITY, &val); @@ -1032,6 +1094,10 @@ void NdkCamera::onCaptureCompleted(ACameraCaptureSession* session, ACaptureReque status = ACameraMetadata_getConstEntry(result, ACAMERA_CONTROL_AF_MODE, &val); mResult.autoFocus = *(val.data.u8); + val = {0}; + status = ACameraMetadata_getConstEntry(result, ACAMERA_CONTROL_AE_EXPOSURE_COMPENSATION, &val); + mResult.compensation = *(val.data.i32); + ALOGD("onCaptureCompleted EXPO=%lld, FD=%f camera id=%s, AE=%s AFS=%u AES=%u", exTime, focusDistance, mCameraId.c_str(), ((aeMode == 1) ? "ON" : "OFF"), mResult.afState, mResult.aeState); // __android_log_print(ANDROID_LOG_WARN, "NdkCamera", "onCaptureCompleted %p %p %p", session, request, result); diff --git a/app/src/main/cpp/camera2/ndkcamera.h b/app/src/main/cpp/camera2/ndkcamera.h index 72fd6d33..246287b7 100644 --- a/app/src/main/cpp/camera2/ndkcamera.h +++ b/app/src/main/cpp/camera2/ndkcamera.h @@ -78,6 +78,7 @@ public: unsigned int reserved : 7; unsigned int exposureTime; // ms unsigned int sensibility; + int compensation; float zoomRatio; }; @@ -91,9 +92,9 @@ public: int64_t exposureTime; float FocusDistance; int32_t sensitibity; + int32_t compensation; uint8_t sceneMode; float zoomRatio; - }; NdkCamera(int32_t width, int32_t height, const CAMERA_PARAMS& params); @@ -146,6 +147,7 @@ protected: // int32_t sensitivity_; RangeValue sensitivityRange; RangeValue aeCompensationRange; + ACameraMetadata_rational aeCompensationStep; unsigned int m_imagesCaptured; diff --git a/app/src/main/java/com/xypower/mpapp/ChannelActivity.java b/app/src/main/java/com/xypower/mpapp/ChannelActivity.java index 448a06b5..91f19f46 100644 --- a/app/src/main/java/com/xypower/mpapp/ChannelActivity.java +++ b/app/src/main/java/com/xypower/mpapp/ChannelActivity.java @@ -164,6 +164,11 @@ public class ChannelActivity extends AppCompatActivity { binding.exposuretime.setText(Integer.toString(jsonObject.optInt("exposureTime", 0))); binding.sensitivity.setText(Integer.toString(jsonObject.optInt("sensibility", 0))); binding.btnZoom.setChecked(jsonObject.optInt("zoom", 0) == 1); + if (jsonObject.has("compensation")) { + binding.compensation.setText(Integer.toString(jsonObject.optInt("compensation", 0))); + } else { + binding.compensation.setText(""); + } NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(1); @@ -272,6 +277,12 @@ public class ChannelActivity extends AppCompatActivity { } else { jsonObject.put("zoomRatio", 0f); } + String text = binding.compensation.getText().toString(); + if (TextUtils.isEmpty(text)) { + jsonObject.remove("compensation"); + } else { + jsonObject.put("compensation", Integer.parseInt(text)); + } if (!TextUtils.isEmpty(binding.resolutionCX.getText().toString())) { jsonObject.put("resolutionCX", Integer.parseInt(binding.resolutionCX.getText().toString())); } else { diff --git a/app/src/main/java/com/xypower/mpapp/MainActivity.java b/app/src/main/java/com/xypower/mpapp/MainActivity.java index 30da600c..12b1f125 100644 --- a/app/src/main/java/com/xypower/mpapp/MainActivity.java +++ b/app/src/main/java/com/xypower/mpapp/MainActivity.java @@ -119,7 +119,6 @@ public class MainActivity extends AppCompatActivity { // ViewUtils.hideSoftKeyboard(this); - ActionBar actionBar = getSupportActionBar(); // String buildTime = BuildConfig.BUILD_ diff --git a/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java b/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java index 8685eb9b..264eab6f 100644 --- a/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java +++ b/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java @@ -79,17 +79,11 @@ public class MicroPhotoService extends Service { public static final int MSG_WHAT_LOG = 10; - public final static int MSG_WHAT_NETWORK_CHANGE = 20; - - public final static int MSG_WHAT_SERVICE_STATUS_CHANGE = 30; - public final static int MSG_WHAT_SENDING_HB = 40; public final static int MSG_WHAT_MAX = 1000; - private static final String ALARM_EVENT = "com.xinyingpower.mp.MicroPhotoService.AlarmReceiver"; public static final int NOTIFICATION_ID_FOREGROUND_SERVICE = 8466503; - // public static final int NOTIFICATION_ID_FOREGROUND_SERVICE = 0; public static final String ACTION_MSG_BROADCAST = "ACT_MSG_BROADCAST"; public static final String ACTION_START = "com.xypower.mpapp.ACT_START"; @@ -97,6 +91,7 @@ public class MicroPhotoService extends Service { public static final String ACTION_MAIN = "com.xypower.mpapp.ACT_MAIN"; private static final String ACTION_HEARTBEAT = MicroPhotoContext.ACTION_HEARTBEAT_MP; private static final String ACTION_TAKE_PHOTO = "com.xypower.mpapp.ACT_TP"; + private static final String ACTION_GPS_TIMEOUT = "com.xypower.mpapp.GPS_TIMEOUT"; private static final String ACTION_IMP_PUBKRY = "com.xypower.mpapp.ACT_IMP_PUBKEY"; @@ -111,12 +106,10 @@ public class MicroPhotoService extends Service { private static final String EXTRA_PARAM_SCHEDULE = "Schedule_"; private static final String EXTRA_PARAM_TAKING_TIME = "TakingTime"; private static final String EXTRA_PARAM_TIME = "Time"; - // private static String EXTRA_PARAM_FILENAME = "FileName"; - private static final String EXTRA_PARAM_TIMER_UID = "TimerUid"; - // private static String EXTRA_PARAM_TIMER_TYPE = "TimerType"; - private static final String EXTRA_PARAM_TIMEOUT = "Timeout"; - private static final String EXTRA_PARAM_TIMES = "Times"; - private static final String EXTRA_PARAM_ELASPED_TIMES = "ElapsedTimes"; + // private static final String EXTRA_PARAM_TIMER_UID = "TimerUid"; + // private static final String EXTRA_PARAM_TIMEOUT = "Timeout"; + // private static final String EXTRA_PARAM_TIMES = "Times"; + // private static final String EXTRA_PARAM_ELASPED_TIMES = "ElapsedTimes"; private static final String FOREGROUND_CHANNEL_ID = "foreground_channel_id"; public static class STATE_SERVICE { public static final int CONNECTED = 10; @@ -128,10 +121,9 @@ public class MicroPhotoService extends Service { private NotificationManager mNotificationManager; private final Map mWakeLocks = new HashMap<>(); private int mHeartbeatDuration = 0; // MUST BE 0!!! - private long mNextHeartbeatTime = 0; + // private long mNextHeartbeatTime = 0; - private PositionManager mPositionManager = null; - private final Map mTimers = new HashMap<>(); + // private final Map mTimers = new HashMap<>(); protected long mNativeHandle = 0; private AlarmReceiver mAlarmReceiver = null; @@ -139,6 +131,9 @@ public class MicroPhotoService extends Service { private ScreenActionReceiver mScreenaAtionReceiver = null; private NetworkChangedReceiver mNetworkChangedReceiver = null; + private long mGpsTimeout = 60000; // 1 minute + private PendingIntent mPreviousGpsTimer = null; + private ServiceHandler mHander = null; private Messenger mMessenger = null; @@ -182,6 +177,7 @@ public class MicroPhotoService extends Service { intentFilter.addAction(ACTION_UPDATE_CONFIGS); intentFilter.addAction(ACTION_IMP_PUBKRY); intentFilter.addAction(ACTION_TAKE_PHOTO_MANUALLY); + intentFilter.addAction(ACTION_GPS_TIMEOUT); // intentFilter.addAction(ACTION_HEARTBEAT_MANUALLY); // intentFilter.addAction(ACTION_MSG_BROADCAST); // intentFilter.addAction(ACTION_VIDEO_FINISHED); @@ -376,6 +372,14 @@ public class MicroPhotoService extends Service { } else if (TextUtils.equals(ACTION_IMP_PUBKRY, action)) { String path = intent.getStringExtra("path"); String md5 = intent.getStringExtra("md5"); + } else if (TextUtils.equals(ACTION_GPS_TIMEOUT, action)) { + mService.mPreviousGpsTimer = null; + try { + mService.mLocationManager.removeUpdates(mService.mLocationListener); + } catch (Exception ex) { + ex.printStackTrace(); + } + mService.enableGps(false); } } } @@ -383,11 +387,26 @@ public class MicroPhotoService extends Service { // Will be called fron native private void registerHeartbeatTimer(int duration, long nextPhotoTime) { int orgHeartbeatDuration = mHeartbeatDuration; - mHeartbeatDuration = duration; + if (orgHeartbeatDuration == 0) { - registerHeartbeatTimer(); + if (nextPhotoTime == 0) { + mHeartbeatDuration = duration; + registerHeartbeatTimer(); + } else { + long ts = System.currentTimeMillis(); + nextPhotoTime *= 1000; + if (nextPhotoTime > ts) { + mHeartbeatDuration = (int) ((nextPhotoTime - ts) % duration) + 999; + registerHeartbeatTimer(); + mHeartbeatDuration = duration; + } else { + mHeartbeatDuration = duration; + registerHeartbeatTimer(); + } + } + } else { + mHeartbeatDuration = duration; } - } private void registerHeartbeatTimer() { @@ -399,7 +418,7 @@ public class MicroPhotoService extends Service { AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + mHeartbeatDuration, pendingIntent); - mNextHeartbeatTime = System.currentTimeMillis() + mHeartbeatDuration; + // mNextHeartbeatTime = System.currentTimeMillis() + mHeartbeatDuration; // alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeout, pendingIntent); } @@ -664,6 +683,12 @@ public class MicroPhotoService extends Service { long startTime = (date.getTime() + 999) / 1000; service.updateCaptureSchedule(startTime); + if (mPreviousLocation != null) { + service.updatePosition(mNativeHandle, mPreviousLocation.getLongitude(), mPreviousLocation.getLatitude(), + mPreviousLocation.getAccuracy(), mPreviousLocation.getTime() / 1000); + } + + /* try { Location location = mLocationManager.getLastKnownLocation(mLocateType); if (location != null) { @@ -672,6 +697,8 @@ public class MicroPhotoService extends Service { } catch (Exception ex) { ex.printStackTrace(); } + + */ } } }; @@ -1054,6 +1081,35 @@ public class MicroPhotoService extends Service { */ } public void enableGps(boolean enabled) { + if (enabled) { + try { + AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); + if (mPreviousGpsTimer != null) { + alarmManager.cancel(mPreviousGpsTimer); + mPreviousGpsTimer = null; + } + + Intent intent = new Intent(); + intent.setAction(ACTION_GPS_TIMEOUT); + mPreviousGpsTimer = PendingIntent.getBroadcast(this, 0, intent, 0); + + alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + mGpsTimeout, mPreviousGpsTimer); + } catch (Exception ex) { + ex.printStackTrace(); + } + } else { + if (mPreviousGpsTimer != null) { + try { + AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); + alarmManager.cancel(mPreviousGpsTimer); + } catch (Exception ex) { + ex.printStackTrace(); + } finally { + mPreviousGpsTimer = null; + } + } + } + SysApi.enableGps(getApplicationContext(), enabled); } @@ -1090,19 +1146,22 @@ cellSignalStrengthGsm.getDbm(); ////////////////////////GPS//////////////////// // private static final String GPS_LOCATION_NAME = android.location.LocationManager.GPS_PROVIDER; private LocationManager mLocationManager; + private Location mPreviousLocation = null; private String mLocateType; private LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { + if (mNativeHandle != 0) { updatePosition(mNativeHandle, location.getLongitude(), location.getLatitude(), location.getAccuracy(), location.getTime() / 1000); - - mLocationManager.removeUpdates(this); - // Close GPS - enableGps(false); + } else { + mPreviousLocation = location; } + mLocationManager.removeUpdates(this); + // Close GPS + enableGps(false); Log.i(TAG, "Time:" + location.getTime() + " Lon=" + location.getLongitude() + "Lat=" + location.getLatitude() + "Alt=" + location.getAltitude()); } diff --git a/app/src/main/res/layout/activity_channel.xml b/app/src/main/res/layout/activity_channel.xml index f5d1986c..07f79765 100644 --- a/app/src/main/res/layout/activity_channel.xml +++ b/app/src/main/res/layout/activity_channel.xml @@ -246,6 +246,27 @@ app:layout_constraintStart_toEndOf="@+id/btnZoom" app:layout_constraintTop_toTopOf="@+id/btnZoom" /> + + + + 压缩率(50-100) USB Camera 短视频时长(秒) + 曝光补偿 Hello blank fragment Record diff --git a/common/src/main/java/com/xypower/common/ZipUtils.java b/common/src/main/java/com/xypower/common/ZipUtils.java index d43fafba..701ac236 100644 --- a/common/src/main/java/com/xypower/common/ZipUtils.java +++ b/common/src/main/java/com/xypower/common/ZipUtils.java @@ -51,7 +51,7 @@ public class ZipUtils { } // for (int i = 0; i < fileList.length; i++) { - if (fileList[i].startsWith("specdata")) { + if (fileList[i].startsWith("specdata") || fileList[i].endsWith(".lck")) { continue; } ZipFiles(srcFileParentName + srcFileName + "/", fileList[i], zipOutputSteam); diff --git a/gradle.properties b/gradle.properties index b4d7f13a..70dee003 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,7 +18,13 @@ android.nonTransitiveRClass=true android.useAndroidX=true android.enableJetifier=true +BUILD_TOOLS_VERSION=33.0.3 +COMPILE_SDK_VERSION=33 +TARGET_SDK_VERSION=28 +COMPILE_MIN_SDK_VERSION=25 + opencvsdk=D:/Workspace/deps/opencv-mobile-4.9.0-android +# opencvsdk=D:/Workspace/deps/opencv-mobile-3.4.20-android coreroot=D:/Workspace/Github/xymp/xymp/Core # opencvsdk=D:/Workspace/deps/opencv-v5 asioroot=D:/Workspace/deps/asio-1.28.0 diff --git a/mpmaster/build.gradle b/mpmaster/build.gradle index 58aff4e4..348364fc 100644 --- a/mpmaster/build.gradle +++ b/mpmaster/build.gradle @@ -4,7 +4,7 @@ plugins { def AppMajorVersion = 1 def AppMinorVersion = 0 -def AppBuildNumber = 31 +def AppBuildNumber = 33 def AppVersionName = AppMajorVersion + "." + AppMinorVersion + "." + AppBuildNumber def AppVersionCode = AppMajorVersion * 100000 + AppMinorVersion * 1000 + AppBuildNumber diff --git a/mpmaster/src/main/AndroidManifest.xml b/mpmaster/src/main/AndroidManifest.xml index 7c9581af..06ef67fd 100644 --- a/mpmaster/src/main/AndroidManifest.xml +++ b/mpmaster/src/main/AndroidManifest.xml @@ -79,6 +79,7 @@ android:requestLegacyExternalStorage="true" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" + android:extractNativeLibs="true" android:theme="@style/Theme.MpMaster" tools:targetApi="28"> > postParams = new ArrayList<>(); postParams.add(new Pair("id", mCmdid)); postParams.add(new Pair("XyDev", "1")); + if (mBundleWithMpApp) { + postParams.add(new Pair("bundled", "1")); + } postParams.add(new Pair("bootTime", Long.toString(getBootTime()))); postParams.add(new Pair("i1Version", mService.getMpAppVersion())); postParams.add(new Pair("oid", mService.getSerialNo())); postParams.add(new Pair("maintainVersion", mService.getMasterAppVersion())); - postParams.add(new Pair("simcard1", getImei(1))); - if (mService.isSeparateNetwork()) { - postParams.add(new Pair("simcard2", getImei(2))); - } + postParams.add(new Pair("simcard1", mService.getIccid(1))); + // if (mService.isSeparateNetwork()) { + postParams.add(new Pair("simcard2", mService.getIccid(2))); + // } postParams.add(new Pair("freeROM", getFreeROM())); buildStats(startTime, postParams); @@ -406,17 +416,21 @@ public class AppMaster { String cmd = jsonObject.optString("cmd", ""); if (TextUtils.equals(cmd, CMD_REBOOT_DEV)) { + mService.logger.warning("Recv Reset Cmd"); SysApi.reboot(mService.getApplicationContext()); } else if (TextUtils.equals(cmd, CMD_UPLOAD_LOGS)) { String url = jsonObject.optString("url", null); uploadLogs(url); + uploadMasterLogs(url); } else if (TextUtils.equals(cmd, CMD_SET_CMA)) { String ip = jsonObject.optString("value_str", null); int port = jsonObject.optInt("value_int", 0); + mService.logger.warning("Recv Set CMA Cmd: " + (TextUtils.isEmpty(ip) ? "" : ip) + " port=" + Integer.toString(port)); updateCma(ip, port); } else if (TextUtils.equals(cmd, CMD_SET_MNTN)) { String ip = jsonObject.optString("value_str", null); int port = jsonObject.optInt("value_int", 0); + mService.logger.warning("Recv Set Mntn Cmd: " + (TextUtils.isEmpty(ip) ? "" : ip) + " port=" + Integer.toString(port)); String newUrl = buildMntnServer(ip, port); if (newUrl != null) { mService.updateMntn(newUrl); @@ -500,6 +514,13 @@ public class AppMaster { deleteFile(path); } else if (TextUtils.equals(cmd, CMD_IMPORT_PUB_KEY)) { + } else if (TextUtils.equals(cmd, CMD_UPD_OTA)) { + String url = jsonObject.optString("url", null); + String fileName = jsonObject.optString("fileName", null); + String md5 = jsonObject.optString("md5", null); + if (!TextUtils.isEmpty(url)) { + upgradeOta(cid, cmd, url, fileName, md5); + } } } @@ -658,6 +679,8 @@ public class AppMaster { private void upgradeApp(long cid, String action, String url) { + mService.logger.warning("Recv Upgrade Cmd: url=" + url); + FileDownloader dl = new FileDownloader(); File path = new File(MicroPhotoContext.buildAppDir(mService.getApplicationContext()), "packages"); if (!path.exists()) { @@ -678,6 +701,30 @@ public class AppMaster { } } + private void upgradeOta(long cid, String action, String url, String fileName, String md5) { + + mService.logger.warning("Recv Upgrade OTA: url=" + url); + + FileDownloader dl = new FileDownloader(); + File path = new File(MicroPhotoContext.buildAppDir(mService.getApplicationContext()), "ota"); + if (!path.exists()) { + path.mkdirs(); + } + + File file = new File(path, fileName == null ? "ota.zip" : fileName); + if (file.exists()) { + file.delete(); + } + String otaPath = file.getAbsolutePath(); + if (dl.download(url, otaPath)) { + sendResult(cid, 1, action, action + ":" + mCmdid); + Context context = mService.getApplicationContext(); + mService.logger.info("Upgrade OTA: " + url); + + SysApi.installOTA(context, context.getPackageName(), otaPath); + } + } + private void uploadLogs(String url) { String appDir = mService.buildAppDir(); @@ -717,6 +764,77 @@ public class AppMaster { } } + private void uploadMasterLogs(String url) { + String appDir = mService.buildAppDir(); + + try { + + long ts = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis(); + SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); + Date dt = new Date(ts); + + final String fileName = mCmdid + "_mst_" + format.format(dt) + ".zip"; + final File file = File.createTempFile(fileName, null, new File(appDir)); + if (file == null) { + return; + } + + final String mpAppDir = MicroPhotoContext.buildMasterAppDir(mService.getApplicationContext()); + final File logDir = new File(mpAppDir + "logs" + File.separator); + if (!logDir.exists()) { + return; + } + + ZipUtils.ZipFolder(logDir, file); + + if (!file.exists()) { + return; + } + + FileUploader fileUploader = new FileUploader(url); + fileUploader.addFilePart("file", file, fileName, "application/x-zip-compressed"); + + String response = fileUploader.finish(); + if (response != null) { + + } + } catch (Exception ex) { + + } + } + + private void uploadLogs(String url, String tempPath, String path, String ext, String uploadFileName) { + + try { + + final File pathFile = new File(path); + if (!pathFile.exists()) { + return; + } + + final File file = File.createTempFile(uploadFileName, null, new File(tempPath)); + if (file == null) { + return; + } + + ZipUtils.ZipFolder(pathFile, file); + + if (!file.exists()) { + return; + } + + FileUploader fileUploader = new FileUploader(url); + fileUploader.addFilePart("file", file, uploadFileName, "application/x-zip-compressed"); + + String response = fileUploader.finish(); + if (response != null) { + + } + } catch (Exception ex) { + + } + } + private void uploadFiles(String url, List paths) { String appDir = mService.buildAppDir(); diff --git a/mpmaster/src/main/java/com/xypower/mpmaster/MpMasterService.java b/mpmaster/src/main/java/com/xypower/mpmaster/MpMasterService.java index 86f6286f..dc7c367e 100644 --- a/mpmaster/src/main/java/com/xypower/mpmaster/MpMasterService.java +++ b/mpmaster/src/main/java/com/xypower/mpmaster/MpMasterService.java @@ -22,6 +22,8 @@ import android.os.Message; import android.os.PowerManager; import android.os.SystemClock; import android.telephony.SignalStrength; +import android.telephony.SubscriptionInfo; +import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; @@ -53,7 +55,6 @@ public class MpMasterService extends Service { public Logger logger; - public final static int MSG_WHAT_SENDING_HB = 40; public static final int NOTIFICATION_ID_FOREGROUND_SERVICE = 8466503; public static final String ACTION_MSG_BROADCAST = "ACT_MSG_BROADCAST"; @@ -61,7 +62,9 @@ public class MpMasterService extends Service { public static final String ACTION_STOP = "com.xypower.mpmaster.ACT_STOP"; public static final String ACTION_MAIN = "com.xypower.mpmaster.ACT_MAIN"; - public static final String ACTION_UPD_OTA = "com.xy.otaupdateresult"; + public static final String ACTION_UPD_OTA = SysApi.OTA_RESULT_ACTION; + public static final String ACTION_INSTALL_RESULT = SysApi.INSTALL_RESULT_ACTION; + public static final String ACTION_UNINSTALL_RESULT = SysApi.UNINSTALL_RESULT_ACTION; private static final String ACTION_UPDATE_CONFIGS = "com.xypower.mpmaster.ACT_UPD_CFG"; @@ -112,6 +115,9 @@ public class MpMasterService extends Service { private PendingIntent mPreviousHB = null; private long mPreviousHeartbeatTime = 0; + private String mIccid1 = null; + private String mIccid2 = null; + public MpMasterService() { } @Override @@ -125,7 +131,7 @@ public class MpMasterService extends Service { super.onCreate(); loadConfig(); - + loadIccid(); logger = Logger.getLogger("com.xypower.mpmaster.logger"); logger.setLevel(Level.ALL); // LogFormatter.installFormatter(logger); @@ -150,6 +156,7 @@ public class MpMasterService extends Service { fileHandler = new FileHandler(logFile.getAbsolutePath(), true);//true表示日志内容在文件中追加 fileHandler.setLevel(Level.ALL);//级别为ALL,记录所有消息 + // fileHandler. fileHandler.setFormatter(logFormatter); logger.addHandler(fileHandler); @@ -197,6 +204,8 @@ public class MpMasterService extends Service { intentFilter.addAction(ACTION_MSG_BROADCAST); intentFilter.addAction(ACTION_UPDATE_CONFIGS); intentFilter.addAction(ACTION_UPD_OTA); + intentFilter.addAction(ACTION_INSTALL_RESULT); + intentFilter.addAction(ACTION_UNINSTALL_RESULT); if (!mSeparateNetwork) { intentFilter.addAction(MicroPhotoContext.ACTION_HEARTBEAT_MP); } @@ -222,12 +231,20 @@ public class MpMasterService extends Service { // AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); - startMaster(); + // startMaster(false); startMpApp(); registerHeartbeatTimer(); } + public String getIccid(int number) { + if (number == 1) { + return mIccid1 == null ? "" : mIccid1; + } else { + return mIccid2 == null ? "" : mIccid2; + } + } + @Override public void onDestroy() { @@ -240,6 +257,13 @@ public class MpMasterService extends Service { unregisterReceiver(mUpdateReceiver); unregisterReceiver(mSmsSnedReceiver); + for (java.util.logging.Handler h : logger.getHandlers()) { + try { + h.close(); + } catch (Exception ex) { + } + } + super.onDestroy(); } @@ -269,6 +293,31 @@ public class MpMasterService extends Service { mTimeOfMpAppAlive = masterConfig.mpappMonitorTimeout; } + private void loadIccid() { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) + { + try { + SubscriptionManager sm = SubscriptionManager.from(this); + List sis = sm.getActiveSubscriptionInfoList(); + if (sis.size() >= 1) { + SubscriptionInfo si1 = sis.get(0); + mIccid1 = si1.getIccId(); + // String phoneNum1 = si1.getNumber(); + } + if (sis.size() >= 2) { + SubscriptionInfo si2 = sis.get(1); + mIccid2 = si2.getIccId(); + // String phoneNum2 = si2.getNumber(); + } + // int count = sm.getActiveSubscriptionInfoCount();// real cards + // int max = sm.getActiveSubscriptionInfoCountMax();// Slot number + + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + // public boolean useSeparater public String getCmdid() { return mCmdid; @@ -374,7 +423,7 @@ public class MpMasterService extends Service { } } - private void startMaster() { + private void startMaster(boolean bundleWithMpApp) { String masterUrl = MicroPhotoContext.DEFAULT_MASTER_URL; MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(getApplicationContext()); @@ -387,7 +436,7 @@ public class MpMasterService extends Service { logger.warning("Start Mntn report:" + masterUrl); - AppMaster appMaster = new AppMaster(this, masterUrl, appConfig.cmdid); + AppMaster appMaster = new AppMaster(this, masterUrl, appConfig.cmdid, bundleWithMpApp); appMaster.start(); } @@ -406,7 +455,7 @@ public class MpMasterService extends Service { mService.registerHeartbeatTimer(); - mService.startMaster(); + mService.startMaster(false); mService.startMpApp(); } else if (TextUtils.equals(MicroPhotoContext.ACTION_HEARTBEAT_MP, action)) { @@ -415,7 +464,7 @@ public class MpMasterService extends Service { mService.registerHeartbeatTimer(mService.mPreviousHeartbeatTime + mService.mHeartbeatDuration * 1000); - mService.startMaster(); + mService.startMaster(true); mService.startMpApp(); } } else if (TextUtils.equals(ACTION_UPDATE_CONFIGS, action)) { @@ -428,6 +477,48 @@ public class MpMasterService extends Service { } } else if (TextUtils.equals(ACTION_UPD_OTA, action)) { + String cmd = intent.getStringExtra("cmd"); + String msg = intent.getStringExtra("msg"); + // Log.e("_otg_","cmd="+cmd); + if("write".equals(cmd)) + { + // int progress = Integer.parseInt(msg); + } + else if("update".equals(cmd)) + { + // int progress = Integer.parseInt(msg); + } + else if("info".equals(cmd)) + { + + } + else if("error".equals(cmd)) + { + mService.logger.warning("UPD OTA Failed"); + } + else if("success".equals(cmd)) + { + //confirm to reboot device ?? + mService.logger.warning("UPD OTA Succeeded, will RESET dev"); + Handler handler = new Handler(); + handler.postDelayed(new Runnable() { + @Override + public void run() { + SysApi.reboot(context); + } + }, 1000); + } + } else if (TextUtils.equals(ACTION_INSTALL_RESULT, action)) { + boolean bSucc = intent.getBooleanExtra("succ", false); + String pkname = intent.getStringExtra("pkname"); + String msg = intent.getStringExtra("msg"); + // Log.e("_otg_","install result bsuc="+bSucc+",pkname="+pkname+",msg="+msg); + mService.logger.warning("INSTALL APP result =" + bSucc + ",pkname=" + pkname + ",msg=" + msg); + } else if (TextUtils.equals(ACTION_UNINSTALL_RESULT, action)) { + boolean bSucc = intent.getBooleanExtra("succ", false); + String pkname = intent.getStringExtra("pkname"); + String msg = intent.getStringExtra("msg"); + mService.logger.warning("UNINSTALL APP result =" + bSucc + ",pkname=" + pkname + ",msg=" + msg); } } } @@ -491,7 +582,7 @@ public class MpMasterService extends Service { registerHeartbeatTimer(); - startMaster(); + startMaster(false); break; case ACTION_STOP: @@ -745,11 +836,12 @@ public class MpMasterService extends Service { @Override public void run() { if (rebootType == 0) { + logger.warning("Recv REBOOT MpMst APP cmd"); Context context = MpMasterService.this.getApplicationContext(); restartApp(context, context.getPackageName()); } else { - Log.w(TAG, "Recv REBOOT command"); + logger.warning("Recv RESET cmd"); SysApi.reboot(MpMasterService.this.getApplicationContext()); } } @@ -778,6 +870,7 @@ public class MpMasterService extends Service { } public void selectSimCard(int num) { + logger.warning("Select SimCard: " + Integer.toString(num)); SysApi.selectSimCard4Data(getApplicationContext(), num); } diff --git a/mpmaster/src/main/java/com/xypower/mpmaster/UpdateReceiver.java b/mpmaster/src/main/java/com/xypower/mpmaster/UpdateReceiver.java index 96946481..0085a8e0 100644 --- a/mpmaster/src/main/java/com/xypower/mpmaster/UpdateReceiver.java +++ b/mpmaster/src/main/java/com/xypower/mpmaster/UpdateReceiver.java @@ -3,7 +3,13 @@ package com.xypower.mpmaster; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; +import android.text.TextUtils; import android.util.Log; +import android.os.Handler; + +import com.xypower.common.MicroPhotoContext; + +import java.io.File; public class UpdateReceiver extends BroadcastReceiver { @@ -40,6 +46,41 @@ public class UpdateReceiver extends BroadcastReceiver { } } + private void packageChanged(Context context, String action, String packageName, String targetPackageName, String aliveFileName) { + if (action.equals(Intent.ACTION_PACKAGE_REPLACED)) { // Upgrade Broadcast + Log.e(TAG, "onReceive:Upgraded and Restart the App:" + targetPackageName); + MpMasterService.resetVersions(); + if (packageName.equals("package:" + targetPackageName)) { + // SysApi.enableApp(context, targetPackageName); + tryToRestartApp(context, targetPackageName); + } + } else if (action.equals(Intent.ACTION_PACKAGE_ADDED)) {// Install broadcast + Log.e(TAG, "onReceive:Installed and Start the App:" + targetPackageName); + MpMasterService.resetVersions(); + if (packageName.equals("package:" + targetPackageName)) { + /*SystemUtil.reBootDevice();*/ + // SysApi.enableApp(context, targetPackageName); + tryToRestartApp(context, targetPackageName); + } + } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { // Uninstall + // Logger.e(TAG, "onReceive:uninstall" + packageName); + } + } + + private void tryToRestartApp(final Context context, final String targetPackageName) { + Handler handler = new Handler(); + handler.postDelayed(new Runnable() { + @Override + public void run() { + if (TextUtils.equals(targetPackageName, APP_PACKAGE_MPAPP)) { + startMpApp(context); + } else { + restartAPP(context, targetPackageName); + } + } + }, 10000); + } + public static void restartAPP(Context context, String packageName) { Intent intent = context.getPackageManager() .getLaunchIntentForPackage(packageName); @@ -47,4 +88,29 @@ public class UpdateReceiver extends BroadcastReceiver { context.startActivity(intent); // ActManager.getAppManager().finishAllActivity(); } + + public void startMpApp(final Context context) { + try { + + if (MicroPhotoContext.isAppAlive(context, MicroPhotoContext.PACKAGE_NAME_MPAPP)) { + return; + } + + String appPath = MicroPhotoContext.buildMpAppDir(context); + long ts = System.currentTimeMillis(); + + File mpappDb = new File(appPath + "data/App.db"); + long modifiedTimeOfDb = 0; + if (mpappDb.exists()) { + modifiedTimeOfDb = mpappDb.lastModified(); + } + if ((ts - modifiedTimeOfDb) > 12 * 1000) { + // greater than 12 seconds + // logger.warning("Start MpAPP as it is NOT running"); + MicroPhotoContext.restartMpApp(context); + } + } catch (Exception ex) { + + } + } } \ No newline at end of file