(lruEntries.values())) {
+ for (Entry entry : new ArrayList<>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
@@ -706,7 +703,7 @@ final class DiskLruCache implements Closeable {
public final class Snapshot implements Closeable {
private final String key;
private final long sequenceNumber;
- private File[] files;
+ private final File[] files;
private final InputStream[] ins;
private final long[] lengths;
@@ -756,7 +753,7 @@ final class DiskLruCache implements Closeable {
private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
@Override
- public void write(int b) throws IOException {
+ public void write(int b) {
// Eat all writes silently. Nom nom.
}
};
@@ -777,7 +774,7 @@ final class DiskLruCache implements Closeable {
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
- public InputStream newInputStream(int index) throws IOException {
+ public InputStream newInputStream(int index) {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
@@ -809,7 +806,7 @@ final class DiskLruCache implements Closeable {
* {@link #commit} is called. The returned output stream does not throw
* IOExceptions.
*/
- public OutputStream newOutputStream(int index) throws IOException {
+ public OutputStream newOutputStream(int index) {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
@@ -936,7 +933,7 @@ final class DiskLruCache implements Closeable {
this.lengths = new long[valueCount];
}
- public String getLengths() throws IOException {
+ public String getLengths() {
StringBuilder result = new StringBuilder();
for (long size : lengths) {
result.append(' ').append(size);
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java
index 35c53f36f2..ead1ad4ea4 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/glide/utils/DiskLruCacheManager.java
@@ -25,10 +25,9 @@ public class DiskLruCacheManager {
private static volatile DiskLruCacheManager instance;
private static final byte[] obj = new byte[0];
- private final int MAX_CACHE_SIZE = 64 * 1024 * 1024;
-
private DiskLruCacheManager(Context context) {
try {
+ int MAX_CACHE_SIZE = 64 * 1024 * 1024;
diskLruCache = DiskLruCache.open(context.getCacheDir(), 1, 1,
MAX_CACHE_SIZE, Integer.MAX_VALUE);
} catch (Exception e) {
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java
index e67902356f..d8ce1700e3 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/mogo/logger/LoggerPrinter.java
@@ -107,6 +107,8 @@ final class LoggerPrinter implements Printer {
}
}
+ private static final String xmlHtml = "http://xml.apache.org/xslt";
+
public void xml( String tag, String xml) {
if ( TextUtils.isEmpty(xml)) {
this.d(tag, "Empty/Null xml content");
@@ -116,7 +118,7 @@ final class LoggerPrinter implements Printer {
StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+ transformer.setOutputProperty("{" + xmlHtml + "}indent-amount", "2");
transformer.transform(e, xmlOutput);
this.d(tag, xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
} catch ( TransformerException var5) {
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java
deleted file mode 100644
index 9199638ded..0000000000
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/AssetsUtils.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.mogo.eagle.core.utilcode.util;
-
-import android.content.Context;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.io.BufferedInputStream;
-import java.io.InputStream;
-
-/**
- * @author congtaowang
- * @since 2019-12-12
- *
- * 读取asset文件
- */
-public class AssetsUtils {
-
- private static final String TAG = "amap.AssetsUtils";
-
- public static byte[] read( Context context, String fileName ) {
- if ( context == null || TextUtils.isEmpty( fileName ) ) {
- return null;
- }
- byte[] buffer = null;
- try {
- InputStream is = context.getAssets().open( fileName );
- BufferedInputStream bis = new BufferedInputStream( is );
- buffer = new byte[is.available()];
- bis.read( buffer );
- bis.close();
- is.close();
- Log.d( TAG, "read assets success: " + fileName + " size=" + buffer.length );
- } catch ( Exception e ) {
- e.printStackTrace();
- }
- return buffer;
- }
-}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java
index e4fbc80f0d..aa4f403338 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/BitmapHelper.java
@@ -53,9 +53,6 @@ public class BitmapHelper {
/**
* 根据原图添加圆角
- *
- * @param source
- * @return
*/
public static Bitmap createRoundCornerImage( Bitmap source, float corner ) {
final Paint paint = new Paint();
@@ -75,7 +72,7 @@ public class BitmapHelper {
}
ByteArrayOutputStream bos = null;
- byte[] result = null;
+ byte[] result;
try {
bos = new ByteArrayOutputStream();
@@ -150,7 +147,7 @@ public class BitmapHelper {
}
listener.onBeforeCompress();
ByteArrayOutputStream bos = null;
- Bitmap target = null;
+ Bitmap target;
try {
bos = new ByteArrayOutputStream();
@@ -164,15 +161,11 @@ public class BitmapHelper {
byte[] result = bos.toByteArray();
target = bytesToBitmap( result );
- if ( listener != null ) {
- listener.onCompressSuccess( result );
- }
+ listener.onCompressSuccess( result );
} catch ( Exception e ) {
e.printStackTrace();
target = null;
- if ( listener != null ) {
- listener.onCompressFailed( "压缩失败" );
- }
+ listener.onCompressFailed( "压缩失败" );
} finally {
IOUtils.closeSilently( bos );
}
@@ -203,7 +196,6 @@ public class BitmapHelper {
target = bytesToBitmap( result );
} catch ( Exception e ) {
e.printStackTrace();
- target = null;
} finally {
IOUtils.closeSilently( bos );
}
@@ -630,26 +622,19 @@ public class BitmapHelper {
*/
public static Bitmap getVideoThumbnail( String filePath ) {
Bitmap b = null;
- MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+ MediaMetadataRetriever retriever = null;
try {
retriever = new MediaMetadataRetriever();
- if (Build.VERSION.SDK_INT >= 14)
- retriever.setDataSource(filePath, new HashMap());
- else
- retriever.setDataSource(filePath);
- // mediaMetadataRetriever.setDataSource(videoPath);
+ retriever.setDataSource(filePath, new HashMap<>());
b = retriever.getFrameAtTime();
- } catch ( IllegalArgumentException e ) {
- e.printStackTrace();
} catch ( RuntimeException e ) {
e.printStackTrace();
-
} finally {
try {
- retriever.release();
- } catch ( RuntimeException e ) {
- e.printStackTrace();
- } catch (IOException e) {
+ if(retriever != null){
+ retriever.release();
+ }
+ } catch ( RuntimeException | IOException e ) {
e.printStackTrace();
}
}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java
index 8bfe7fe99e..06a457b844 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/DeviceIdUtils.java
@@ -39,11 +39,7 @@ public final class DeviceIdUtils {
if (TextUtils.isEmpty(deviceId)) {
deviceId = getDeviceIdInternal(appContext);
if (TextUtils.isEmpty(deviceId)) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
- deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
- }
- } else {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
}
if (TextUtils.isEmpty(deviceId)) {
@@ -65,10 +61,8 @@ public final class DeviceIdUtils {
private static String getDeviceIdInternal(Context context) {
String id = "";
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
- return id;
- }
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
+ return id;
}
TelephonyManager telephonymanager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
@@ -100,13 +94,7 @@ public final class DeviceIdUtils {
method.setAccessible(true);
}
serial = (String) method.invoke(new Build(), "ro.serialno");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
+ } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return serial;
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java
index 9efcc380dc..472a1e5a77 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/EncryptUtils.java
@@ -175,7 +175,7 @@ public final class EncryptUtils {
public static byte[] encryptMD5File(final File file) {
if (file == null) return null;
FileInputStream fis = null;
- DigestInputStream digestInputStream;
+ DigestInputStream digestInputStream = null;
try {
fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
@@ -191,6 +191,9 @@ public final class EncryptUtils {
return null;
} finally {
try {
+ if (digestInputStream != null) {
+ digestInputStream.close();
+ }
if (fis != null) {
fis.close();
}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java
index a9b26d8fce..3016a6c36a 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/FileUtils.java
@@ -1091,7 +1091,7 @@ public final class FileUtils {
is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int readChars;
- if (LINE_SEP.endsWith("\n")) {
+ if (LINE_SEP != null && LINE_SEP.endsWith("\n")) {
while ((readChars = is.read(buffer, 0, 1024)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (buffer[i] == '\n') ++count;
@@ -1442,13 +1442,8 @@ public final class FileUtils {
StatFs statFs = new StatFs(anyPathInFs);
long blockSize;
long totalSize;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- blockSize = statFs.getBlockSizeLong();
- totalSize = statFs.getBlockCountLong();
- } else {
- blockSize = statFs.getBlockSize();
- totalSize = statFs.getBlockCount();
- }
+ blockSize = statFs.getBlockSizeLong();
+ totalSize = statFs.getBlockCountLong();
return blockSize * totalSize;
}
@@ -1463,13 +1458,8 @@ public final class FileUtils {
StatFs statFs = new StatFs(anyPathInFs);
long blockSize;
long availableSize;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- blockSize = statFs.getBlockSizeLong();
- availableSize = statFs.getAvailableBlocksLong();
- } else {
- blockSize = statFs.getBlockSize();
- availableSize = statFs.getAvailableBlocks();
- }
+ blockSize = statFs.getBlockSizeLong();
+ availableSize = statFs.getAvailableBlocksLong();
return blockSize * availableSize;
}
@@ -1558,8 +1548,6 @@ public final class FileUtils {
byte[] bytes = new byte[in.available()];
int length = in.read(bytes);
base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
@@ -1709,53 +1697,49 @@ public final class FileUtils {
* @param listener
*/
public static void copy(final InputStream is, final String to, final FileCopyListener listener) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- Log.w("FileUtils", "======copy======");
+ new Thread(() -> {
+ Log.w("FileUtils", "======copy======");
- if (listener != null) {
- listener.onStart();
+ if (listener != null) {
+ listener.onStart();
+ }
+
+ try {
+
+ long fileSize = is.available();
+ long process = 0;
+
+ byte[] buff = new byte[1024];
+ int rc = 0;
+
+ File toFile = new File(to);
+ if (toFile.getParentFile() != null && !toFile.getParentFile().exists()) {
+ toFile.getParentFile().mkdirs();
}
- try {
+ FileOutputStream fos = new FileOutputStream(toFile);
- long fileSize = is.available();
- long process = 0;
-
- byte[] buff = new byte[1024];
- int rc = 0;
-
- File toFile = new File(to);
- if (!toFile.getParentFile().exists()) {
- toFile.getParentFile().mkdirs();
- }
-
- FileOutputStream fos = new FileOutputStream(toFile);
-
- while ((rc = is.read(buff, 0, 1024)) > 0) {
- process += rc;
- fos.write(buff, 0, rc);
- if (listener != null) {
- listener.onProcess(((int) (((float) process) * 100 / fileSize)));
- }
- }
-
- fos.flush();
- fos.close();
- is.close();
-
- } catch (Exception e) {
+ while ((rc = is.read(buff, 0, 1024)) > 0) {
+ process += rc;
+ fos.write(buff, 0, rc);
if (listener != null) {
- listener.onFail(e);
- return;
+ listener.onProcess(((int) (((float) process) * 100 / fileSize)));
}
}
+ fos.flush();
+ fos.close();
+ is.close();
+ } catch (Exception e) {
if (listener != null) {
- listener.onFinish(to);
+ listener.onFail(e);
+ return;
}
}
+
+ if (listener != null) {
+ listener.onFinish(to);
+ }
}).start();
}
@@ -1767,74 +1751,71 @@ public final class FileUtils {
* @param listener
*/
public static void copy(final String from, final String to, final FileCopyListener listener) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- File file = null;
- try {
- file = new File(from);
- } catch (Exception e) {
- if (listener != null) {
- listener.onFail(e);
- }
+ new Thread(() -> {
+ File file = null;
+ try {
+ file = new File(from);
+ } catch (Exception e) {
+ if (listener != null) {
+ listener.onFail(e);
+ }
+ return;
+ }
+ if (!file.isFile()) {
+ if (listener != null) {
+ listener.onFail(new Exception(String.format("%s is not a file", from)));
return;
}
- if (!file.isFile()) {
- if (listener != null) {
- listener.onFail(new Exception(String.format("%s is not a file", from)));
- return;
- }
- }
- if (!file.exists()) {
- if (listener != null) {
- listener.onFail(new FileNotFoundException(String.format("%s is not exists.", from)));
- return;
- }
- }
-
+ }
+ if (!file.exists()) {
if (listener != null) {
- listener.onStart();
+ listener.onFail(new FileNotFoundException(String.format("%s is not exists.", from)));
+ return;
+ }
+ }
+
+ if (listener != null) {
+ listener.onStart();
+ }
+
+ long fileSize = file.length();
+ long process = 0;
+
+ try {
+ FileInputStream fis = new FileInputStream(file);
+
+ byte[] buff = new byte[1024];
+ int rc = 0;
+
+ File toFile = new File(to);
+ if (!toFile.getParentFile().exists()) {
+ toFile.getParentFile().mkdirs();
}
- long fileSize = file.length();
- long process = 0;
+ FileOutputStream fos = new FileOutputStream(toFile);
- try {
- FileInputStream fis = new FileInputStream(file);
-
- byte[] buff = new byte[1024];
- int rc = 0;
-
- File toFile = new File(to);
- if (!toFile.getParentFile().exists()) {
- toFile.getParentFile().mkdirs();
- }
-
- FileOutputStream fos = new FileOutputStream(toFile);
-
- while ((rc = fis.read(buff, 0, 1024)) > 0) {
- process += rc;
- fos.write(buff, 0, rc);
- if (listener != null) {
- listener.onProcess(((int) (((float) process) * 100 / fileSize)));
- }
- }
-
- fos.flush();
- fos.close();
- fis.close();
-
- } catch (Exception e) {
+ while ((rc = fis.read(buff, 0, 1024)) > 0) {
+ process += rc;
+ fos.write(buff, 0, rc);
if (listener != null) {
- listener.onFail(e);
- return;
+ listener.onProcess(((int) (((float) process) * 100 / fileSize)));
}
}
+ fos.flush();
+ fos.close();
+ fis.close();
+
+ } catch (Exception e) {
if (listener != null) {
- listener.onFinish(to);
+ listener.onFail(e);
+ return;
}
}
+
+ if (listener != null) {
+ listener.onFinish(to);
+ }
}).start();
}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java
deleted file mode 100644
index 44b37542d8..0000000000
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/LogUtils.java
+++ /dev/null
@@ -1,1231 +0,0 @@
-package com.mogo.eagle.core.utilcode.util;
-
-import android.content.ClipData;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.graphics.Rect;
-import android.net.Uri;
-import android.os.Build;
-import android.os.Bundle;
-import android.util.Log;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Formatter;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-
-import androidx.annotation.IntDef;
-import androidx.annotation.IntRange;
-import androidx.annotation.RequiresApi;
-import androidx.collection.SimpleArrayMap;
-
-/**
- *
- * author: Blankj
- * blog : http://blankj.com
- * time : 2016/09/21
- * desc : utils about log
- *
- */
-public final class LogUtils {
-
- public static final int V = Log.VERBOSE;
- public static final int D = Log.DEBUG;
- public static final int I = Log.INFO;
- public static final int W = Log.WARN;
- public static final int E = Log.ERROR;
- public static final int A = Log.ASSERT;
-
- @IntDef({V, D, I, W, E, A})
- @Retention(RetentionPolicy.SOURCE)
- public @interface TYPE {
- }
-
- private static final char[] T = new char[]{'V', 'D', 'I', 'W', 'E', 'A'};
-
- private static final int FILE = 0x10;
- private static final int JSON = 0x20;
- private static final int XML = 0x30;
-
- private static final String FILE_SEP = System.getProperty("file.separator");
- private static final String LINE_SEP = System.getProperty("line.separator");
- private static final String TOP_CORNER = "┌";
- private static final String MIDDLE_CORNER = "├";
- private static final String LEFT_BORDER = "│ ";
- private static final String BOTTOM_CORNER = "└";
- private static final String SIDE_DIVIDER =
- "────────────────────────────────────────────────────────";
- private static final String MIDDLE_DIVIDER =
- "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄";
- private static final String TOP_BORDER = TOP_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
- private static final String MIDDLE_BORDER = MIDDLE_CORNER + MIDDLE_DIVIDER + MIDDLE_DIVIDER;
- private static final String BOTTOM_BORDER = BOTTOM_CORNER + SIDE_DIVIDER + SIDE_DIVIDER;
- private static final int MAX_LEN = 1100;// fit for Chinese character
- private static final String NOTHING = "log nothing";
- private static final String NULL = "null";
- private static final String ARGS = "args";
- private static final String PLACEHOLDER = " ";
- private static final Config CONFIG = new Config();
-
- private static SimpleDateFormat simpleDateFormat;
-
- private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
-
- private static final SimpleArrayMap I_FORMATTER_MAP = new SimpleArrayMap<>();
-
- private LogUtils() {
- throw new UnsupportedOperationException("u can't instantiate me...");
- }
-
- public static Config getConfig() {
- return CONFIG;
- }
-
- public static void v(final Object... contents) {
- log(V, CONFIG.getGlobalTag(), contents);
- }
-
- public static void vTag(final String tag, final Object... contents) {
- log(V, tag, contents);
- }
-
- public static void d(final Object... contents) {
- log(D, CONFIG.getGlobalTag(), contents);
- }
-
- public static void dTag(final String tag, final Object... contents) {
- log(D, tag, contents);
- }
-
- public static void i(final Object... contents) {
- log(I, CONFIG.getGlobalTag(), contents);
- }
-
- public static void iTag(final String tag, final Object... contents) {
- log(I, tag, contents);
- }
-
- public static void w(final Object... contents) {
- log(W, CONFIG.getGlobalTag(), contents);
- }
-
- public static void wTag(final String tag, final Object... contents) {
- log(W, tag, contents);
- }
-
- public static void e(final Object... contents) {
- log(E, CONFIG.getGlobalTag(), contents);
- }
-
- public static void eTag(final String tag, final Object... contents) {
- log(E, tag, contents);
- }
-
- public static void a(final Object... contents) {
- log(A, CONFIG.getGlobalTag(), contents);
- }
-
- public static void aTag(final String tag, final Object... contents) {
- log(A, tag, contents);
- }
-
- public static void file(final Object content) {
- log(FILE | D, CONFIG.getGlobalTag(), content);
- }
-
- public static void file(@TYPE final int type, final Object content) {
- log(FILE | type, CONFIG.getGlobalTag(), content);
- }
-
- public static void file(final String tag, final Object content) {
- log(FILE | D, tag, content);
- }
-
- public static void file(@TYPE final int type, final String tag, final Object content) {
- log(FILE | type, tag, content);
- }
-
- public static void json(final Object content) {
- log(JSON | D, CONFIG.getGlobalTag(), content);
- }
-
- public static void json(@TYPE final int type, final Object content) {
- log(JSON | type, CONFIG.getGlobalTag(), content);
- }
-
- public static void json(final String tag, final Object content) {
- log(JSON | D, tag, content);
- }
-
- public static void json(@TYPE final int type, final String tag, final Object content) {
- log(JSON | type, tag, content);
- }
-
- public static void xml(final String content) {
- log(XML | D, CONFIG.getGlobalTag(), content);
- }
-
- public static void xml(@TYPE final int type, final String content) {
- log(XML | type, CONFIG.getGlobalTag(), content);
- }
-
- public static void xml(final String tag, final String content) {
- log(XML | D, tag, content);
- }
-
- public static void xml(@TYPE final int type, final String tag, final String content) {
- log(XML | type, tag, content);
- }
-
- public static void log(final int type, final String tag, final Object... contents) {
- if (!CONFIG.isLogSwitch()) return;
- final int type_low = type & 0x0f, type_high = type & 0xf0;
- if (CONFIG.isLog2ConsoleSwitch() || CONFIG.isLog2FileSwitch() || type_high == FILE) {
- if (type_low < CONFIG.mConsoleFilter && type_low < CONFIG.mFileFilter) return;
- final TagHead tagHead = processTagAndHead(tag);
- final String body = processBody(type_high, contents);
- if (CONFIG.isLog2ConsoleSwitch() && type_high != FILE && type_low >= CONFIG.mConsoleFilter) {
- print2Console(type_low, tagHead.tag, tagHead.consoleHead, body);
- }
- if ((CONFIG.isLog2FileSwitch() || type_high == FILE) && type_low >= CONFIG.mFileFilter) {
- EXECUTOR.execute(new Runnable() {
- @Override
- public void run() {
- print2File(type_low, tagHead.tag, tagHead.fileHead + body);
- }
- });
- }
- }
- }
-
- public static String getCurrentLogFilePath() {
- return getCurrentLogFilePath(new Date());
- }
-
- public static List getLogFiles() {
- String dir = CONFIG.getDir();
- File logDir = new File(dir);
- if (!logDir.exists()) return new ArrayList<>();
- File[] files = logDir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return isMatchLogFileName(name);
- }
- });
- List list = new ArrayList<>();
- Collections.addAll(list, files);
- return list;
- }
-
- private static TagHead processTagAndHead(String tag) {
- if (!CONFIG.mTagIsSpace && !CONFIG.isLogHeadSwitch()) {
- tag = CONFIG.getGlobalTag();
- } else {
- final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
- final int stackIndex = 3 + CONFIG.getStackOffset();
- if (stackIndex >= stackTrace.length) {
- StackTraceElement targetElement = stackTrace[3];
- final String fileName = getFileName(targetElement);
- if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) {
- int index = fileName.indexOf('.');// Use proguard may not find '.'.
- tag = index == -1 ? fileName : fileName.substring(0, index);
- }
- return new TagHead(tag, null, ": ");
- }
- StackTraceElement targetElement = stackTrace[stackIndex];
- final String fileName = getFileName(targetElement);
- if (CONFIG.mTagIsSpace && UtilsBridge.isSpace(tag)) {
- int index = fileName.indexOf('.');// Use proguard may not find '.'.
- tag = index == -1 ? fileName : fileName.substring(0, index);
- }
- if (CONFIG.isLogHeadSwitch()) {
- String tName = Thread.currentThread().getName();
- final String head = new Formatter()
- .format("%s, %s.%s(%s:%d)",
- tName,
- targetElement.getClassName(),
- targetElement.getMethodName(),
- fileName,
- targetElement.getLineNumber())
- .toString();
- final String fileHead = " [" + head + "]: ";
- if (CONFIG.getStackDeep() <= 1) {
- return new TagHead(tag, new String[]{head}, fileHead);
- } else {
- final String[] consoleHead =
- new String[Math.min(
- CONFIG.getStackDeep(),
- stackTrace.length - stackIndex
- )];
- consoleHead[0] = head;
- int spaceLen = tName.length() + 2;
- String space = new Formatter().format("%" + spaceLen + "s", "").toString();
- for (int i = 1, len = consoleHead.length; i < len; ++i) {
- targetElement = stackTrace[i + stackIndex];
- consoleHead[i] = new Formatter()
- .format("%s%s.%s(%s:%d)",
- space,
- targetElement.getClassName(),
- targetElement.getMethodName(),
- getFileName(targetElement),
- targetElement.getLineNumber())
- .toString();
- }
- return new TagHead(tag, consoleHead, fileHead);
- }
- }
- }
- return new TagHead(tag, null, ": ");
- }
-
- private static String getFileName(final StackTraceElement targetElement) {
- String fileName = targetElement.getFileName();
- if (fileName != null) return fileName;
- // If name of file is null, should add
- // "-keepattributes SourceFile,LineNumberTable" in proguard file.
- String className = targetElement.getClassName();
- String[] classNameInfo = className.split("\\.");
- if (classNameInfo.length > 0) {
- className = classNameInfo[classNameInfo.length - 1];
- }
- int index = className.indexOf('$');
- if (index != -1) {
- className = className.substring(0, index);
- }
- return className + ".java";
- }
-
- private static String processBody(final int type, final Object... contents) {
- String body = NULL;
- if (contents != null) {
- if (contents.length == 1) {
- body = formatObject(type, contents[0]);
- } else {
- StringBuilder sb = new StringBuilder();
- for (int i = 0, len = contents.length; i < len; ++i) {
- Object content = contents[i];
- sb.append(ARGS)
- .append("[")
- .append(i)
- .append("]")
- .append(" = ")
- .append(formatObject(content))
- .append(LINE_SEP);
- }
- body = sb.toString();
- }
- }
- return body.length() == 0 ? NOTHING : body;
- }
-
- private static String formatObject(int type, Object object) {
- if (object == null) return NULL;
- if (type == JSON) return LogFormatter.object2String(object, JSON);
- if (type == XML) return LogFormatter.object2String(object, XML);
- return formatObject(object);
- }
-
- private static String formatObject(Object object) {
- if (object == null) return NULL;
- if (!I_FORMATTER_MAP.isEmpty()) {
- IFormatter iFormatter = I_FORMATTER_MAP.get(getClassFromObject(object));
- if (iFormatter != null) {
- //noinspection unchecked
- return iFormatter.format(object);
- }
- }
- return LogFormatter.object2String(object);
- }
-
- private static void print2Console(final int type,
- final String tag,
- final String[] head,
- final String msg) {
- if (CONFIG.isSingleTagSwitch()) {
- printSingleTagMsg(type, tag, processSingleTagMsg(type, tag, head, msg));
- } else {
- printBorder(type, tag, true);
- printHead(type, tag, head);
- printMsg(type, tag, msg);
- printBorder(type, tag, false);
- }
- }
-
- private static void printBorder(final int type, final String tag, boolean isTop) {
- if (CONFIG.isLogBorderSwitch()) {
- print2Console(type, tag, isTop ? TOP_BORDER : BOTTOM_BORDER);
- }
- }
-
- private static void printHead(final int type, final String tag, final String[] head) {
- if (head != null) {
- for (String aHead : head) {
- print2Console(type, tag, CONFIG.isLogBorderSwitch() ? LEFT_BORDER + aHead : aHead);
- }
- if (CONFIG.isLogBorderSwitch()) print2Console(type, tag, MIDDLE_BORDER);
- }
- }
-
- private static void printMsg(final int type, final String tag, final String msg) {
- int len = msg.length();
- int countOfSub = len / MAX_LEN;
- if (countOfSub > 0) {
- int index = 0;
- for (int i = 0; i < countOfSub; i++) {
- printSubMsg(type, tag, msg.substring(index, index + MAX_LEN));
- index += MAX_LEN;
- }
- if (index != len) {
- printSubMsg(type, tag, msg.substring(index, len));
- }
- } else {
- printSubMsg(type, tag, msg);
- }
- }
-
- private static void printSubMsg(final int type, final String tag, final String msg) {
- if (!CONFIG.isLogBorderSwitch()) {
- print2Console(type, tag, msg);
- return;
- }
- StringBuilder sb = new StringBuilder();
- String[] lines = msg.split(LINE_SEP);
- for (String line : lines) {
- print2Console(type, tag, LEFT_BORDER + line);
- }
- }
-
- private static String processSingleTagMsg(final int type,
- final String tag,
- final String[] head,
- final String msg) {
- StringBuilder sb = new StringBuilder();
- if (CONFIG.isLogBorderSwitch()) {
- sb.append(PLACEHOLDER).append(LINE_SEP);
- sb.append(TOP_BORDER).append(LINE_SEP);
- if (head != null) {
- for (String aHead : head) {
- sb.append(LEFT_BORDER).append(aHead).append(LINE_SEP);
- }
- sb.append(MIDDLE_BORDER).append(LINE_SEP);
- }
- for (String line : msg.split(LINE_SEP)) {
- sb.append(LEFT_BORDER).append(line).append(LINE_SEP);
- }
- sb.append(BOTTOM_BORDER);
- } else {
- if (head != null) {
- sb.append(PLACEHOLDER).append(LINE_SEP);
- for (String aHead : head) {
- sb.append(aHead).append(LINE_SEP);
- }
- }
- sb.append(msg);
- }
- return sb.toString();
- }
-
- private static void printSingleTagMsg(final int type, final String tag, final String msg) {
- int len = msg.length();
- int countOfSub = CONFIG.isLogBorderSwitch() ? (len - BOTTOM_BORDER.length()) / MAX_LEN : len / MAX_LEN;
- if (countOfSub > 0) {
- if (CONFIG.isLogBorderSwitch()) {
- print2Console(type, tag, msg.substring(0, MAX_LEN) + LINE_SEP + BOTTOM_BORDER);
- int index = MAX_LEN;
- for (int i = 1; i < countOfSub; i++) {
- print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
- + LEFT_BORDER + msg.substring(index, index + MAX_LEN)
- + LINE_SEP + BOTTOM_BORDER);
- index += MAX_LEN;
- }
- if (index != len - BOTTOM_BORDER.length()) {
- print2Console(type, tag, PLACEHOLDER + LINE_SEP + TOP_BORDER + LINE_SEP
- + LEFT_BORDER + msg.substring(index, len));
- }
- } else {
- print2Console(type, tag, msg.substring(0, MAX_LEN));
- int index = MAX_LEN;
- for (int i = 1; i < countOfSub; i++) {
- print2Console(type, tag,
- PLACEHOLDER + LINE_SEP + msg.substring(index, index + MAX_LEN));
- index += MAX_LEN;
- }
- if (index != len) {
- print2Console(type, tag, PLACEHOLDER + LINE_SEP + msg.substring(index, len));
- }
- }
- } else {
- print2Console(type, tag, msg);
- }
- }
-
- private static void print2Console(int type, String tag, String msg) {
- Log.println(type, tag, msg);
- if (CONFIG.mOnConsoleOutputListener != null) {
- CONFIG.mOnConsoleOutputListener.onConsoleOutput(type, tag, msg);
- }
- }
-
- private static void print2File(final int type, final String tag, final String msg) {
- Date d = new Date();
- String format = getSdf().format(d);
- String date = format.substring(0, 10);
- String currentLogFilePath = getCurrentLogFilePath(d);
- if (!createOrExistsFile(currentLogFilePath, date)) {
- Log.e("LogUtils", "create " + currentLogFilePath + " failed!");
- return;
- }
- String time = format.substring(11);
- final String content = time +
- T[type - V] +
- "/" +
- tag +
- msg +
- LINE_SEP;
- input2File(currentLogFilePath, content);
- }
-
- private static String getCurrentLogFilePath(Date d) {
- String format = getSdf().format(d);
- String date = format.substring(0, 10);
- return CONFIG.getDir() + CONFIG.getFilePrefix() + "_"
- + date + "_" +
- CONFIG.getProcessName() + CONFIG.getFileExtension();
- }
-
-
- private static SimpleDateFormat getSdf() {
- if (simpleDateFormat == null) {
- simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss.SSS ", Locale.getDefault());
- }
- return simpleDateFormat;
- }
-
- private static boolean createOrExistsFile(final String filePath, final String date) {
- File file = new File(filePath);
- if (file.exists()) return file.isFile();
- if (!UtilsBridge.createOrExistsDir(file.getParentFile())) return false;
- try {
- deleteDueLogs(filePath, date);
- boolean isCreate = file.createNewFile();
- if (isCreate) {
- printDeviceInfo(filePath, date);
- }
- return isCreate;
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
-
- private static void deleteDueLogs(final String filePath, final String date) {
- if (CONFIG.getSaveDays() <= 0) return;
- File file = new File(filePath);
- File parentFile = file.getParentFile();
- File[] files = parentFile.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return isMatchLogFileName(name);
- }
- });
- if (files == null || files.length <= 0) return;
- final SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd", Locale.getDefault());
- try {
- long dueMillis = sdf.parse(date).getTime() - CONFIG.getSaveDays() * 86400000L;
- for (final File aFile : files) {
- String name = aFile.getName();
- int l = name.length();
- String logDay = findDate(name);
- if (sdf.parse(logDay).getTime() <= dueMillis) {
- EXECUTOR.execute(new Runnable() {
- @Override
- public void run() {
- boolean delete = aFile.delete();
- if (!delete) {
- Log.e("LogUtils", "delete " + aFile + " failed!");
- }
- }
- });
- }
- }
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
-
- private static boolean isMatchLogFileName(String name) {
- return name.matches("^" + CONFIG.getFilePrefix() + "_[0-9]{4}_[0-9]{2}_[0-9]{2}_.*$");
- }
-
- private static String findDate(String str) {
- Pattern pattern = Pattern.compile("[0-9]{4}_[0-9]{2}_[0-9]{2}");
- Matcher matcher = pattern.matcher(str);
- if (matcher.find()) {
- return matcher.group();
- }
- return "";
- }
-
- private static void printDeviceInfo(final String filePath, final String date) {
- CONFIG.mFileHead.addFirst("Date of Log", date);
- input2File(filePath, CONFIG.mFileHead.toString());
- }
-
- private static void input2File(final String filePath, final String input) {
- if (CONFIG.mFileWriter == null) {
- UtilsBridge.writeFileFromString(filePath, input, true);
- } else {
- CONFIG.mFileWriter.write(filePath, input);
- }
- if (CONFIG.mOnFileOutputListener != null) {
- CONFIG.mOnFileOutputListener.onFileOutput(filePath, input);
- }
- }
-
- public static final class Config {
- private String mDefaultDir; // The default storage directory of log.
- private String mDir; // The storage directory of log.
- private String mFilePrefix = "util";// The file prefix of log.
- private String mFileExtension = ".txt";// The file extension of log.
- private boolean mLogSwitch = true; // The switch of log.
- private boolean mLog2ConsoleSwitch = true; // The logcat's switch of log.
- private String mGlobalTag = ""; // The global tag of log.
- private boolean mTagIsSpace = true; // The global tag is space.
- private boolean mLogHeadSwitch = true; // The head's switch of log.
- private boolean mLog2FileSwitch = false; // The file's switch of log.
- private boolean mLogBorderSwitch = true; // The border's switch of log.
- private boolean mSingleTagSwitch = true; // The single tag of log.
- private int mConsoleFilter = V; // The console's filter of log.
- private int mFileFilter = V; // The file's filter of log.
- private int mStackDeep = 1; // The stack's deep of log.
- private int mStackOffset = 0; // The stack's offset of log.
- private int mSaveDays = -1; // The save days of log.
- private String mProcessName = UtilsBridge.getCurrentProcessName();
- private IFileWriter mFileWriter;
- private OnConsoleOutputListener mOnConsoleOutputListener;
- private OnFileOutputListener mOnFileOutputListener;
- private UtilsBridge.FileHead mFileHead = new UtilsBridge.FileHead("Log");
-
- private Config() {
- if (UtilsBridge.isSDCardEnableByEnvironment()
- && Utils.getApp().getExternalFilesDir(null) != null)
- mDefaultDir = Utils.getApp().getExternalFilesDir(null) + FILE_SEP + "log" + FILE_SEP;
- else {
- mDefaultDir = Utils.getApp().getFilesDir() + FILE_SEP + "log" + FILE_SEP;
- }
- }
-
- public final Config setLogSwitch(final boolean logSwitch) {
- mLogSwitch = logSwitch;
- return this;
- }
-
- public final Config setConsoleSwitch(final boolean consoleSwitch) {
- mLog2ConsoleSwitch = consoleSwitch;
- return this;
- }
-
- public final Config setGlobalTag(final String tag) {
- if (UtilsBridge.isSpace(tag)) {
- mGlobalTag = "";
- mTagIsSpace = true;
- } else {
- mGlobalTag = tag;
- mTagIsSpace = false;
- }
- return this;
- }
-
- public final Config setLogHeadSwitch(final boolean logHeadSwitch) {
- mLogHeadSwitch = logHeadSwitch;
- return this;
- }
-
- public final Config setLog2FileSwitch(final boolean log2FileSwitch) {
- mLog2FileSwitch = log2FileSwitch;
- return this;
- }
-
- public final Config setDir(final String dir) {
- if (UtilsBridge.isSpace(dir)) {
- mDir = null;
- } else {
- mDir = dir.endsWith(FILE_SEP) ? dir : dir + FILE_SEP;
- }
- return this;
- }
-
- public final Config setDir(final File dir) {
- mDir = dir == null ? null : (dir.getAbsolutePath() + FILE_SEP);
- return this;
- }
-
- public final Config setFilePrefix(final String filePrefix) {
- if (UtilsBridge.isSpace(filePrefix)) {
- mFilePrefix = "util";
- } else {
- mFilePrefix = filePrefix;
- }
- return this;
- }
-
- public final Config setFileExtension(final String fileExtension) {
- if (UtilsBridge.isSpace(fileExtension)) {
- mFileExtension = ".txt";
- } else {
- if (fileExtension.startsWith(".")) {
- mFileExtension = fileExtension;
- } else {
- mFileExtension = "." + fileExtension;
- }
- }
- return this;
- }
-
- public final Config setBorderSwitch(final boolean borderSwitch) {
- mLogBorderSwitch = borderSwitch;
- return this;
- }
-
- public final Config setSingleTagSwitch(final boolean singleTagSwitch) {
- mSingleTagSwitch = singleTagSwitch;
- return this;
- }
-
- public final Config setConsoleFilter(@TYPE final int consoleFilter) {
- mConsoleFilter = consoleFilter;
- return this;
- }
-
- public final Config setFileFilter(@TYPE final int fileFilter) {
- mFileFilter = fileFilter;
- return this;
- }
-
- public final Config setStackDeep(@IntRange(from = 1) final int stackDeep) {
- mStackDeep = stackDeep;
- return this;
- }
-
- public final Config setStackOffset(@IntRange(from = 0) final int stackOffset) {
- mStackOffset = stackOffset;
- return this;
- }
-
- public final Config setSaveDays(@IntRange(from = 1) final int saveDays) {
- mSaveDays = saveDays;
- return this;
- }
-
- public final Config addFormatter(final IFormatter iFormatter) {
- if (iFormatter != null) {
- I_FORMATTER_MAP.put(getTypeClassFromParadigm(iFormatter), iFormatter);
- }
- return this;
- }
-
- public final Config setFileWriter(final IFileWriter fileWriter) {
- mFileWriter = fileWriter;
- return this;
- }
-
- public final Config setOnConsoleOutputListener(final OnConsoleOutputListener listener) {
- mOnConsoleOutputListener = listener;
- return this;
- }
-
- public final Config setOnFileOutputListener(final OnFileOutputListener listener) {
- mOnFileOutputListener = listener;
- return this;
- }
-
- public final Config addFileExtraHead(final Map fileExtraHead) {
- mFileHead.append(fileExtraHead);
- return this;
- }
-
- public final Config addFileExtraHead(final String key, final String value) {
- mFileHead.append(key, value);
- return this;
- }
-
- public final String getProcessName() {
- if (mProcessName == null) return "";
- return mProcessName.replace(":", "_");
- }
-
- public final String getDefaultDir() {
- return mDefaultDir;
- }
-
- public final String getDir() {
- return mDir == null ? mDefaultDir : mDir;
- }
-
- public final String getFilePrefix() {
- return mFilePrefix;
- }
-
- public final String getFileExtension() {
- return mFileExtension;
- }
-
- public final boolean isLogSwitch() {
- return mLogSwitch;
- }
-
- public final boolean isLog2ConsoleSwitch() {
- return mLog2ConsoleSwitch;
- }
-
- public final String getGlobalTag() {
- if (UtilsBridge.isSpace(mGlobalTag)) return "";
- return mGlobalTag;
- }
-
- public final boolean isLogHeadSwitch() {
- return mLogHeadSwitch;
- }
-
- public final boolean isLog2FileSwitch() {
- return mLog2FileSwitch;
- }
-
- public final boolean isLogBorderSwitch() {
- return mLogBorderSwitch;
- }
-
- public final boolean isSingleTagSwitch() {
- return mSingleTagSwitch;
- }
-
- public final char getConsoleFilter() {
- return T[mConsoleFilter - V];
- }
-
- public final char getFileFilter() {
- return T[mFileFilter - V];
- }
-
- public final int getStackDeep() {
- return mStackDeep;
- }
-
- public final int getStackOffset() {
- return mStackOffset;
- }
-
- public final int getSaveDays() {
- return mSaveDays;
- }
-
- public final boolean haveSetOnConsoleOutputListener() {
- return mOnConsoleOutputListener != null;
- }
-
- public final boolean haveSetOnFileOutputListener() {
- return mOnFileOutputListener != null;
- }
-
- @Override
- public String toString() {
- return "process: " + getProcessName()
- + LINE_SEP + "logSwitch: " + isLogSwitch()
- + LINE_SEP + "consoleSwitch: " + isLog2ConsoleSwitch()
- + LINE_SEP + "tag: " + (getGlobalTag().equals("") ? "null" : getGlobalTag())
- + LINE_SEP + "headSwitch: " + isLogHeadSwitch()
- + LINE_SEP + "fileSwitch: " + isLog2FileSwitch()
- + LINE_SEP + "dir: " + getDir()
- + LINE_SEP + "filePrefix: " + getFilePrefix()
- + LINE_SEP + "borderSwitch: " + isLogBorderSwitch()
- + LINE_SEP + "singleTagSwitch: " + isSingleTagSwitch()
- + LINE_SEP + "consoleFilter: " + getConsoleFilter()
- + LINE_SEP + "fileFilter: " + getFileFilter()
- + LINE_SEP + "stackDeep: " + getStackDeep()
- + LINE_SEP + "stackOffset: " + getStackOffset()
- + LINE_SEP + "saveDays: " + getSaveDays()
- + LINE_SEP + "formatter: " + I_FORMATTER_MAP
- + LINE_SEP + "fileWriter: " + mFileWriter
- + LINE_SEP + "onConsoleOutputListener: " + mOnConsoleOutputListener
- + LINE_SEP + "onFileOutputListener: " + mOnFileOutputListener
- + LINE_SEP + "fileExtraHeader: " + mFileHead.getAppended();
- }
- }
-
- public abstract static class IFormatter {
- public abstract String format(T t);
- }
-
- public interface IFileWriter {
- void write(String file, String content);
- }
-
- public interface OnConsoleOutputListener {
- void onConsoleOutput(@TYPE int type, String tag, String content);
- }
-
- public interface OnFileOutputListener {
- void onFileOutput(String filePath, String content);
- }
-
- private final static class TagHead {
- String tag;
- String[] consoleHead;
- String fileHead;
-
- TagHead(String tag, String[] consoleHead, String fileHead) {
- this.tag = tag;
- this.consoleHead = consoleHead;
- this.fileHead = fileHead;
- }
- }
-
- private final static class LogFormatter {
-
- static String object2String(Object object) {
- return object2String(object, -1);
- }
-
- static String object2String(Object object, int type) {
- if (object.getClass().isArray()) return array2String(object);
- if (object instanceof Throwable)
- return UtilsBridge.getFullStackTrace((Throwable) object);
- if (object instanceof Bundle) return bundle2String((Bundle) object);
- if (object instanceof Intent) return intent2String((Intent) object);
- if (type == JSON) {
- return object2Json(object);
- } else if (type == XML) {
- return formatXml(object.toString());
- }
- return object.toString();
- }
-
- private static String bundle2String(Bundle bundle) {
- Iterator iterator = bundle.keySet().iterator();
- if (!iterator.hasNext()) {
- return "Bundle {}";
- }
- StringBuilder sb = new StringBuilder(128);
- sb.append("Bundle { ");
- for (; ; ) {
- String key = iterator.next();
- Object value = bundle.get(key);
- sb.append(key).append('=');
- if (value instanceof Bundle) {
- sb.append(value == bundle ? "(this Bundle)" : bundle2String((Bundle) value));
- } else {
- sb.append(formatObject(value));
- }
- if (!iterator.hasNext()) return sb.append(" }").toString();
- sb.append(',').append(' ');
- }
- }
-
- private static String intent2String(Intent intent) {
- StringBuilder sb = new StringBuilder(128);
- sb.append("Intent { ");
- boolean first = true;
- String mAction = intent.getAction();
- if (mAction != null) {
- sb.append("act=").append(mAction);
- first = false;
- }
- Set mCategories = intent.getCategories();
- if (mCategories != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("cat=[");
- boolean firstCategory = true;
- for (String c : mCategories) {
- if (!firstCategory) {
- sb.append(',');
- }
- sb.append(c);
- firstCategory = false;
- }
- sb.append("]");
- }
- Uri mData = intent.getData();
- if (mData != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("dat=").append(mData);
- }
- String mType = intent.getType();
- if (mType != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("typ=").append(mType);
- }
- int mFlags = intent.getFlags();
- if (mFlags != 0) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("flg=0x").append(Integer.toHexString(mFlags));
- }
- String mPackage = intent.getPackage();
- if (mPackage != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("pkg=").append(mPackage);
- }
- ComponentName mComponent = intent.getComponent();
- if (mComponent != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("cmp=").append(mComponent.flattenToShortString());
- }
- Rect mSourceBounds = intent.getSourceBounds();
- if (mSourceBounds != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("bnds=").append(mSourceBounds.toShortString());
- }
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
- ClipData mClipData = intent.getClipData();
- if (mClipData != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- clipData2String(mClipData, sb);
- }
- }
- Bundle mExtras = intent.getExtras();
- if (mExtras != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("extras={");
- sb.append(bundle2String(mExtras));
- sb.append('}');
- }
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
- Intent mSelector = intent.getSelector();
- if (mSelector != null) {
- if (!first) {
- sb.append(' ');
- }
- first = false;
- sb.append("sel={");
- sb.append(mSelector == intent ? "(this Intent)" : intent2String(mSelector));
- sb.append("}");
- }
- }
- sb.append(" }");
- return sb.toString();
- }
-
- @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
- private static void clipData2String(ClipData clipData, StringBuilder sb) {
- ClipData.Item item = clipData.getItemAt(0);
- if (item == null) {
- sb.append("ClipData.Item {}");
- return;
- }
- sb.append("ClipData.Item { ");
- String mHtmlText = item.getHtmlText();
- if (mHtmlText != null) {
- sb.append("H:");
- sb.append(mHtmlText);
- sb.append("}");
- return;
- }
- CharSequence mText = item.getText();
- if (mText != null) {
- sb.append("T:");
- sb.append(mText);
- sb.append("}");
- return;
- }
- Uri uri = item.getUri();
- if (uri != null) {
- sb.append("U:").append(uri);
- sb.append("}");
- return;
- }
- Intent intent = item.getIntent();
- if (intent != null) {
- sb.append("I:");
- sb.append(intent2String(intent));
- sb.append("}");
- return;
- }
- sb.append("NULL");
- sb.append("}");
- }
-
- private static String object2Json(Object object) {
- if (object instanceof CharSequence) {
- return UtilsBridge.formatJson(object.toString());
- }
- try {
- return UtilsBridge.getGson4LogUtils().toJson(object);
- } catch (Throwable t) {
- return object.toString();
- }
- }
-
- private static String formatJson(String json) {
- try {
- for (int i = 0, len = json.length(); i < len; i++) {
- char c = json.charAt(i);
- if (c == '{') {
- return new JSONObject(json).toString(2);
- } else if (c == '[') {
- return new JSONArray(json).toString(2);
- } else if (!Character.isWhitespace(c)) {
- return json;
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return json;
- }
-
- private static String formatXml(String xml) {
- try {
- Source xmlInput = new StreamSource(new StringReader(xml));
- StreamResult xmlOutput = new StreamResult(new StringWriter());
- Transformer transformer = TransformerFactory.newInstance().newTransformer();
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
- transformer.transform(xmlInput, xmlOutput);
- xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEP);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return xml;
- }
-
- private static String array2String(Object object) {
- if (object instanceof Object[]) {
- return Arrays.deepToString((Object[]) object);
- } else if (object instanceof boolean[]) {
- return Arrays.toString((boolean[]) object);
- } else if (object instanceof byte[]) {
- return Arrays.toString((byte[]) object);
- } else if (object instanceof char[]) {
- return Arrays.toString((char[]) object);
- } else if (object instanceof double[]) {
- return Arrays.toString((double[]) object);
- } else if (object instanceof float[]) {
- return Arrays.toString((float[]) object);
- } else if (object instanceof int[]) {
- return Arrays.toString((int[]) object);
- } else if (object instanceof long[]) {
- return Arrays.toString((long[]) object);
- } else if (object instanceof short[]) {
- return Arrays.toString((short[]) object);
- }
- throw new IllegalArgumentException("Array has incompatible type: " + object.getClass());
- }
- }
-
- private static Class getTypeClassFromParadigm(final IFormatter formatter) {
- Type[] genericInterfaces = formatter.getClass().getGenericInterfaces();
- Type type;
- if (genericInterfaces.length == 1) {
- type = genericInterfaces[0];
- } else {
- type = formatter.getClass().getGenericSuperclass();
- }
- type = ((ParameterizedType) type).getActualTypeArguments()[0];
- while (type instanceof ParameterizedType) {
- type = ((ParameterizedType) type).getRawType();
- }
- String className = type.toString();
- if (className.startsWith("class ")) {
- className = className.substring(6);
- } else if (className.startsWith("interface ")) {
- className = className.substring(10);
- }
- try {
- return Class.forName(className);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static Class getClassFromObject(final Object obj) {
- Class objClass = obj.getClass();
- if (objClass.isAnonymousClass() || objClass.isSynthetic()) {
- Type[] genericInterfaces = objClass.getGenericInterfaces();
- String className;
- if (genericInterfaces.length == 1) {// interface
- Type type = genericInterfaces[0];
- while (type instanceof ParameterizedType) {
- type = ((ParameterizedType) type).getRawType();
- }
- className = type.toString();
- } else {// abstract class or lambda
- Type type = objClass.getGenericSuperclass();
- while (type instanceof ParameterizedType) {
- type = ((ParameterizedType) type).getRawType();
- }
- className = type.toString();
- }
-
- if (className.startsWith("class ")) {
- className = className.substring(6);
- } else if (className.startsWith("interface ")) {
- className = className.substring(10);
- }
- try {
- return Class.forName(className);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- return objClass;
- }
-}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java
index 5419e2a828..913c2cd0e5 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ProcessUtils.java
@@ -58,7 +58,7 @@ public final class ProcessUtils {
public static String getForegroundProcessName() {
ActivityManager am =
(ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
- //noinspection ConstantConditions
+ //noinspection Constant Conditions
List pInfo = am.getRunningAppProcesses();
if (pInfo != null && pInfo.size() > 0) {
for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
@@ -68,57 +68,55 @@ public final class ProcessUtils {
}
}
}
- if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
- PackageManager pm = Utils.getApp().getPackageManager();
- Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
- List list =
- pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
- Log.i("ProcessUtils", list.toString());
- if (list.size() <= 0) {
+ PackageManager pm = Utils.getApp().getPackageManager();
+ Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
+ List list =
+ pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+ Log.i("ProcessUtils", list.toString());
+ if (list.size() <= 0) {
+ Log.i("ProcessUtils",
+ "getForegroundProcessName: noun of access to usage information.");
+ return "";
+ }
+ try {// Access to usage information.
+ ApplicationInfo info =
+ pm.getApplicationInfo(Utils.getApp().getPackageName(), 0);
+ AppOpsManager aom =
+ (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE);
+ if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
+ info.uid,
+ info.packageName) != AppOpsManager.MODE_ALLOWED) {
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ Utils.getApp().startActivity(intent);
+ }
+ if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
+ info.uid,
+ info.packageName) != AppOpsManager.MODE_ALLOWED) {
Log.i("ProcessUtils",
- "getForegroundProcessName: noun of access to usage information.");
+ "getForegroundProcessName: refuse to device usage stats.");
return "";
}
- try {// Access to usage information.
- ApplicationInfo info =
- pm.getApplicationInfo(Utils.getApp().getPackageName(), 0);
- AppOpsManager aom =
- (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE);
- if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
- info.uid,
- info.packageName) != AppOpsManager.MODE_ALLOWED) {
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- Utils.getApp().startActivity(intent);
- }
- if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
- info.uid,
- info.packageName) != AppOpsManager.MODE_ALLOWED) {
- Log.i("ProcessUtils",
- "getForegroundProcessName: refuse to device usage stats.");
- return "";
- }
- UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp()
- .getSystemService(Context.USAGE_STATS_SERVICE);
- List usageStatsList = null;
- if (usageStatsManager != null) {
- long endTime = System.currentTimeMillis();
- long beginTime = endTime - 86400000 * 7;
- usageStatsList = usageStatsManager
- .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
- beginTime, endTime);
- }
- if (usageStatsList == null || usageStatsList.isEmpty()) return "";
- UsageStats recentStats = null;
- for (UsageStats usageStats : usageStatsList) {
- if (recentStats == null
- || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
- recentStats = usageStats;
- }
- }
- return recentStats == null ? null : recentStats.getPackageName();
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
+ UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp()
+ .getSystemService(Context.USAGE_STATS_SERVICE);
+ List usageStatsList = null;
+ if (usageStatsManager != null) {
+ long endTime = System.currentTimeMillis();
+ long beginTime = endTime - 86400000 * 7;
+ usageStatsList = usageStatsManager
+ .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
+ beginTime, endTime);
}
+ if (usageStatsList == null || usageStatsList.isEmpty()) return "";
+ UsageStats recentStats = null;
+ for (UsageStats usageStats : usageStatsList) {
+ if (recentStats == null
+ || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
+ recentStats = usageStats;
+ }
+ }
+ return recentStats == null ? null : recentStats.getPackageName();
+ } catch (PackageManager.NameNotFoundException e) {
+ e.printStackTrace();
}
return "";
}
@@ -223,9 +221,8 @@ public final class ProcessUtils {
}
private static String getCurrentProcessNameByFile() {
- try {
- File file = new File("/proc/" + Process.myPid() + "/" + "cmdline");
- BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
+ File file = new File("/proc/" + Process.myPid() + "/" + "cmdline");
+ try(BufferedReader mBufferedReader = new BufferedReader(new FileReader(file))) {
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
@@ -301,7 +298,7 @@ public final class ProcessUtils {
}
public static String getPackageName() {
- String packageName = null;
+ String packageName;
BufferedReader reader = null;
try {
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java
index 581c7d26af..5753635382 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/RomUtils.java
@@ -393,7 +393,6 @@ public final class RomUtils {
}
private static String getSystemPropertyByShell(final String propName) {
- String line;
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("getprop " + propName);
@@ -414,11 +413,9 @@ public final class RomUtils {
}
private static String getSystemPropertyByStream(final String key) {
- try {
+ try( FileInputStream is = new FileInputStream(
+ new File(Environment.getRootDirectory(), "build.prop"))) {
Properties prop = new Properties();
- FileInputStream is = new FileInputStream(
- new File(Environment.getRootDirectory(), "build.prop")
- );
prop.load(is);
return prop.getProperty(key, "");
} catch (Exception ignore) {/**/}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java
index 04e0563543..07bda7a10d 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/SystemPropertiesUtils.java
@@ -11,16 +11,15 @@ public final class SystemPropertiesUtils {
public static String getProperty(String key, String defaultValue) {
String value = defaultValue;
-
try {
Class> c = Class.forName(CLASS_NAME);
Method get = c.getMethod("get", String.class, String.class);
value = (String) (get.invoke(c, key, defaultValue));
+ return value;
} catch (Exception e) {
e.printStackTrace();
- } finally {
- return value;
}
+ return value;
}
public static void setProperty(String key, String value) {
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java
index c7f2ce6ced..5c46a7945b 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/TimeTransformUtils.java
@@ -19,11 +19,14 @@ public final class TimeTransformUtils {
int hours = totalSeconds / 3600;
StringBuilder stringBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
+ String formatStr;
if (hours > 0) {
- return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
+ formatStr = mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
- return mFormatter.format("%02d:%02d", minutes, seconds).toString();
+ formatStr = mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
+ mFormatter.close();
+ return formatStr;
}
public static String stringForTimeWithHours(int timeMs) {
@@ -36,7 +39,9 @@ public final class TimeTransformUtils {
int hours = totalSeconds / 3600;
StringBuilder stringBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
- return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
+ String formatStr = mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
+ mFormatter.close();
+ return formatStr;
}
diff --git a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java
index 0c2b7feb0e..df3571d267 100644
--- a/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java
+++ b/core/mogo-core-utils/src/main/java/com/mogo/eagle/core/utilcode/util/ZipUtils.java
@@ -62,18 +62,11 @@ public final class ZipUtils {
final String comment)
throws IOException {
if (srcFilePaths == null || zipFilePath == null) return false;
- ZipOutputStream zos = null;
- try {
- zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
+ try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
for (String srcFile : srcFilePaths) {
if (!zipFile(UtilsBridge.getFileByPath(srcFile), "", zos, comment)) return false;
}
return true;
- } finally {
- if (zos != null) {
- zos.finish();
- zos.close();
- }
}
}
@@ -104,18 +97,11 @@ public final class ZipUtils {
final String comment)
throws IOException {
if (srcFiles == null || zipFile == null) return false;
- ZipOutputStream zos = null;
- try {
- zos = new ZipOutputStream(new FileOutputStream(zipFile));
+ try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
for (File srcFile : srcFiles) {
if (!zipFile(srcFile, "", zos, comment)) return false;
}
return true;
- } finally {
- if (zos != null) {
- zos.finish();
- zos.close();
- }
}
}
@@ -177,14 +163,8 @@ public final class ZipUtils {
final String comment)
throws IOException {
if (srcFile == null || zipFile == null) return false;
- ZipOutputStream zos = null;
- try {
- zos = new ZipOutputStream(new FileOutputStream(zipFile));
+ try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
return zipFile(srcFile, "", zos, comment);
- } finally {
- if (zos != null) {
- zos.close();
- }
}
}
@@ -207,22 +187,16 @@ public final class ZipUtils {
}
}
} else {
- InputStream is = null;
- try {
- is = new BufferedInputStream(new FileInputStream(srcFile));
+ try (InputStream is = new BufferedInputStream(new FileInputStream(srcFile))) {
ZipEntry entry = new ZipEntry(rootPath);
entry.setComment(comment);
zos.putNextEntry(entry);
- byte buffer[] = new byte[BUFFER_LEN];
+ byte[] buffer = new byte[BUFFER_LEN];
int len;
while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
- } finally {
- if (is != null) {
- is.close();
- }
}
}
return true;
@@ -330,23 +304,12 @@ public final class ZipUtils {
return UtilsBridge.createOrExistsDir(file);
} else {
if (!UtilsBridge.createOrExistsFile(file)) return false;
- InputStream in = null;
- OutputStream out = null;
- try {
- in = new BufferedInputStream(zip.getInputStream(entry));
- out = new BufferedOutputStream(new FileOutputStream(file));
- byte buffer[] = new byte[BUFFER_LEN];
+ try (InputStream in = new BufferedInputStream(zip.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
+ byte[] buffer = new byte[BUFFER_LEN];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
- } finally {
- if (in != null) {
- in.close();
- }
- if (out != null) {
- out.close();
- }
}
}
return true;
diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java
index 6b2afa8ef1..6fb688aea9 100644
--- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java
+++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/element/M3DCar.java
@@ -6,13 +6,13 @@ import java.io.DataInputStream;
import java.io.IOException;
public class M3DCar {
- private Context context;
- private int resid;
+ private final Context context;
+ private final int redis;
public byte[] totBuffer = null;
public int totSize = 0;
- public M3DCar(Context context, int resid) {
- this.resid = resid;
+ public M3DCar(Context context, int redis) {
+ this.redis = redis;
this.context = context;
loadData();
}
@@ -20,12 +20,12 @@ public class M3DCar {
private void loadData() {
if (null != totBuffer)
return;
- DataInputStream dis = new DataInputStream(context.getResources().openRawResource(resid));
+ ;
int curTotSize = 64 * 1024;
totBuffer = new byte[curTotSize];
byte[] buffer = new byte[1024];
- int size = 0;
- try {
+ int size;
+ try(DataInputStream dis = new DataInputStream(context.getResources().openRawResource(redis))) {
while ((size = dis.read(buffer)) >= 0) {
if (totSize + size > curTotSize) {
curTotSize = (totSize + size) * 3 / 2;
@@ -36,8 +36,8 @@ public class M3DCar {
System.arraycopy(buffer, 0, totBuffer, totSize, size);
totSize += size;
}
- dis.close();
} catch (IOException e) {
+ e.printStackTrace();
}
}
}
diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java
index ca863d4d06..c71069f266 100644
--- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java
+++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/panel/DirectionLayer.java
@@ -23,8 +23,8 @@ public class DirectionLayer extends ImageView implements MapStatusListener {
private static final String TAG = "DirectionLayer";
private Drawable icon;
private IMapController mMapController;
- private Matrix matrix = new Matrix();
- private Camera mCamera = new Camera();
+ private final Matrix matrix = new Matrix();
+ private final Camera mCamera = new Camera();
public DirectionLayer(Context context){
super(context);
diff --git a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java
index 130e91f0ac..540f62aa69 100644
--- a/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java
+++ b/libraries/mapmodule/src/main/java/com/zhidaoauto/map/sdk/inner/utils/MainInfo.java
@@ -7,7 +7,7 @@ import java.text.SimpleDateFormat;
import java.util.Date;
public class MainInfo {
- private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
+ private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
private static MainInfo m_hinst = null;
private boolean mbUserLog = true;
private static boolean mbDebug = false;
@@ -33,11 +33,9 @@ public class MainInfo {
if (null == dir) {
return;
}
- try {
- FileWriter fw = new FileWriter((dir + "log.txt"), true);
+ try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) {
String date = dateFormat.format(new Date());
fw.write(date + " " + log + "\r\n");
- fw.close();
} catch (Exception ex) {
}
}
@@ -50,10 +48,8 @@ public class MainInfo {
if (null == dir) {
return;
}
- try {
- FileWriter fw = new FileWriter((dir + "log.txt"), true);
+ try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) {
e.printStackTrace(new PrintWriter(fw));
- fw.close();
} catch (Exception ex) {
}
}
diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java
index 1fdceec991..0a461fc6fd 100644
--- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java
+++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/common/BaseSDCardHelper.java
@@ -79,7 +79,9 @@ public class BaseSDCardHelper {
e.printStackTrace();
} finally {
try {
- bos.close();
+ if (bos != null) {
+ bos.close();
+ }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -108,7 +110,9 @@ public class BaseSDCardHelper {
e.printStackTrace();
} finally {
try {
- bos.close();
+ if (bos != null) {
+ bos.close();
+ }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -134,7 +138,9 @@ public class BaseSDCardHelper {
e.printStackTrace();
} finally {
try {
- bos.close();
+ if(bos != null){
+ bos.close();
+ }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -160,7 +166,9 @@ public class BaseSDCardHelper {
e.printStackTrace();
} finally {
try {
- bos.close();
+ if(bos != null){
+ bos.close();
+ }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@@ -177,9 +185,9 @@ public class BaseSDCardHelper {
try {
bis = new BufferedInputStream(
- new FileInputStream(new File(fileDir)));
+ new FileInputStream(fileDir));
byte[] buffer = new byte[8 * 1024];
- int c = 0;
+ int c;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
@@ -237,27 +245,27 @@ public class BaseSDCardHelper {
* 删除文件夹
* @param path
*/
- public static boolean deleteAllFilesOfDir(File path) {
+ public static boolean deleteAllFilesOfDir(File path) {
if (!path.exists()){
return false;
}
if (path.isFile()) {
- path.delete();
- return true;
+ return path.delete();
}
File[] files = path.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteAllFilesOfDir(files[i]);
+ if(files != null){
+ for (File file : files) {
+ deleteAllFilesOfDir(file);
+ }
}
- path.delete();
System.out.println("删除文件夹成功");
- return true;
+ return path.delete();
}
/**
* 删除文件夹2
* @param path
*/
- public static void deleteAllFilesOfDir2(File path) {
+ public static void deleteAllFilesOfDir2(File path) {
if (!path.exists()){
return ;
}
@@ -266,8 +274,10 @@ public class BaseSDCardHelper {
return ;
}
File[] files = path.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteAllFilesOfDir(files[i]);
+ if(files != null){
+ for (File file : files) {
+ deleteAllFilesOfDir(file);
+ }
}
path.delete();
System.out.println("删除文件夹成功");
diff --git a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java
index 2e7dca9179..db142ba712 100644
--- a/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java
+++ b/libraries/mogo-adas/src/main/java/com/zhidao/support/adas/high/subscribe/SubscribeInterface.java
@@ -36,7 +36,6 @@ public class SubscribeInterface {
public SubscribeInterface(@NonNull OnSubscribeInterfaceListener listener) {
this.listener = listener;
- if (listener == null) throw new RuntimeException();
init();
}
@@ -62,10 +61,8 @@ public class SubscribeInterface {
* @param role 角色 详情参见{@link Constants.TERMINAL_ROLE}
* @param type 注册类型 详情参见{@link Constants.SUBSCRIBE_TYPE}
* @param messageTypes 要操作的接口
- * @return
*/
public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull Set messageTypes) {
- if (messageTypes == null) return false;
MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder();
builder.setRole(role).setReqType(type);
Map temp = new HashMap<>();
@@ -89,9 +86,7 @@ public class SubscribeInterface {
}
}
}
-
-
- return false;
+ return isSendSucceed;
}
/**
@@ -103,7 +98,6 @@ public class SubscribeInterface {
* @return 是否加入ws发送队列
*/
public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull MessageType messageType) {
- if (messageType == null) return false;
MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder();
builder.setRole(role).setReqType(type).addDataTypes(messageType.typeCode.getNumber());
boolean isSendSucceed = listener.onSendSubscribe(builder.build().toByteArray());
@@ -120,7 +114,7 @@ public class SubscribeInterface {
subscribedInterface.remove(messageType);
}
}
- return false;
+ return isSendSucceed;
}
//根据参数查询是否已订阅
diff --git a/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java b/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java
index 4c3e8705cf..18a6f2fd72 100644
--- a/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java
+++ b/tts/tts-pad/src/main/java/com/mogo/tts/pad/PadTTS.java
@@ -68,7 +68,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
private int curTtsLevel = -1;
// 由于主动打断不会有回调事件,所以主动打断时清掉map中被打断的text和callback
private String curTtsContent = "";
- private LinkedList> linkedList = new LinkedList<>();
+ private final LinkedList> linkedList = new LinkedList<>();
public void release() {
CallerLogger.d(TAG, "release");
@@ -101,13 +101,13 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
private VoiceClient mVoiceClient;
private MogoVoiceManager mogoVoiceManager;
// 免唤醒指令
- private Map> mCmdMap = new HashMap<>();
+ private final Map> mCmdMap = new HashMap<>();
// 问答指令
- private Map mQAndAMap = new HashMap<>();
+ private final Map mQAndAMap = new HashMap<>();
// 单独的语音播放
- private Map mSpeakVoiceMap = new HashMap<>();
+ private final Map mSpeakVoiceMap = new HashMap<>();
- private Map mCacheUnWakeupCommands = new ConcurrentHashMap<>();
+ private final Map mCacheUnWakeupCommands = new ConcurrentHashMap<>();
private static final String TTS_BACK_RES_ZHILING = "zhilingf_common_back_ce_local.v2.1.0.bin";
private int audioRecorderType = DUILiteConfig.TYPE_COMMON_MIC;
@@ -119,7 +119,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
public static final String TTS_BACK_RES_GUODGM = "guodgm_common_back_ce_local.v2.1.0.bin";
private AILocalTTSEngine mEngine;
private AILocalTTSIntent mAILocalTTSIntent;
- private String[] mBackResBinArray = new String[]{TTS_BACK_RES_ZHILING, TTS_BACK_RES_GUODGM};
+ private final String[] mBackResBinArray = new String[]{TTS_BACK_RES_ZHILING, TTS_BACK_RES_GUODGM};
// 单独的语音播放
private boolean mHasAuth;
private int retryCount;
@@ -277,8 +277,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/**
* 是否语音注册成功
- *
- * @return
*/
@Override
public boolean hasFlush() {
@@ -363,8 +361,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/**
* 语音播报
- *
- * @param text
*/
public void speakTTSVoice(String text, IMogoTTSCallback callBack) {
if (mEngine != null && mHasAuth) {
@@ -376,9 +372,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
public void stopSpeakTts(String text) {
if (mEngine != null && mHasAuth) {
- if (mSpeakVoiceMap.containsKey(text)) {
- mSpeakVoiceMap.remove(text);
- }
+ mSpeakVoiceMap.remove(text);
curTtsContent = "";
curTtsLevel = -1;
mEngine.stop();
@@ -387,9 +381,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
public void stopTts() {
if (mEngine != null && mHasAuth) {
- if (mSpeakVoiceMap.containsKey(curTtsContent)) {
- mSpeakVoiceMap.remove(curTtsContent);
- }
+ mSpeakVoiceMap.remove(curTtsContent);
// tts过程中调用stop不会有回调事件
curTtsContent = "";
curTtsLevel = -1;
@@ -399,8 +391,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/**
* 语音播报
- *
- * @param text
*/
public void speakTTSVoice(String text) {
CallerLogger.d(TAG, "speakTTSVoice");
@@ -493,24 +483,24 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
initFlushStatus();
if (mHasFlush) {
mSpeakVoiceMap.put(text, callBack);
- VoiceClient.PreemptType preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NONE;
- if (type != null) {
- switch (type) {
- case PREEMPT_TYPE_NEXT:
- preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NEXT;
- break;
- case PREEMPT_TYPE_FLUSH:
- preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_FLUSH;
- break;
- case PREEMPT_TYPE_IMMEDIATELY:
- preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY;
- break;
- case PREEMPT_TYPE_IMMEDIATELY_WITHOUT_CANCEL:
- preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY_WITHOUT_CANCLE;
- break;
- }
- }
speakTTSVoice(text);
+// VoiceClient.PreemptType preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NONE;
+// if (type != null) {
+// switch (type) {
+// case PREEMPT_TYPE_NEXT:
+// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_NEXT;
+// break;
+// case PREEMPT_TYPE_FLUSH:
+// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_FLUSH;
+// break;
+// case PREEMPT_TYPE_IMMEDIATELY:
+// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY;
+// break;
+// case PREEMPT_TYPE_IMMEDIATELY_WITHOUT_CANCEL:
+// preemptType = VoiceClient.PreemptType.PREEMPT_TYPE_IMMEADIATELY_WITHOUT_CANCLE;
+// break;
+// }
+// }
// mVoiceClient.speakTypeText( text, preemptType );
}
} catch (Exception e) {
@@ -679,7 +669,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
CallerLogger.d(TAG, "txz is voiceServiceReady");
return true;
}
- return true;
+ return false;
}
public void speakTTSAndDuck(String text) {