diff --git a/app/src/main/cpp/PhoneDevice.cpp b/app/src/main/cpp/PhoneDevice.cpp index c42cd660..70c31522 100644 --- a/app/src/main/cpp/PhoneDevice.cpp +++ b/app/src/main/cpp/PhoneDevice.cpp @@ -175,10 +175,9 @@ CPhoneDevice::CPhoneDevice(JavaVM* vm, jobject service, const std::string& appPa m_javaService = env->NewGlobalRef(service); jclass classService = env->GetObjectClass(m_javaService); - mRegisterTimerMid = env->GetMethodID(classService, "registerTimer", "(JIJ)Z"); mRegisterHeartbeatMid = env->GetMethodID(classService, "registerHeartbeatTimer", "(I)V"); - mUnregisterTimerMid = env->GetMethodID(classService, "unregisterTimer", "(J)Z"); mUpdateTimeMid = env->GetMethodID(classService, "updateTime", "(J)Z"); + mUpdateCaptureScheduleMid = env->GetMethodID(classService, "updateCaptureSchedule", "(JJ)Z"); mStartRecordingMid = env->GetMethodID(classService, "startRecording", "(IJIIII)V"); mRequestWakelockMid = env->GetMethodID(classService, "requestWakelock", "(Ljava/lang/String;J)V"); @@ -212,6 +211,13 @@ CPhoneDevice::CPhoneDevice(JavaVM* vm, jobject service, const std::string& appPa CPhoneDevice::~CPhoneDevice() { + for (auto it = mTimers.begin(); it != mTimers.end(); ++it) + { + timer_delete((timer_t)it->first); + delete it->second; + } + mTimers.clear(); + JNIEnv* env = NULL; bool didAttachThread = false; bool res = GetJniEnv(m_vm, &env, didAttachThread); @@ -292,7 +298,24 @@ bool CPhoneDevice::UpdateTime(time_t ts) bool CPhoneDevice::UpdateSchedules() { - return true; + JNIEnv* env = NULL; + jboolean ret = JNI_FALSE; + bool didAttachThread = false; + bool res = GetJniEnv(m_vm, &env, didAttachThread); + if (!res) + { + ALOGE("Failed to get JNI Env"); + } + time_t ts = time(NULL); + time_t zeroPoint = GetTimeOfZeroPoint(ts); + ret = env->CallBooleanMethod(m_javaService, mUpdateCaptureScheduleMid, zeroPoint, ts - zeroPoint); + if (didAttachThread) + { + m_vm->DetachCurrentThread(); + } + + return (ret == JNI_TRUE); + } bool CPhoneDevice::QuerySystemProperties(std::map& properties) diff --git a/app/src/main/cpp/PhoneDevice.h b/app/src/main/cpp/PhoneDevice.h index 41504c4b..9ea0a387 100644 --- a/app/src/main/cpp/PhoneDevice.h +++ b/app/src/main/cpp/PhoneDevice.h @@ -250,10 +250,9 @@ protected: jclass m_sysApiClass; std::string m_appPath; - jmethodID mRegisterTimerMid; jmethodID mRegisterHeartbeatMid; - jmethodID mUnregisterTimerMid; - jmethodID mUpdateTimeMid; + jmethodID mUpdateCaptureScheduleMid; + jmethodID mUpdateTimeMid; jmethodID mStartRecordingMid; jmethodID mRequestWakelockMid; diff --git a/app/src/main/java/com/xypower/mpapp/AppMaster.java b/app/src/main/java/com/xypower/mpapp/AppMaster.java deleted file mode 100644 index 2d741863..00000000 --- a/app/src/main/java/com/xypower/mpapp/AppMaster.java +++ /dev/null @@ -1,223 +0,0 @@ -package com.xypower.mpapp; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.List; - -import android.content.Context; -import android.os.PowerManager; -import android.text.TextUtils; -import android.util.Pair; - -import com.dev.devapi.api.SysApi; -import com.xypower.common.FileDownloader; -import com.xypower.common.MicroPhotoContext; - -import org.json.JSONObject; - -public class AppMaster { - - private MicroPhotoService mService; - private String mCmdid; - private PowerManager.WakeLock mWakelock; - - private final static String MASTER_URL = "http://180.166.218.222:40101/?cmdid="; - - public AppMaster(MicroPhotoService service, String cmdid) { - - PowerManager powerManager = (PowerManager) service.getSystemService(Context.POWER_SERVICE); - mWakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.xinyingpower.microphoto:Upgrader"); - - mService = service; - mCmdid = cmdid; - } - - @Override - protected void finalize() { - try { - if (mWakelock != null) { - mWakelock.setReferenceCounted(false); - mWakelock.release(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - mWakelock = null; - } - mService = null; - } - - public void start() { - - new Thread(new Runnable() { - @Override - public void run() { - HttpURLConnection httpURLConnection = null; - InputStream inputStream = null; - - try { - String url = MASTER_URL + URLEncoder.encode(mCmdid, "UTF-8"); - URL mUrl = new URL(url); - httpURLConnection = (HttpURLConnection) mUrl.openConnection(); - httpURLConnection.setConnectTimeout(15000); - httpURLConnection.setReadTimeout(15000); - httpURLConnection.setRequestMethod("POST"); - // httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); - httpURLConnection.setDoInput(true); - httpURLConnection.setDoOutput(true); - - List> postParams = new ArrayList<>(); - postParams.add(new Pair("id", mCmdid)); - // postParams(httpURLConnection.getOutputStream(), postParams); - buildParams(httpURLConnection.getOutputStream()); - httpURLConnection.connect(); - inputStream = httpURLConnection.getInputStream(); - - int responseCode = httpURLConnection.getResponseCode(); - - if (responseCode == HttpURLConnection.HTTP_OK) { - //在子线程中不能操作UI线程,通过handler在UI线程中进行操作 - // handler.sendEmptyMessage(0x00); - String response = convertStreamToString(inputStream); - process(response); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (AppMaster.this.mWakelock != null) { - try { - AppMaster.this.mWakelock.setReferenceCounted(false); - AppMaster.this.mWakelock.release(); - } catch (Exception e) { - e.printStackTrace(); - } - AppMaster.this.mWakelock = null; - } - } - - } - }).start(); - } - - private void process(String content) { - if (TextUtils.isEmpty(content)) { - return; - } - - try { - JSONObject jsonObject = new JSONObject(content); - int isUpgrade = jsonObject.optInt("isUpgrade", 0); - String url = jsonObject.optString("url", null); - - if (isUpgrade == 1 && !TextUtils.isEmpty(url)) { - upgradeApp(url); - } - } catch (Exception e) { - e.printStackTrace(); - } - - } - - private void upgradeApp(String url) { - - FileDownloader dl = new FileDownloader(); - File path = new File(MicroPhotoContext.buildAppDir(mService.getApplicationContext()), "packages"); - if (!path.exists()) { - path.mkdirs(); - } - - File file = new File(path, "app.apk"); - if (file.exists()) { - file.delete(); - } - String apkPath = file.getAbsolutePath(); - if (dl.download(url, apkPath)) { - Context context = mService.getApplicationContext(); - SysApi.installApk(context, apkPath, context.getPackageName(), true); - } - } - - private void buildParams(OutputStream output) { - BufferedWriter bufferedWriter = null; - try { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("id", mCmdid); - - bufferedWriter = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); - bufferedWriter.write(jsonObject.toString()); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (bufferedWriter != null) { - bufferedWriter.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static void postParams(OutputStream output, List> paramsList) { - - BufferedWriter bufferedWriter = null; - try { - StringBuilder stringBuilder = new StringBuilder(); - for (Pair pair : paramsList) { - if (!TextUtils.isEmpty(stringBuilder)) { - stringBuilder.append("&"); - } - stringBuilder.append(URLEncoder.encode(pair.first, "UTF-8")); - stringBuilder.append("="); - stringBuilder.append(URLEncoder.encode(pair.second, "UTF-8")); - bufferedWriter = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); - bufferedWriter.write(stringBuilder.toString()); - } - - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (bufferedWriter != null) { - bufferedWriter.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private String convertStreamToString(InputStream inputStream) { - BufferedReader bufferedReader = null; - StringBuffer stringBuffer = new StringBuffer(); - String line; - try { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - while ((line = bufferedReader.readLine()) != null) { - stringBuffer.append(line).append("\n"); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (bufferedReader != null) { - bufferedReader.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - return stringBuffer.toString(); - } - - -} diff --git a/app/src/main/java/com/xypower/mpapp/ChannelActivity.java b/app/src/main/java/com/xypower/mpapp/ChannelActivity.java index bdd79aed..3b0defc3 100644 --- a/app/src/main/java/com/xypower/mpapp/ChannelActivity.java +++ b/app/src/main/java/com/xypower/mpapp/ChannelActivity.java @@ -11,6 +11,7 @@ import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; +import com.xypower.common.JSONUtils; import com.xypower.common.MicroPhotoContext; import com.xypower.mpapp.databinding.ActivityChannelBinding; @@ -118,23 +119,13 @@ public class ChannelActivity extends AppCompatActivity { String appPath = MicroPhotoContext.buildAppDir(getApplicationContext()); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; try { - File channelFile = new File(appPath + "data/channels/" + String.valueOf(channel) + ".json"); - StringBuilder stringBuilder = null; - if (channelFile.exists()) { - - inputStreamReader = new InputStreamReader(new FileInputStream(channelFile), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - stringBuilder = new StringBuilder(); - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } + String path = appPath + "data/channels/" + String.valueOf(channel) + ".json"; - JSONObject jsonObject = stringBuilder != null ? (new JSONObject(stringBuilder.toString())) : new JSONObject(); + JSONObject jsonObject = JSONUtils.loadJson(path); + if (jsonObject == null) { + jsonObject = new JSONObject(); + } binding.btnUsbCamera.setChecked(jsonObject.optInt("usbCamera", 0) == 1); binding.btnAutoExplosure.setChecked(jsonObject.optInt("autoExposure", 1) == 1); binding.btnAutoFocus.setChecked(jsonObject.optInt("autoFocus", 1) == 1); @@ -177,26 +168,8 @@ public class ChannelActivity extends AppCompatActivity { binding.osdRightBottom.setText(""); binding.osdLeftBottom.setText(""); } - - } catch (UnsupportedEncodingException e) { + } catch (Exception e) { e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { - try { - inputStreamReader.close(); - } catch (Exception ex) { - } - } } } @@ -204,45 +177,10 @@ public class ChannelActivity extends AppCompatActivity { JSONObject jsonObject = null; String appPath = MicroPhotoContext.buildAppDir(this.getApplicationContext()); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - File dataPath = new File(appPath + "data/channels/"); - File file = new File(dataPath, String.valueOf(channel) + ".json"); - - try { - StringBuilder stringBuilder = new StringBuilder(); + String dataPath = appPath + "data/channels/"; + String filePath = dataPath + String.valueOf(channel) + ".json"; - if (file.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - - jsonObject =stringBuilder.length() > 0 ? (new JSONObject(stringBuilder.toString())) : (new JSONObject()); - } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (JSONException e) { - e.printStackTrace(); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { - try { - inputStreamReader.close(); - } catch (Exception ex) { - } - } - } + jsonObject = JSONUtils.loadJson(filePath); if (jsonObject == null) { jsonObject = new JSONObject(); @@ -291,26 +229,15 @@ public class ChannelActivity extends AppCompatActivity { } catch (JSONException ex) { } - OutputStreamWriter outputStreamWriter = null; + try { - if (!dataPath.exists()) { - dataPath.mkdirs(); + File dataPathFile = new File(dataPath); + if (!dataPathFile.exists()) { + dataPathFile.mkdirs(); } - - outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); - outputStreamWriter.write(jsonObject.toString()); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { + JSONUtils.saveJson(filePath, jsonObject); + } catch (Exception e) { e.printStackTrace(); - } finally { - if (outputStreamWriter != null) { - try { - outputStreamWriter.close(); - } catch (Exception ex) { - } - - } } } } \ No newline at end of file diff --git a/app/src/main/java/com/xypower/mpapp/MainActivity.java b/app/src/main/java/com/xypower/mpapp/MainActivity.java index 42594c9a..f94e7bb6 100644 --- a/app/src/main/java/com/xypower/mpapp/MainActivity.java +++ b/app/src/main/java/com/xypower/mpapp/MainActivity.java @@ -263,50 +263,50 @@ public class MainActivity extends AppCompatActivity { this.binding.btnTakePhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 1, 255, true); + takePhoto(1, 255, true); } }); this.binding.btnTakePhoto2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 2, 255, true); + takePhoto(2, 255, true); } }); this.binding.btnTakePhoto3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 3, 255, true); + takePhoto(3, 255, true); } }); this.binding.btnTakePhoto4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 4, 255, true); + takePhoto(4, 255, true); } }); this.binding.takeVideoBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 1, 255, false); + takePhoto(1, 255, false); } }); this.binding.takeVideoBtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 2, 255, false); + takePhoto(2, 255, false); } }); this.binding.takeVideoBtn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 3, 255, false); + takePhoto(3, 255, false); } }); this.binding.takeVideoBtn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - MicroPhotoService.takePhoto(view.getContext().getApplicationContext(), 4, 255, false); + takePhoto(4, 255, false); } }); @@ -514,6 +514,10 @@ public class MainActivity extends AppCompatActivity { } } + private void takePhoto(int channel, int preset, boolean photoOrVideo) { + MicroPhotoService.takePhoto(this, channel, preset, photoOrVideo); + } + @Override protected void onStart() { // call the superclass method first diff --git a/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java b/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java index 760dc08d..7e56a803 100644 --- a/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java +++ b/app/src/main/java/com/xypower/mpapp/MicroPhotoService.java @@ -1,6 +1,5 @@ package com.xypower.mpapp; -import static java.lang.System.in; import static java.lang.System.loadLibrary; import android.app.AlarmManager; @@ -40,10 +39,8 @@ import android.os.PowerManager; import android.os.RemoteException; import android.os.SystemClock; -import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.core.content.FileProvider; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.telephony.SignalStrength; import android.telephony.SubscriptionManager; @@ -106,6 +103,7 @@ public class MicroPhotoService extends Service { private static final String EXTRA_PARAM_PHOTO_OR_VIDEO = "PhotoOrVideo"; private static final String EXTRA_PARAM_SCHEDULES = "Schedules"; 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"; @@ -357,7 +355,7 @@ public class MicroPhotoService extends Service { long startTime = date.getTime() / 1000; long baseTime = nowTs - startTime; - mService.registerCaptureSchedule(startTime, baseTime); + mService.updateCaptureSchedule(startTime, baseTime); } else if (TextUtils.equals(ACTION_HEARTBEAT_MANUALLY, action)) { Log.i(TAG, "HB Timer Fired ACTION=" + action); mService.sendHeartbeat(mService.mNativeHandle); @@ -412,7 +410,7 @@ public class MicroPhotoService extends Service { // alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeout, pendingIntent); } - private static void registerPhotoTimer(Context context, int channel, int preset, long ts, long timeout, List schedules) { + private static void registerPhotoTimer(Context context, int channel, int preset, long scheduleTime, long takingTime, long timeout, List schedules) { // 创建延迟意图 Intent alarmIntent = new Intent(); @@ -426,7 +424,8 @@ public class MicroPhotoService extends Service { channelStr += "CH=" + ((val & 0XFF0000) >> 16) + "-PR=" + ((val & 0XFF00) >> 8) + " "; } - alarmIntent.putExtra(EXTRA_PARAM_TIME, ts); + alarmIntent.putExtra(EXTRA_PARAM_TIME, scheduleTime); + alarmIntent.putExtra(EXTRA_PARAM_TAKING_TIME, takingTime); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); @@ -441,12 +440,15 @@ public class MicroPhotoService extends Service { } private void registerPhotoTimer(int channel, int preset, long ts, long timeout, List schedules) { - registerPhotoTimer(this.getApplicationContext(), channel, preset, ts, timeout, schedules); + registerPhotoTimer(this, channel, preset, ts, ts, timeout, schedules); } public void startRecording(int cameraId, long videoId, int duration, int width, int height, int quality) { Context context = getApplicationContext(); Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.xypower.mvapp"); + if (intent == null) { + return; + } intent.putExtra("cameraId", cameraId); intent.putExtra("videoId", videoId); intent.putExtra("duration", duration); @@ -458,7 +460,7 @@ public class MicroPhotoService extends Service { context.startActivity(intent); } - private boolean registerCaptureSchedule(long timeOfZeroPoint, long secondsOfToday) { + protected boolean updateCaptureSchedule(long timeOfZeroPoint, long secondsOfToday) { long[] photoTimeData = getPhotoTimeData(mNativeHandle); if (photoTimeData == null) { @@ -485,6 +487,7 @@ public class MicroPhotoService extends Service { } if ((ts - secondsOfToday) > maxDuration) { + day = 2; // For break two loops break; } @@ -497,6 +500,7 @@ public class MicroPhotoService extends Service { Log.i(TAG, "PhotoTimer Reg: CH=" + channel + " PR=" + preset); } else if (ts > currentTs) { + day = 2; // For break two loops break; } else { @@ -536,7 +540,7 @@ public class MicroPhotoService extends Service { schedules.add(Long.valueOf(val)); - registerPhotoTimer(context, channel, preset, 0, 0, schedules); + registerPhotoTimer(context, channel, preset, 0, System.currentTimeMillis() / 1000, 100, schedules); } public static void sendHeartbeat(Context context) { @@ -691,7 +695,7 @@ public class MicroPhotoService extends Service { long startTime = date.getTime() / 1000; long baseTime = nowTs - startTime; - service.registerCaptureSchedule(startTime, baseTime); + service.updateCaptureSchedule(startTime, baseTime); } } }; diff --git a/common/src/main/java/com/xypower/common/JSONUtils.java b/common/src/main/java/com/xypower/common/JSONUtils.java index 302258b2..27e8fe16 100644 --- a/common/src/main/java/com/xypower/common/JSONUtils.java +++ b/common/src/main/java/com/xypower/common/JSONUtils.java @@ -21,13 +21,15 @@ public class JSONUtils { public static JSONObject loadJson(String path) { JSONObject jsonObject = null; + FileInputStream fis = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = null; try { File appCfgFile = new File(path); if (appCfgFile.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(appCfgFile), "UTF-8"); + fis = new FileInputStream(appCfgFile); + inputStreamReader = new InputStreamReader(fis, "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String line; stringBuilder = new StringBuilder(); @@ -50,12 +52,21 @@ public class JSONUtils { try { bufferedReader.close(); } catch (Exception ex) { + ex.printStackTrace(); } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (fis != null) { + try { + fis.close(); + } catch (Exception ex) { + ex.printStackTrace(); } } } @@ -65,9 +76,11 @@ public class JSONUtils { public static boolean saveJson(String path, JSONObject jsonObject) { + FileOutputStream fos = null; OutputStreamWriter outputStreamWriter = null; try { - outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8"); + fos = new FileOutputStream(new File(path)); + outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); outputStreamWriter.write(jsonObject.toString()); return true; } catch (UnsupportedEncodingException e) { @@ -82,6 +95,13 @@ public class JSONUtils { ex.printStackTrace(); } } + if (fos != null) { + try { + fos.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } return false; diff --git a/common/src/main/java/com/xypower/common/MicroPhotoContext.java b/common/src/main/java/com/xypower/common/MicroPhotoContext.java index e6eb42b0..0997e004 100644 --- a/common/src/main/java/com/xypower/common/MicroPhotoContext.java +++ b/common/src/main/java/com/xypower/common/MicroPhotoContext.java @@ -4,6 +4,7 @@ import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; +import android.text.TextUtils; import org.json.JSONException; import org.json.JSONObject; @@ -43,6 +44,54 @@ public class MicroPhotoContext { public int heartbeatDuration; } + public static String readTextFile(String path) { + FileInputStream fis = null; + InputStreamReader inputStreamReader = null; + BufferedReader bufferedReader = null; + StringBuilder stringBuilder = null; + try { + File appCfgFile = new File(path); + if (appCfgFile.exists()) { + fis = new FileInputStream(appCfgFile); + inputStreamReader = new InputStreamReader(fis, "UTF-8"); + bufferedReader = new BufferedReader(inputStreamReader); + stringBuilder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + stringBuilder.append(line); + } + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (inputStreamReader != null) { + try { + inputStreamReader.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + if (fis != null) { + try { + fis.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + return stringBuilder == null ? null : stringBuilder.toString(); + } + public static String buildAppDir(Context contxt) { String path = Environment.getExternalStorageDirectory().getAbsolutePath(); @@ -80,22 +129,10 @@ public class MicroPhotoContext { String appPath = buildAppDir(context); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - StringBuilder stringBuilder = null; try { - File appCfgFile = new File(appPath + "data/App.json"); - if (appCfgFile.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(appCfgFile), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - stringBuilder = new StringBuilder(); - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } + String content = readTextFile(appPath + "data/App.json"); - JSONObject jsonObject = stringBuilder == null ? new JSONObject() : new JSONObject(stringBuilder.toString()); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); appConfig.cmdid = jsonObject.optString("CMDID", ""); appConfig.server = jsonObject.optString("Server", ""); appConfig.port = jsonObject.optInt("Port", 0); @@ -108,27 +145,9 @@ public class MicroPhotoContext { if (appConfig.protocol == 0) { appConfig.protocol = DEFAULT_PROTOCOL; } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { - try { - inputStreamReader.close(); - } catch (Exception ex) { - } - } } - return appConfig; } @@ -138,22 +157,10 @@ public class MicroPhotoContext { String appPath = buildMpAppDir(context); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - StringBuilder stringBuilder = null; try { - File appCfgFile = new File(appPath + "data/App.json"); - if (appCfgFile.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(appCfgFile), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - stringBuilder = new StringBuilder(); - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } + String content = readTextFile(appPath + "data/App.json"); - JSONObject jsonObject = stringBuilder == null ? new JSONObject() : new JSONObject(stringBuilder.toString()); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); appConfig.cmdid = jsonObject.optString("CMDID", ""); appConfig.server = jsonObject.optString("Server", ""); appConfig.port = jsonObject.optInt("Port", 0); @@ -166,25 +173,8 @@ public class MicroPhotoContext { if (appConfig.protocol == 0) { appConfig.protocol = DEFAULT_PROTOCOL; } - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { - try { - inputStreamReader.close(); - } catch (Exception ex) { - } - } } return appConfig; @@ -193,8 +183,7 @@ public class MicroPhotoContext { public static void saveAppConfig(Context context, AppConfig appConfig) { String appPath = buildAppDir(context); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; + FileOutputStream fos = null; OutputStreamWriter outputStreamWriter = null; try { @@ -203,20 +192,9 @@ public class MicroPhotoContext { dataPath.mkdirs(); } - StringBuilder stringBuilder = new StringBuilder(); - File file = new File(dataPath, "App.json"); - if (file.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - - JSONObject jsonObject = stringBuilder.length() > 0 ? (new JSONObject(stringBuilder.toString())) : (new JSONObject()); + String content = readTextFile(appPath + "data/App.json"); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); jsonObject.put("CMDID", appConfig.cmdid); jsonObject.put("Server", appConfig.server); jsonObject.put("Port", appConfig.port); @@ -235,7 +213,8 @@ public class MicroPhotoContext { jsonObject.remove("packetSize"); } - outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(appPath + "data/App.json")), "UTF-8"); + fos = new FileOutputStream(new File(appPath + "data/App.json")); + outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); outputStreamWriter.write(jsonObject.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); @@ -244,24 +223,17 @@ public class MicroPhotoContext { } catch (JSONException e) { e.printStackTrace(); } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { + if (outputStreamWriter != null) { try { - inputStreamReader.close(); + outputStreamWriter.close(); } catch (Exception ex) { } } - if (outputStreamWriter != null) { + if (fos != null) { try { - outputStreamWriter.close(); + fos.close(); } catch (Exception ex) { } - } } } @@ -269,48 +241,18 @@ public class MicroPhotoContext { public static MasterConfig getMasterConfig(Context context) { MasterConfig masterConfig = new MasterConfig(); - String appPath = buildAppDir(context); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - StringBuilder stringBuilder = null; try { - File appCfgFile = new File(appPath + "data/Master.json"); - if (appCfgFile.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(appCfgFile), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - stringBuilder = new StringBuilder(); - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } + String content = readTextFile(appPath + "data/Master.json"); - JSONObject jsonObject = stringBuilder == null ? new JSONObject() : new JSONObject(stringBuilder.toString()); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); masterConfig.url = jsonObject.optString("url", ""); masterConfig.mntnMode = jsonObject.optInt("mntnMode", 0); masterConfig.quickHbMode = jsonObject.optInt("quickHbMode", 0); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { - try { - inputStreamReader.close(); - } catch (Exception ex) { - } - } } return masterConfig; @@ -319,8 +261,7 @@ public class MicroPhotoContext { public static void saveMasterConfig(Context context, MasterConfig masterConfig) { String appPath = buildAppDir(context); - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; + FileOutputStream fos = null; OutputStreamWriter outputStreamWriter = null; try { @@ -329,51 +270,32 @@ public class MicroPhotoContext { dataPath.mkdirs(); } - StringBuilder stringBuilder = new StringBuilder(); - File file = new File(dataPath, "Master.json"); - if (file.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - - JSONObject jsonObject = stringBuilder.length() > 0 ? (new JSONObject(stringBuilder.toString())) : (new JSONObject()); + String content = readTextFile(appPath + "data/Master.json"); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); jsonObject.put("url", masterConfig.url); jsonObject.put("Server", masterConfig.mntnMode); jsonObject.put("Port", masterConfig.quickHbMode); - outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(appPath + "data/App.json")), "UTF-8"); + fos = new FileOutputStream(new File(appPath + "data/App.json")); + outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); outputStreamWriter.write(jsonObject.toString()); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { + if (outputStreamWriter != null) { try { - inputStreamReader.close(); + outputStreamWriter.close(); } catch (Exception ex) { } } - if (outputStreamWriter != null) { + if (fos != null) { try { - outputStreamWriter.close(); + fos.close(); } catch (Exception ex) { } - } } } @@ -406,8 +328,7 @@ public class MicroPhotoContext { public static void saveMpAppConfig(String path, AppConfig appConfig) { - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; + FileOutputStream fos = null; OutputStreamWriter outputStreamWriter = null; try { @@ -416,20 +337,9 @@ public class MicroPhotoContext { dataPath.mkdirs(); } - StringBuilder stringBuilder = new StringBuilder(); - File file = new File(dataPath, "App.json"); - if (file.exists()) { - inputStreamReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); - bufferedReader = new BufferedReader(inputStreamReader); - String line; - - while ((line = bufferedReader.readLine()) != null) { - stringBuilder.append(line); - } - } - - JSONObject jsonObject = stringBuilder.length() > 0 ? (new JSONObject(stringBuilder.toString())) : (new JSONObject()); + String content = readTextFile(path + "data/App.json"); + JSONObject jsonObject = TextUtils.isEmpty(content) ? new JSONObject() : new JSONObject(content); jsonObject.put("CMDID", appConfig.cmdid); jsonObject.put("Server", appConfig.server); jsonObject.put("Port", appConfig.port); @@ -448,33 +358,25 @@ public class MicroPhotoContext { jsonObject.remove("packetSize"); } - outputStreamWriter = new OutputStreamWriter(new FileOutputStream(new File(path + "data/App.json")), "UTF-8"); + fos = new FileOutputStream(new File(path + "data/App.json")); + outputStreamWriter = new OutputStreamWriter(fos, "UTF-8"); outputStreamWriter.write(jsonObject.toString()); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (Exception ex) { - } - } - if (inputStreamReader != null) { + if (outputStreamWriter != null) { try { - inputStreamReader.close(); + outputStreamWriter.close(); } catch (Exception ex) { } } - if (outputStreamWriter != null) { + if (fos != null) { try { - outputStreamWriter.close(); + fos.close(); } catch (Exception ex) { } - } } } diff --git a/mpmaster/src/main/java/com/xypower/mpmaster/AppMaster.java b/mpmaster/src/main/java/com/xypower/mpmaster/AppMaster.java index c4ab9e8a..cff92c7f 100644 --- a/mpmaster/src/main/java/com/xypower/mpmaster/AppMaster.java +++ b/mpmaster/src/main/java/com/xypower/mpmaster/AppMaster.java @@ -445,13 +445,15 @@ public class AppMaster { private void buildParams(OutputStream output) { BufferedWriter bufferedWriter = null; + OutputStreamWriter outputStreamWriter = null; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", mCmdid); jsonObject.put("i1Version", mService.getMpAppVersion()); jsonObject.put("maintainVersion", mService.getMasterAppVersion()); - bufferedWriter = new BufferedWriter(new OutputStreamWriter(output, "UTF-8")); + outputStreamWriter = new OutputStreamWriter(output, "UTF-8"); + bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write(jsonObject.toString()); } catch (Exception e) { e.printStackTrace(); @@ -463,6 +465,13 @@ public class AppMaster { } catch (Exception e) { e.printStackTrace(); } + try { + if (outputStreamWriter != null) { + outputStreamWriter.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } } }