[sonar] merge

This commit is contained in:
zhongchao
2023-10-18 16:28:03 +08:00
parent da2fd464e5
commit 523ae08c5a
27 changed files with 277 additions and 1647 deletions

3
.gitignore vendored
View File

@@ -7,4 +7,5 @@
/build /build
/captures /captures
.externalNativeBuild .externalNativeBuild
.cxx .cxx
.gitlab-ci.yml

View File

@@ -24,13 +24,13 @@ public class OCHStockBlurView extends View {
private float mDownsampleFactor; // default 4 private float mDownsampleFactor; // default 4
private int mOverlayColor; // default #aaffffff private int mOverlayColor; // default #aaffffff
private float mBlurRadius; // default 10dp (0 < r <= 25) private float mBlurRadius; // default 10dp (0 < r <= 25)
private boolean onece; private final boolean onece;
private boolean mDirty; private boolean mDirty;
private Bitmap mBitmapToBlur, mBlurredBitmap; private Bitmap mBitmapToBlur, mBlurredBitmap;
private Canvas mBlurringCanvas; private Canvas mBlurringCanvas;
private boolean mIsRendering; private boolean mIsRendering;
private Paint mPaint; private final Paint mPaint;
private final Rect mRectSrc = new Rect(), mRectDst = new Rect(); private final Rect mRectSrc = new Rect(), mRectDst = new Rect();
// mDecorView should be the root view of the activity (even if you are on a different window like a dialog) // mDecorView should be the root view of the activity (even if you are on a different window like a dialog)
private View mDecorView; private View mDecorView;

View File

@@ -8,4 +8,5 @@
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest> </manifest>

View File

@@ -5,7 +5,6 @@ import static com.mogo.eagle.core.utilcode.mogo.logger.scene.SceneConstant.M_DEV
import android.media.AudioRecord; import android.media.AudioRecord;
import android.media.MediaRecorder; import android.media.MediaRecorder;
import android.os.Environment; import android.os.Environment;
import android.util.Log;
import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger; import com.mogo.eagle.core.utilcode.mogo.logger.CallerLogger;
import com.mogo.eagle.core.utilcode.util.FileUtils; import com.mogo.eagle.core.utilcode.util.FileUtils;
@@ -42,7 +41,7 @@ public class RecordHelper {
private File resultFile = null; private File resultFile = null;
private File tmpFile = null; private File tmpFile = null;
private List<File> files = new ArrayList<>(); private final List<File> files = new ArrayList<>();
private Mp3EncodeThread mp3EncodeThread; private Mp3EncodeThread mp3EncodeThread;
public RecordHelper(RecordConfig config) { public RecordHelper(RecordConfig config) {
@@ -69,7 +68,9 @@ public class RecordHelper {
return; return;
} }
String path = getFilePath(fileName); String path = getFilePath(fileName);
resultFile = new File(path); if(path!=null){
resultFile = new File(path);
}
String tempFilePath = getTempFilePath(); String tempFilePath = getTempFilePath();
tmpFile = new File(tempFilePath); tmpFile = new File(tempFilePath);
audioRecordThread = new AudioRecordThread(); audioRecordThread = new AudioRecordThread();
@@ -134,7 +135,7 @@ public class RecordHelper {
} }
} }
private FftFactory fftFactory = new FftFactory(FftFactory.Level.Original); private final FftFactory fftFactory = new FftFactory(FftFactory.Level.Original);
private void notifyData(final byte[] data) { private void notifyData(final byte[] data) {
if (listener != null) { if (listener != null) {
@@ -192,14 +193,10 @@ public class RecordHelper {
@Override @Override
public void run() { public void run() {
super.run(); super.run();
if (currentConfig.getFormat() == RecordConfig.RecordFormat.MP3) {
switch (currentConfig.getFormat()) { startMp3Recorder();
case MP3: } else {
startMp3Recorder(); startPcmRecorder();
break;
default:
startPcmRecorder();
break;
} }
} }
@@ -275,12 +272,9 @@ public class RecordHelper {
private void stopMp3Encoded() { private void stopMp3Encoded() {
if (mp3EncodeThread != null) { if (mp3EncodeThread != null) {
mp3EncodeThread.stopSafe(new Mp3EncodeThread.EncordFinishListener() { mp3EncodeThread.stopSafe(() -> {
@Override notifyFinish();
public void onFinish() { mp3EncodeThread = null;
notifyFinish();
mp3EncodeThread = null;
}
}); });
} else { } else {
CallerLogger.e("$M_DEVA$TAG", "mp3EncodeThread is null, 代码业务流程有误,请检查!! "); CallerLogger.e("$M_DEVA$TAG", "mp3EncodeThread is null, 代码业务流程有误,请检查!! ");
@@ -382,8 +376,7 @@ public class RecordHelper {
} }
String format = currentConfig.getFormat().getExtension(); String format = currentConfig.getFormat().getExtension();
String filePath = String.format(Locale.getDefault(), "%s%s%s", ROOT_PATH, fileName, format); return String.format(Locale.getDefault(), "%s%s%s", ROOT_PATH, fileName, format);
return filePath;
} }
private String getTempFilePath() { private String getTempFilePath() {

View File

@@ -1311,11 +1311,9 @@ internal class DebugSettingView @JvmOverloads constructor(
*/ */
tbSelfLog.setOnCheckedChangeListener { _, isChecked -> tbSelfLog.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) { if (isChecked) {
LogUtils.getConfig().isLogSwitch = false
Logger.init(LogLevel.OFF) Logger.init(LogLevel.OFF)
MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = false MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = false
} else { } else {
LogUtils.getConfig().isLogSwitch = true
Logger.init(LogLevel.DEBUG) Logger.init(LogLevel.DEBUG)
MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = true MoGoAiCloudClient.getInstance().aiCloudClientConfig.isShowDebugLog = true
} }

View File

@@ -143,13 +143,13 @@ final class DiskLruCache implements Closeable {
private final File journalFileBackup; private final File journalFileBackup;
private final int appVersion; private final int appVersion;
private long maxSize; private long maxSize;
private int maxFileCount; private final int maxFileCount;
private final int valueCount; private final int valueCount;
private long size = 0; private long size = 0;
private int fileCount = 0; private int fileCount = 0;
private Writer journalWriter; private Writer journalWriter;
private final LinkedHashMap<String, Entry> lruEntries = private final LinkedHashMap<String, Entry> lruEntries =
new LinkedHashMap<String, Entry>(0, 0.75f, true); new LinkedHashMap<>(0, 0.75f, true);
private int redundantOpCount; private int redundantOpCount;
/** /**
@@ -161,7 +161,7 @@ final class DiskLruCache implements Closeable {
/** This cache uses a single background thread to evict entries. */ /** This cache uses a single background thread to evict entries. */
final ThreadPoolExecutor executorService = final ThreadPoolExecutor executorService =
new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
private final Callable<Void> cleanupCallable = new Callable<Void>() { private final Callable<Void> cleanupCallable = new Callable<Void>() {
public Void call() throws Exception { public Void call() throws Exception {
synchronized (DiskLruCache.this) { synchronized (DiskLruCache.this) {
@@ -355,9 +355,8 @@ final class DiskLruCache implements Closeable {
journalWriter.close(); journalWriter.close();
} }
Writer writer = new BufferedWriter( try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII)); new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII))) {
try {
writer.write(MAGIC); writer.write(MAGIC);
writer.write("\n"); writer.write("\n");
writer.write(VERSION_1); writer.write(VERSION_1);
@@ -375,8 +374,6 @@ final class DiskLruCache implements Closeable {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
} }
} }
} finally {
writer.close();
} }
if (journalFile.exists()) { if (journalFile.exists()) {
@@ -446,7 +443,7 @@ final class DiskLruCache implements Closeable {
} }
redundantOpCount++; redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n'); journalWriter.append(READ + ' ').append(key).append(String.valueOf('\n'));
if (journalRebuildRequired()) { if (journalRebuildRequired()) {
executorService.submit(cleanupCallable); executorService.submit(cleanupCallable);
} }
@@ -622,7 +619,7 @@ final class DiskLruCache implements Closeable {
} }
redundantOpCount++; redundantOpCount++;
journalWriter.append(REMOVE + ' ' + key + '\n'); journalWriter.append(REMOVE + ' ').append(key).append(String.valueOf('\n'));
lruEntries.remove(key); lruEntries.remove(key);
if (journalRebuildRequired()) { if (journalRebuildRequired()) {
@@ -656,7 +653,7 @@ final class DiskLruCache implements Closeable {
if (journalWriter == null) { if (journalWriter == null) {
return; // Already closed. return; // Already closed.
} }
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { for (Entry entry : new ArrayList<>(lruEntries.values())) {
if (entry.currentEditor != null) { if (entry.currentEditor != null) {
entry.currentEditor.abort(); entry.currentEditor.abort();
} }
@@ -706,7 +703,7 @@ final class DiskLruCache implements Closeable {
public final class Snapshot implements Closeable { public final class Snapshot implements Closeable {
private final String key; private final String key;
private final long sequenceNumber; private final long sequenceNumber;
private File[] files; private final File[] files;
private final InputStream[] ins; private final InputStream[] ins;
private final long[] lengths; private final long[] lengths;
@@ -756,7 +753,7 @@ final class DiskLruCache implements Closeable {
private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
@Override @Override
public void write(int b) throws IOException { public void write(int b) {
// Eat all writes silently. Nom nom. // 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, * Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed. * or null if no value has been committed.
*/ */
public InputStream newInputStream(int index) throws IOException { public InputStream newInputStream(int index) {
synchronized (DiskLruCache.this) { synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) { if (entry.currentEditor != this) {
throw new IllegalStateException(); throw new IllegalStateException();
@@ -809,7 +806,7 @@ final class DiskLruCache implements Closeable {
* {@link #commit} is called. The returned output stream does not throw * {@link #commit} is called. The returned output stream does not throw
* IOExceptions. * IOExceptions.
*/ */
public OutputStream newOutputStream(int index) throws IOException { public OutputStream newOutputStream(int index) {
synchronized (DiskLruCache.this) { synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) { if (entry.currentEditor != this) {
throw new IllegalStateException(); throw new IllegalStateException();
@@ -936,7 +933,7 @@ final class DiskLruCache implements Closeable {
this.lengths = new long[valueCount]; this.lengths = new long[valueCount];
} }
public String getLengths() throws IOException { public String getLengths() {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (long size : lengths) { for (long size : lengths) {
result.append(' ').append(size); result.append(' ').append(size);

View File

@@ -25,10 +25,9 @@ public class DiskLruCacheManager {
private static volatile DiskLruCacheManager instance; private static volatile DiskLruCacheManager instance;
private static final byte[] obj = new byte[0]; private static final byte[] obj = new byte[0];
private final int MAX_CACHE_SIZE = 64 * 1024 * 1024;
private DiskLruCacheManager(Context context) { private DiskLruCacheManager(Context context) {
try { try {
int MAX_CACHE_SIZE = 64 * 1024 * 1024;
diskLruCache = DiskLruCache.open(context.getCacheDir(), 1, 1, diskLruCache = DiskLruCache.open(context.getCacheDir(), 1, 1,
MAX_CACHE_SIZE, Integer.MAX_VALUE); MAX_CACHE_SIZE, Integer.MAX_VALUE);
} catch (Exception e) { } catch (Exception e) {

View File

@@ -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) { public void xml( String tag, String xml) {
if ( TextUtils.isEmpty(xml)) { if ( TextUtils.isEmpty(xml)) {
this.d(tag, "Empty/Null xml content"); this.d(tag, "Empty/Null xml content");
@@ -116,7 +118,7 @@ final class LoggerPrinter implements Printer {
StreamResult xmlOutput = new StreamResult(new StringWriter()); StreamResult xmlOutput = new StreamResult(new StringWriter());
Transformer transformer = TransformerFactory.newInstance().newTransformer(); Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes"); transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty("{" + xmlHtml + "}indent-amount", "2");
transformer.transform(e, xmlOutput); transformer.transform(e, xmlOutput);
this.d(tag, xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); this.d(tag, xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
} catch ( TransformerException var5) { } catch ( TransformerException var5) {

View File

@@ -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
* <p>
* 读取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;
}
}

View File

@@ -53,9 +53,6 @@ public class BitmapHelper {
/** /**
* 根据原图添加圆角 * 根据原图添加圆角
*
* @param source
* @return
*/ */
public static Bitmap createRoundCornerImage( Bitmap source, float corner ) { public static Bitmap createRoundCornerImage( Bitmap source, float corner ) {
final Paint paint = new Paint(); final Paint paint = new Paint();
@@ -75,7 +72,7 @@ public class BitmapHelper {
} }
ByteArrayOutputStream bos = null; ByteArrayOutputStream bos = null;
byte[] result = null; byte[] result;
try { try {
bos = new ByteArrayOutputStream(); bos = new ByteArrayOutputStream();
@@ -150,7 +147,7 @@ public class BitmapHelper {
} }
listener.onBeforeCompress(); listener.onBeforeCompress();
ByteArrayOutputStream bos = null; ByteArrayOutputStream bos = null;
Bitmap target = null; Bitmap target;
try { try {
bos = new ByteArrayOutputStream(); bos = new ByteArrayOutputStream();
@@ -164,15 +161,11 @@ public class BitmapHelper {
byte[] result = bos.toByteArray(); byte[] result = bos.toByteArray();
target = bytesToBitmap( result ); target = bytesToBitmap( result );
if ( listener != null ) { listener.onCompressSuccess( result );
listener.onCompressSuccess( result );
}
} catch ( Exception e ) { } catch ( Exception e ) {
e.printStackTrace(); e.printStackTrace();
target = null; target = null;
if ( listener != null ) { listener.onCompressFailed( "压缩失败" );
listener.onCompressFailed( "压缩失败" );
}
} finally { } finally {
IOUtils.closeSilently( bos ); IOUtils.closeSilently( bos );
} }
@@ -203,7 +196,6 @@ public class BitmapHelper {
target = bytesToBitmap( result ); target = bytesToBitmap( result );
} catch ( Exception e ) { } catch ( Exception e ) {
e.printStackTrace(); e.printStackTrace();
target = null;
} finally { } finally {
IOUtils.closeSilently( bos ); IOUtils.closeSilently( bos );
} }
@@ -630,26 +622,19 @@ public class BitmapHelper {
*/ */
public static Bitmap getVideoThumbnail( String filePath ) { public static Bitmap getVideoThumbnail( String filePath ) {
Bitmap b = null; Bitmap b = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever(); MediaMetadataRetriever retriever = null;
try { try {
retriever = new MediaMetadataRetriever(); retriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14) retriever.setDataSource(filePath, new HashMap<>());
retriever.setDataSource(filePath, new HashMap<String, String>());
else
retriever.setDataSource(filePath);
// mediaMetadataRetriever.setDataSource(videoPath);
b = retriever.getFrameAtTime(); b = retriever.getFrameAtTime();
} catch ( IllegalArgumentException e ) {
e.printStackTrace();
} catch ( RuntimeException e ) { } catch ( RuntimeException e ) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
retriever.release(); if(retriever != null){
} catch ( RuntimeException e ) { retriever.release();
e.printStackTrace(); }
} catch (IOException e) { } catch ( RuntimeException | IOException e ) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@@ -39,11 +39,7 @@ public final class DeviceIdUtils {
if (TextUtils.isEmpty(deviceId)) { if (TextUtils.isEmpty(deviceId)) {
deviceId = getDeviceIdInternal(appContext); deviceId = getDeviceIdInternal(appContext);
if (TextUtils.isEmpty(deviceId)) { 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) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
}
} else {
deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber(); deviceId = ((TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE)).getSimSerialNumber();
} }
if (TextUtils.isEmpty(deviceId)) { if (TextUtils.isEmpty(deviceId)) {
@@ -65,10 +61,8 @@ public final class DeviceIdUtils {
private static String getDeviceIdInternal(Context context) { private static String getDeviceIdInternal(Context context) {
String id = ""; String id = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return id;
return id;
}
} }
TelephonyManager telephonymanager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); TelephonyManager telephonymanager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
@@ -100,13 +94,7 @@ public final class DeviceIdUtils {
method.setAccessible(true); method.setAccessible(true);
} }
serial = (String) method.invoke(new Build(), "ro.serialno"); serial = (String) method.invoke(new Build(), "ro.serialno");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
return serial; return serial;

View File

@@ -175,7 +175,7 @@ public final class EncryptUtils {
public static byte[] encryptMD5File(final File file) { public static byte[] encryptMD5File(final File file) {
if (file == null) return null; if (file == null) return null;
FileInputStream fis = null; FileInputStream fis = null;
DigestInputStream digestInputStream; DigestInputStream digestInputStream = null;
try { try {
fis = new FileInputStream(file); fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5"); MessageDigest md = MessageDigest.getInstance("MD5");
@@ -191,6 +191,9 @@ public final class EncryptUtils {
return null; return null;
} finally { } finally {
try { try {
if (digestInputStream != null) {
digestInputStream.close();
}
if (fis != null) { if (fis != null) {
fis.close(); fis.close();
} }

View File

@@ -1091,7 +1091,7 @@ public final class FileUtils {
is = new BufferedInputStream(new FileInputStream(file)); is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int readChars; int readChars;
if (LINE_SEP.endsWith("\n")) { if (LINE_SEP != null && LINE_SEP.endsWith("\n")) {
while ((readChars = is.read(buffer, 0, 1024)) != -1) { while ((readChars = is.read(buffer, 0, 1024)) != -1) {
for (int i = 0; i < readChars; ++i) { for (int i = 0; i < readChars; ++i) {
if (buffer[i] == '\n') ++count; if (buffer[i] == '\n') ++count;
@@ -1442,13 +1442,8 @@ public final class FileUtils {
StatFs statFs = new StatFs(anyPathInFs); StatFs statFs = new StatFs(anyPathInFs);
long blockSize; long blockSize;
long totalSize; long totalSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFs.getBlockSizeLong();
blockSize = statFs.getBlockSizeLong(); totalSize = statFs.getBlockCountLong();
totalSize = statFs.getBlockCountLong();
} else {
blockSize = statFs.getBlockSize();
totalSize = statFs.getBlockCount();
}
return blockSize * totalSize; return blockSize * totalSize;
} }
@@ -1463,13 +1458,8 @@ public final class FileUtils {
StatFs statFs = new StatFs(anyPathInFs); StatFs statFs = new StatFs(anyPathInFs);
long blockSize; long blockSize;
long availableSize; long availableSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = statFs.getBlockSizeLong();
blockSize = statFs.getBlockSizeLong(); availableSize = statFs.getAvailableBlocksLong();
availableSize = statFs.getAvailableBlocksLong();
} else {
blockSize = statFs.getBlockSize();
availableSize = statFs.getAvailableBlocks();
}
return blockSize * availableSize; return blockSize * availableSize;
} }
@@ -1558,8 +1548,6 @@ public final class FileUtils {
byte[] bytes = new byte[in.available()]; byte[] bytes = new byte[in.available()];
int length = in.read(bytes); int length = in.read(bytes);
base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT); base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@@ -1709,53 +1697,49 @@ public final class FileUtils {
* @param listener * @param listener
*/ */
public static void copy(final InputStream is, final String to, final FileCopyListener listener) { public static void copy(final InputStream is, final String to, final FileCopyListener listener) {
new Thread(new Runnable() { new Thread(() -> {
@Override Log.w("FileUtils", "======copy======");
public void run() {
Log.w("FileUtils", "======copy======");
if (listener != null) { if (listener != null) {
listener.onStart(); 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(); while ((rc = is.read(buff, 0, 1024)) > 0) {
long process = 0; process += rc;
fos.write(buff, 0, rc);
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) {
if (listener != null) { if (listener != null) {
listener.onFail(e); listener.onProcess(((int) (((float) process) * 100 / fileSize)));
return;
} }
} }
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
if (listener != null) { if (listener != null) {
listener.onFinish(to); listener.onFail(e);
return;
} }
} }
if (listener != null) {
listener.onFinish(to);
}
}).start(); }).start();
} }
@@ -1767,74 +1751,71 @@ public final class FileUtils {
* @param listener * @param listener
*/ */
public static void copy(final String from, final String to, final FileCopyListener listener) { public static void copy(final String from, final String to, final FileCopyListener listener) {
new Thread(new Runnable() { new Thread(() -> {
@Override File file = null;
public void run() { try {
File file = null; file = new File(from);
try { } catch (Exception e) {
file = new File(from); if (listener != null) {
} catch (Exception e) { listener.onFail(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; return;
} }
if (!file.isFile()) { }
if (listener != null) { if (!file.exists()) {
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 (listener != null) { 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(); FileOutputStream fos = new FileOutputStream(toFile);
long process = 0;
try { while ((rc = fis.read(buff, 0, 1024)) > 0) {
FileInputStream fis = new FileInputStream(file); process += rc;
fos.write(buff, 0, rc);
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) {
if (listener != null) { if (listener != null) {
listener.onFail(e); listener.onProcess(((int) (((float) process) * 100 / fileSize)));
return;
} }
} }
fos.flush();
fos.close();
fis.close();
} catch (Exception e) {
if (listener != null) { if (listener != null) {
listener.onFinish(to); listener.onFail(e);
return;
} }
} }
if (listener != null) {
listener.onFinish(to);
}
}).start(); }).start();
} }

View File

@@ -58,7 +58,7 @@ public final class ProcessUtils {
public static String getForegroundProcessName() { public static String getForegroundProcessName() {
ActivityManager am = ActivityManager am =
(ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE); (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
//noinspection ConstantConditions //noinspection Constant Conditions
List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses(); List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses();
if (pInfo != null && pInfo.size() > 0) { if (pInfo != null && pInfo.size() > 0) {
for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) { 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();
PackageManager pm = Utils.getApp().getPackageManager(); Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); List<ResolveInfo> list =
List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); Log.i("ProcessUtils", list.toString());
Log.i("ProcessUtils", list.toString()); if (list.size() <= 0) {
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", Log.i("ProcessUtils",
"getForegroundProcessName: noun of access to usage information."); "getForegroundProcessName: refuse to device usage stats.");
return ""; return "";
} }
try {// Access to usage information. UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp()
ApplicationInfo info = .getSystemService(Context.USAGE_STATS_SERVICE);
pm.getApplicationInfo(Utils.getApp().getPackageName(), 0); List<UsageStats> usageStatsList = null;
AppOpsManager aom = if (usageStatsManager != null) {
(AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE); long endTime = System.currentTimeMillis();
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, long beginTime = endTime - 86400000 * 7;
info.uid, usageStatsList = usageStatsManager
info.packageName) != AppOpsManager.MODE_ALLOWED) { .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); beginTime, endTime);
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<UsageStats> 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();
} }
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 ""; return "";
} }
@@ -223,9 +221,8 @@ public final class ProcessUtils {
} }
private static String getCurrentProcessNameByFile() { private static String getCurrentProcessNameByFile() {
try { File file = new File("/proc/" + Process.myPid() + "/" + "cmdline");
File file = new File("/proc/" + Process.myPid() + "/" + "cmdline"); try(BufferedReader mBufferedReader = new BufferedReader(new FileReader(file))) {
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim(); String processName = mBufferedReader.readLine().trim();
mBufferedReader.close(); mBufferedReader.close();
return processName; return processName;
@@ -301,7 +298,7 @@ public final class ProcessUtils {
} }
public static String getPackageName() { public static String getPackageName() {
String packageName = null; String packageName;
BufferedReader reader = null; BufferedReader reader = null;
try { try {

View File

@@ -393,7 +393,6 @@ public final class RomUtils {
} }
private static String getSystemPropertyByShell(final String propName) { private static String getSystemPropertyByShell(final String propName) {
String line;
BufferedReader input = null; BufferedReader input = null;
try { try {
Process p = Runtime.getRuntime().exec("getprop " + propName); Process p = Runtime.getRuntime().exec("getprop " + propName);
@@ -414,11 +413,9 @@ public final class RomUtils {
} }
private static String getSystemPropertyByStream(final String key) { private static String getSystemPropertyByStream(final String key) {
try { try( FileInputStream is = new FileInputStream(
new File(Environment.getRootDirectory(), "build.prop"))) {
Properties prop = new Properties(); Properties prop = new Properties();
FileInputStream is = new FileInputStream(
new File(Environment.getRootDirectory(), "build.prop")
);
prop.load(is); prop.load(is);
return prop.getProperty(key, ""); return prop.getProperty(key, "");
} catch (Exception ignore) {/**/} } catch (Exception ignore) {/**/}

View File

@@ -11,16 +11,15 @@ public final class SystemPropertiesUtils {
public static String getProperty(String key, String defaultValue) { public static String getProperty(String key, String defaultValue) {
String value = defaultValue; String value = defaultValue;
try { try {
Class<?> c = Class.forName(CLASS_NAME); Class<?> c = Class.forName(CLASS_NAME);
Method get = c.getMethod("get", String.class, String.class); Method get = c.getMethod("get", String.class, String.class);
value = (String) (get.invoke(c, key, defaultValue)); value = (String) (get.invoke(c, key, defaultValue));
return value;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
return value;
} }
return value;
} }
public static void setProperty(String key, String value) { public static void setProperty(String key, String value) {

View File

@@ -19,11 +19,14 @@ public final class TimeTransformUtils {
int hours = totalSeconds / 3600; int hours = totalSeconds / 3600;
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault()); Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
String formatStr;
if (hours > 0) { if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString(); formatStr = mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else { } 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) { public static String stringForTimeWithHours(int timeMs) {
@@ -36,7 +39,9 @@ public final class TimeTransformUtils {
int hours = totalSeconds / 3600; int hours = totalSeconds / 3600;
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault()); 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;
} }

View File

@@ -62,18 +62,11 @@ public final class ZipUtils {
final String comment) final String comment)
throws IOException { throws IOException {
if (srcFilePaths == null || zipFilePath == null) return false; if (srcFilePaths == null || zipFilePath == null) return false;
ZipOutputStream zos = null; try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
try {
zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String srcFile : srcFilePaths) { for (String srcFile : srcFilePaths) {
if (!zipFile(UtilsBridge.getFileByPath(srcFile), "", zos, comment)) return false; if (!zipFile(UtilsBridge.getFileByPath(srcFile), "", zos, comment)) return false;
} }
return true; return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
} }
} }
@@ -104,18 +97,11 @@ public final class ZipUtils {
final String comment) final String comment)
throws IOException { throws IOException {
if (srcFiles == null || zipFile == null) return false; if (srcFiles == null || zipFile == null) return false;
ZipOutputStream zos = null; try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (File srcFile : srcFiles) { for (File srcFile : srcFiles) {
if (!zipFile(srcFile, "", zos, comment)) return false; if (!zipFile(srcFile, "", zos, comment)) return false;
} }
return true; return true;
} finally {
if (zos != null) {
zos.finish();
zos.close();
}
} }
} }
@@ -177,14 +163,8 @@ public final class ZipUtils {
final String comment) final String comment)
throws IOException { throws IOException {
if (srcFile == null || zipFile == null) return false; if (srcFile == null || zipFile == null) return false;
ZipOutputStream zos = null; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
return zipFile(srcFile, "", zos, comment); return zipFile(srcFile, "", zos, comment);
} finally {
if (zos != null) {
zos.close();
}
} }
} }
@@ -207,22 +187,16 @@ public final class ZipUtils {
} }
} }
} else { } else {
InputStream is = null; try (InputStream is = new BufferedInputStream(new FileInputStream(srcFile))) {
try {
is = new BufferedInputStream(new FileInputStream(srcFile));
ZipEntry entry = new ZipEntry(rootPath); ZipEntry entry = new ZipEntry(rootPath);
entry.setComment(comment); entry.setComment(comment);
zos.putNextEntry(entry); zos.putNextEntry(entry);
byte buffer[] = new byte[BUFFER_LEN]; byte[] buffer = new byte[BUFFER_LEN];
int len; int len;
while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) { while ((len = is.read(buffer, 0, BUFFER_LEN)) != -1) {
zos.write(buffer, 0, len); zos.write(buffer, 0, len);
} }
zos.closeEntry(); zos.closeEntry();
} finally {
if (is != null) {
is.close();
}
} }
} }
return true; return true;
@@ -330,23 +304,12 @@ public final class ZipUtils {
return UtilsBridge.createOrExistsDir(file); return UtilsBridge.createOrExistsDir(file);
} else { } else {
if (!UtilsBridge.createOrExistsFile(file)) return false; if (!UtilsBridge.createOrExistsFile(file)) return false;
InputStream in = null; try (InputStream in = new BufferedInputStream(zip.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
OutputStream out = null; byte[] buffer = new byte[BUFFER_LEN];
try {
in = new BufferedInputStream(zip.getInputStream(entry));
out = new BufferedOutputStream(new FileOutputStream(file));
byte buffer[] = new byte[BUFFER_LEN];
int len; int len;
while ((len = in.read(buffer)) != -1) { while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len); out.write(buffer, 0, len);
} }
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} }
} }
return true; return true;

View File

@@ -6,13 +6,13 @@ import java.io.DataInputStream;
import java.io.IOException; import java.io.IOException;
public class M3DCar { public class M3DCar {
private Context context; private final Context context;
private int resid; private final int redis;
public byte[] totBuffer = null; public byte[] totBuffer = null;
public int totSize = 0; public int totSize = 0;
public M3DCar(Context context, int resid) { public M3DCar(Context context, int redis) {
this.resid = resid; this.redis = redis;
this.context = context; this.context = context;
loadData(); loadData();
} }
@@ -20,12 +20,12 @@ public class M3DCar {
private void loadData() { private void loadData() {
if (null != totBuffer) if (null != totBuffer)
return; return;
DataInputStream dis = new DataInputStream(context.getResources().openRawResource(resid)); ;
int curTotSize = 64 * 1024; int curTotSize = 64 * 1024;
totBuffer = new byte[curTotSize]; totBuffer = new byte[curTotSize];
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int size = 0; int size;
try { try(DataInputStream dis = new DataInputStream(context.getResources().openRawResource(redis))) {
while ((size = dis.read(buffer)) >= 0) { while ((size = dis.read(buffer)) >= 0) {
if (totSize + size > curTotSize) { if (totSize + size > curTotSize) {
curTotSize = (totSize + size) * 3 / 2; curTotSize = (totSize + size) * 3 / 2;
@@ -36,8 +36,8 @@ public class M3DCar {
System.arraycopy(buffer, 0, totBuffer, totSize, size); System.arraycopy(buffer, 0, totBuffer, totSize, size);
totSize += size; totSize += size;
} }
dis.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace();
} }
} }
} }

View File

@@ -23,8 +23,8 @@ public class DirectionLayer extends ImageView implements MapStatusListener {
private static final String TAG = "DirectionLayer"; private static final String TAG = "DirectionLayer";
private Drawable icon; private Drawable icon;
private IMapController mMapController; private IMapController mMapController;
private Matrix matrix = new Matrix(); private final Matrix matrix = new Matrix();
private Camera mCamera = new Camera(); private final Camera mCamera = new Camera();
public DirectionLayer(Context context){ public DirectionLayer(Context context){
super(context); super(context);

View File

@@ -7,7 +7,7 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
public class MainInfo { 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 static MainInfo m_hinst = null;
private boolean mbUserLog = true; private boolean mbUserLog = true;
private static boolean mbDebug = false; private static boolean mbDebug = false;
@@ -33,11 +33,9 @@ public class MainInfo {
if (null == dir) { if (null == dir) {
return; return;
} }
try { try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) {
FileWriter fw = new FileWriter((dir + "log.txt"), true);
String date = dateFormat.format(new Date()); String date = dateFormat.format(new Date());
fw.write(date + " " + log + "\r\n"); fw.write(date + " " + log + "\r\n");
fw.close();
} catch (Exception ex) { } catch (Exception ex) {
} }
} }
@@ -50,10 +48,8 @@ public class MainInfo {
if (null == dir) { if (null == dir) {
return; return;
} }
try { try(FileWriter fw = new FileWriter((dir + "log.txt"), true)) {
FileWriter fw = new FileWriter((dir + "log.txt"), true);
e.printStackTrace(new PrintWriter(fw)); e.printStackTrace(new PrintWriter(fw));
fw.close();
} catch (Exception ex) { } catch (Exception ex) {
} }
} }

View File

@@ -79,7 +79,9 @@ public class BaseSDCardHelper {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
bos.close(); if (bos != null) {
bos.close();
}
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@@ -108,7 +110,9 @@ public class BaseSDCardHelper {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
bos.close(); if (bos != null) {
bos.close();
}
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@@ -134,7 +138,9 @@ public class BaseSDCardHelper {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
bos.close(); if(bos != null){
bos.close();
}
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@@ -160,7 +166,9 @@ public class BaseSDCardHelper {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { try {
bos.close(); if(bos != null){
bos.close();
}
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@@ -177,9 +185,9 @@ public class BaseSDCardHelper {
try { try {
bis = new BufferedInputStream( bis = new BufferedInputStream(
new FileInputStream(new File(fileDir))); new FileInputStream(fileDir));
byte[] buffer = new byte[8 * 1024]; byte[] buffer = new byte[8 * 1024];
int c = 0; int c;
while ((c = bis.read(buffer)) != -1) { while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c); baos.write(buffer, 0, c);
baos.flush(); baos.flush();
@@ -237,27 +245,27 @@ public class BaseSDCardHelper {
* 删除文件夹 * 删除文件夹
* @param path * @param path
*/ */
public static boolean deleteAllFilesOfDir(File path) { public static boolean deleteAllFilesOfDir(File path) {
if (!path.exists()){ if (!path.exists()){
return false; return false;
} }
if (path.isFile()) { if (path.isFile()) {
path.delete(); return path.delete();
return true;
} }
File[] files = path.listFiles(); File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) { if(files != null){
deleteAllFilesOfDir(files[i]); for (File file : files) {
deleteAllFilesOfDir(file);
}
} }
path.delete();
System.out.println("删除文件夹成功"); System.out.println("删除文件夹成功");
return true; return path.delete();
} }
/** /**
* 删除文件夹2 * 删除文件夹2
* @param path * @param path
*/ */
public static void deleteAllFilesOfDir2(File path) { public static void deleteAllFilesOfDir2(File path) {
if (!path.exists()){ if (!path.exists()){
return ; return ;
} }
@@ -266,8 +274,10 @@ public class BaseSDCardHelper {
return ; return ;
} }
File[] files = path.listFiles(); File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) { if(files != null){
deleteAllFilesOfDir(files[i]); for (File file : files) {
deleteAllFilesOfDir(file);
}
} }
path.delete(); path.delete();
System.out.println("删除文件夹成功"); System.out.println("删除文件夹成功");

View File

@@ -36,7 +36,6 @@ public class SubscribeInterface {
public SubscribeInterface(@NonNull OnSubscribeInterfaceListener listener) { public SubscribeInterface(@NonNull OnSubscribeInterfaceListener listener) {
this.listener = listener; this.listener = listener;
if (listener == null) throw new RuntimeException();
init(); init();
} }
@@ -62,10 +61,8 @@ public class SubscribeInterface {
* @param role 角色 详情参见{@link Constants.TERMINAL_ROLE} * @param role 角色 详情参见{@link Constants.TERMINAL_ROLE}
* @param type 注册类型 详情参见{@link Constants.SUBSCRIBE_TYPE} * @param type 注册类型 详情参见{@link Constants.SUBSCRIBE_TYPE}
* @param messageTypes 要操作的接口 * @param messageTypes 要操作的接口
* @return
*/ */
public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull Set<MessageType> messageTypes) { public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull Set<MessageType> messageTypes) {
if (messageTypes == null) return false;
MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder(); MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder();
builder.setRole(role).setReqType(type); builder.setRole(role).setReqType(type);
Map<MessageType, Integer> temp = new HashMap<>(); Map<MessageType, Integer> temp = new HashMap<>();
@@ -89,9 +86,7 @@ public class SubscribeInterface {
} }
} }
} }
return isSendSucceed;
return false;
} }
/** /**
@@ -103,7 +98,6 @@ public class SubscribeInterface {
* @return 是否加入ws发送队列 * @return 是否加入ws发送队列
*/ */
public boolean subscribeInterface(@Define.TerminalRole int role, @Define.SubscribeType int type, @NonNull MessageType messageType) { 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(); MessagePad.SubscribeDataReq.Builder builder = MessagePad.SubscribeDataReq.newBuilder();
builder.setRole(role).setReqType(type).addDataTypes(messageType.typeCode.getNumber()); builder.setRole(role).setReqType(type).addDataTypes(messageType.typeCode.getNumber());
boolean isSendSucceed = listener.onSendSubscribe(builder.build().toByteArray()); boolean isSendSucceed = listener.onSendSubscribe(builder.build().toByteArray());
@@ -120,7 +114,7 @@ public class SubscribeInterface {
subscribedInterface.remove(messageType); subscribedInterface.remove(messageType);
} }
} }
return false; return isSendSucceed;
} }
//根据参数查询是否已订阅 //根据参数查询是否已订阅

View File

@@ -68,7 +68,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
private int curTtsLevel = -1; private int curTtsLevel = -1;
// 由于主动打断不会有回调事件所以主动打断时清掉map中被打断的text和callback // 由于主动打断不会有回调事件所以主动打断时清掉map中被打断的text和callback
private String curTtsContent = ""; private String curTtsContent = "";
private LinkedList<Pair<String, Integer>> linkedList = new LinkedList<>(); private final LinkedList<Pair<String, Integer>> linkedList = new LinkedList<>();
public void release() { public void release() {
CallerLogger.d(TAG, "release"); CallerLogger.d(TAG, "release");
@@ -101,13 +101,13 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
private VoiceClient mVoiceClient; private VoiceClient mVoiceClient;
private MogoVoiceManager mogoVoiceManager; private MogoVoiceManager mogoVoiceManager;
// 免唤醒指令 // 免唤醒指令
private Map<String, List<IMogoTTSCallback>> mCmdMap = new HashMap<>(); private final Map<String, List<IMogoTTSCallback>> mCmdMap = new HashMap<>();
// 问答指令 // 问答指令
private Map<String, IMogoTTSCallback> mQAndAMap = new HashMap<>(); private final Map<String, IMogoTTSCallback> mQAndAMap = new HashMap<>();
// 单独的语音播放 // 单独的语音播放
private Map<String, IMogoTTSCallback> mSpeakVoiceMap = new HashMap<>(); private final Map<String, IMogoTTSCallback> mSpeakVoiceMap = new HashMap<>();
private Map<String, String[]> mCacheUnWakeupCommands = new ConcurrentHashMap<>(); private final Map<String, String[]> mCacheUnWakeupCommands = new ConcurrentHashMap<>();
private static final String TTS_BACK_RES_ZHILING = "zhilingf_common_back_ce_local.v2.1.0.bin"; private static final String TTS_BACK_RES_ZHILING = "zhilingf_common_back_ce_local.v2.1.0.bin";
private int audioRecorderType = DUILiteConfig.TYPE_COMMON_MIC; 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"; public static final String TTS_BACK_RES_GUODGM = "guodgm_common_back_ce_local.v2.1.0.bin";
private AILocalTTSEngine mEngine; private AILocalTTSEngine mEngine;
private AILocalTTSIntent mAILocalTTSIntent; 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 boolean mHasAuth;
private int retryCount; private int retryCount;
@@ -277,8 +277,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/** /**
* 是否语音注册成功 * 是否语音注册成功
*
* @return
*/ */
@Override @Override
public boolean hasFlush() { public boolean hasFlush() {
@@ -363,8 +361,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/** /**
* 语音播报 * 语音播报
*
* @param text
*/ */
public void speakTTSVoice(String text, IMogoTTSCallback callBack) { public void speakTTSVoice(String text, IMogoTTSCallback callBack) {
if (mEngine != null && mHasAuth) { if (mEngine != null && mHasAuth) {
@@ -376,9 +372,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
public void stopSpeakTts(String text) { public void stopSpeakTts(String text) {
if (mEngine != null && mHasAuth) { if (mEngine != null && mHasAuth) {
if (mSpeakVoiceMap.containsKey(text)) { mSpeakVoiceMap.remove(text);
mSpeakVoiceMap.remove(text);
}
curTtsContent = ""; curTtsContent = "";
curTtsLevel = -1; curTtsLevel = -1;
mEngine.stop(); mEngine.stop();
@@ -387,9 +381,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
public void stopTts() { public void stopTts() {
if (mEngine != null && mHasAuth) { if (mEngine != null && mHasAuth) {
if (mSpeakVoiceMap.containsKey(curTtsContent)) { mSpeakVoiceMap.remove(curTtsContent);
mSpeakVoiceMap.remove(curTtsContent);
}
// tts过程中调用stop不会有回调事件 // tts过程中调用stop不会有回调事件
curTtsContent = ""; curTtsContent = "";
curTtsLevel = -1; curTtsLevel = -1;
@@ -399,8 +391,6 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
/** /**
* 语音播报 * 语音播报
*
* @param text
*/ */
public void speakTTSVoice(String text) { public void speakTTSVoice(String text) {
CallerLogger.d(TAG, "speakTTSVoice"); CallerLogger.d(TAG, "speakTTSVoice");
@@ -493,24 +483,24 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
initFlushStatus(); initFlushStatus();
if (mHasFlush) { if (mHasFlush) {
mSpeakVoiceMap.put(text, callBack); 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); 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 ); // mVoiceClient.speakTypeText( text, preemptType );
} }
} catch (Exception e) { } catch (Exception e) {
@@ -679,7 +669,7 @@ public class PadTTS implements IMogoTTS, VoiceClient.VoiceCmdCallBack, OnTtsList
CallerLogger.d(TAG, "txz is voiceServiceReady"); CallerLogger.d(TAG, "txz is voiceServiceReady");
return true; return true;
} }
return true; return false;
} }
public void speakTTSAndDuck(String text) { public void speakTTSAndDuck(String text) {