提交 37fd0e2f 编写于 作者: B Blankj

see 05/09 log

上级 f61eb1a9
......@@ -27,7 +27,7 @@ gradlePlugin {
dependencies {
implementation "com.android.tools.build:gradle:3.4.0"
implementation 'com.android.tools.build:gradle-api:3.4.0'
implementation "com.android.tools.build:gradle-api:3.4.0"
implementation dep.javassist
implementation dep.commons_io
......
package com.blankj.bus
import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.blankj.util.JavassistUtils
import com.blankj.util.JsonUtils
import com.blankj.util.LogUtils
import com.google.common.base.Preconditions
import org.apache.commons.io.FileUtils
import org.gradle.api.Project
import java.util.function.Predicate
class BusTransformAsm extends Transform {
Project mProject;
BusTransformAsm(Project project) {
mProject = project
}
@Override
String getName() {
return "busTransform"
}
@Override
Set<QualifiedContent.ContentType> getInputTypes() {
return TransformManager.CONTENT_CLASS
}
@Override
Set<? super QualifiedContent.Scope> getScopes() {
return TransformManager.SCOPE_FULL_PROJECT
}
@Override
boolean isIncremental() {
return true
}
@Override
void transform(TransformInvocation transformInvocation)
throws TransformException, InterruptedException, IOException {
super.transform(transformInvocation)
def outputProvider = transformInvocation.getOutputProvider()
Preconditions.checkNotNull(outputProvider, "Missing output object for transform " + getName());
LogUtils.l(getName() + " started")
long stTime = System.currentTimeMillis();
def inputs = transformInvocation.getInputs()
def referencedInputs = transformInvocation.getReferencedInputs()
def isIncremental = transformInvocation.isIncremental()
if(!isIncremental) {
outputProvider.deleteAll();
}
JavassistUtils.init(mProject)
BusScan busScan = new BusScan()
for (TransformInput input : transformInvocation.getInputs()) {
for (DirectoryInput dirInput : input.getDirectoryInputs()) {// 遍历文件夹
File dir = dirInput.file
JavassistUtils.getPool().appendClassPath(dir.absolutePath)
def dest = outputProvider.getContentLocation(
dirInput.name,
dirInput.contentTypes,
dirInput.scopes,
Format.DIRECTORY
)
FileUtils.copyDirectory(dir, dest)
LogUtils.l("scan dir: $dir [$dest]")
if(isIncremental) {
switch(status) {
case Status.NOTCHANGED:
break;
case Status.ADDED:
case Status.CHANGED:
transformJar(jarInput.getFile(), dest, status);
break;
case Status.REMOVED:
if (dest.exists()) {
FileUtils.forceDelete(dest);
}
break;
}
} else {
//Forgive me!, Some project will store 3rd-party aar for serveral copies in dexbuilder folder,,unknown issue.
if(inDuplcatedClassSafeMode() & !isIncremental && !flagForCleanDexBuilderFolder) {
cleanDexBuilderFolder(dest);
flagForCleanDexBuilderFolder = true;
}
transformJar(jarInput.getFile(), dest, status);
}
busScan.scanDir(dir)
}// 遍历文件夹结束
for (JarInput jarInput : input.getJarInputs()) {// 遍历 jar 文件
File jar = jarInput.file
JavassistUtils.getPool().appendClassPath(jarInput.file.absolutePath)
def jarName = jarInput.name
def dest = outputProvider.getContentLocation(
jarName,
jarInput.contentTypes,
jarInput.scopes,
Format.JAR
)
FileUtils.copyFile(jar, dest)
if (jarName.startsWith("com.blankj:utilcode:")
|| jarName.startsWith("com.blankj:utilcodex:")
|| jarName.contains("utilcode-lib")) {
busScan.busJar = dest
LogUtils.l("bus jar: $jarName [$dest]")
return
}
if (jumpScan(jarName)) {
LogUtils.l("jump jar: $jarName [$dest]")
return
}
LogUtils.l("scan jar: $jarName [$dest]")
busScan.scanJar(jar)
}
}// 遍历 jar 文件结束
if (busScan.busJar != null) {
File jsonFile = new File(mProject.projectDir.getAbsolutePath(), "__bus__.json")
String busJson = JsonUtils.getFormatJson(busScan.busStaticMap)
LogUtils.l(jsonFile.toString() + ": " + busJson)
FileUtils.write(jsonFile, busJson)
BusInject.start(busScan.busStaticMap, busScan.busJar)
} else {
LogUtils.l('u should <implementation "com.blankj:utilcode:1.22.+">')
}
LogUtils.l(getName() + " finished: " + (System.currentTimeMillis() - stTime) + "ms")
}
private static boolean jumpScan(String jarName) {
boolean isExcept = false
for (String except : Config.EXCEPTS) {
if (jarName.startsWith(except)) {
isExcept = true
break
}
}
isExcept
}
}
\ No newline at end of file
......@@ -89,8 +89,8 @@ public abstract class BaseActivity extends AppCompatActivity
swipeLayout.setOnFullSwipeListener(new SwipePanel.OnFullSwipeListener() {
@Override
public void onFullSwipe(int direction) {
finish();
swipeLayout.close(direction);
finish();
}
});
}
......
......@@ -72,7 +72,7 @@ public class BaseApplication extends Application {
.setSingleTagSwitch(true)// 一条日志仅输出一条,默认开,为美化 AS 3.1 的 Logcat
.setConsoleFilter(LogUtils.V)// log 的控制台过滤器,和 logcat 过滤器同理,默认 Verbose
.setFileFilter(LogUtils.V)// log 文件过滤器,和 logcat 过滤器同理,默认 Verbose
.setStackDeep(1)// log 栈深度,默认为 1
.setStackDeep(100)// log 栈深度,默认为 1
.setStackOffset(0)// 设置栈偏移,比如二次封装的话就需要设置,默认为 0
.setSaveDays(3)// 设置日志可保留天数,默认为 -1 表示无限时长
// 新增 ArrayList 格式化器,默认已支持 Array, Throwable, Bundle, Intent 的格式化输出
......@@ -81,7 +81,8 @@ public class BaseApplication extends Application {
public String format(ArrayList arrayList) {
return "LogUtils Formatter ArrayList { " + arrayList.toString() + " }";
}
});
})
.setFileWriter(null);
LogUtils.i(config.toString());
}
......
......@@ -21,9 +21,6 @@ import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
......@@ -253,20 +250,7 @@ public final class BusUtils {
}
private static boolean isMainProcess() {
return Utils.getApp().getPackageName().equals(getCurrentProcessName());
}
private static String getCurrentProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
return Utils.getApp().getPackageName().equals(Utils.getCurrentProcessName());
}
private static boolean isAppInstalled(@NonNull final String pkgName) {
......@@ -340,7 +324,7 @@ public final class BusUtils {
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("BusUtils", "client service connected " + name);
mServer = new Messenger(service);
int key = getCurrentProcessName().hashCode();
int key = Utils.getCurrentProcessName().hashCode();
Message msg = Message.obtain(mReceiveServeMsgHandler, WHAT_SUBSCRIBE, key, 0);
msg.replyTo = mClient;
try {
......
......@@ -23,10 +23,8 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
......@@ -609,47 +607,52 @@ public final class LogUtils {
}
private static void input2File(final String input, final String filePath) {
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(filePath, true));
bw.write(input);
} catch (IOException e) {
e.printStackTrace();
Log.e("LogUtils", "log to " + filePath + " failed!");
} finally {
if (CONFIG.mFileWriter == null) {
EXECUTOR.execute(new Runnable() {
@Override
public void run() {
BufferedWriter bw = null;
try {
if (bw != null) {
bw.close();
}
bw = new BufferedWriter(new FileWriter(filePath, true));
bw.write(input);
} catch (IOException e) {
e.printStackTrace();
Log.e("LogUtils", "log to " + filePath + " failed!");
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
});
} else {
CONFIG.mFileWriter.write(filePath, input);
}
}
public static 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 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 = getCurrentProcessName();
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 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 = Utils.getCurrentProcessName();
private IFileWriter mFileWriter;
private Config() {
if (mDefaultDir != null) return;
......@@ -661,17 +664,17 @@ public final class LogUtils {
}
}
public Config setLogSwitch(final boolean logSwitch) {
public final Config setLogSwitch(final boolean logSwitch) {
mLogSwitch = logSwitch;
return this;
}
public Config setConsoleSwitch(final boolean consoleSwitch) {
public final Config setConsoleSwitch(final boolean consoleSwitch) {
mLog2ConsoleSwitch = consoleSwitch;
return this;
}
public Config setGlobalTag(final String tag) {
public final Config setGlobalTag(final String tag) {
if (isSpace(tag)) {
mGlobalTag = "";
mTagIsSpace = true;
......@@ -682,17 +685,17 @@ public final class LogUtils {
return this;
}
public Config setLogHeadSwitch(final boolean logHeadSwitch) {
public final Config setLogHeadSwitch(final boolean logHeadSwitch) {
mLogHeadSwitch = logHeadSwitch;
return this;
}
public Config setLog2FileSwitch(final boolean log2FileSwitch) {
public final Config setLog2FileSwitch(final boolean log2FileSwitch) {
mLog2FileSwitch = log2FileSwitch;
return this;
}
public Config setDir(final String dir) {
public final Config setDir(final String dir) {
if (isSpace(dir)) {
mDir = null;
} else {
......@@ -701,12 +704,12 @@ public final class LogUtils {
return this;
}
public Config setDir(final File dir) {
public final Config setDir(final File dir) {
mDir = dir == null ? null : (dir.getAbsolutePath() + FILE_SEP);
return this;
}
public Config setFilePrefix(final String filePrefix) {
public final Config setFilePrefix(final String filePrefix) {
if (isSpace(filePrefix)) {
mFilePrefix = "util";
} else {
......@@ -715,37 +718,37 @@ public final class LogUtils {
return this;
}
public Config setBorderSwitch(final boolean borderSwitch) {
public final Config setBorderSwitch(final boolean borderSwitch) {
mLogBorderSwitch = borderSwitch;
return this;
}
public Config setSingleTagSwitch(final boolean singleTagSwitch) {
public final Config setSingleTagSwitch(final boolean singleTagSwitch) {
mSingleTagSwitch = singleTagSwitch;
return this;
}
public Config setConsoleFilter(@TYPE final int consoleFilter) {
public final Config setConsoleFilter(@TYPE final int consoleFilter) {
mConsoleFilter = consoleFilter;
return this;
}
public Config setFileFilter(@TYPE final int fileFilter) {
public final Config setFileFilter(@TYPE final int fileFilter) {
mFileFilter = fileFilter;
return this;
}
public Config setStackDeep(@IntRange(from = 1) final int stackDeep) {
public final Config setStackDeep(@IntRange(from = 1) final int stackDeep) {
mStackDeep = stackDeep;
return this;
}
public Config setStackOffset(@IntRange(from = 0) final int stackOffset) {
public final Config setStackOffset(@IntRange(from = 0) final int stackOffset) {
mStackOffset = stackOffset;
return this;
}
public Config setSaveDays(@IntRange(from = 1) final int saveDays) {
public final Config setSaveDays(@IntRange(from = 1) final int saveDays) {
mSaveDays = saveDays;
return this;
}
......@@ -757,84 +760,76 @@ public final class LogUtils {
return this;
}
public String getProcessName() {
public final Config setFileWriter(final IFileWriter fileWriter) {
mFileWriter = fileWriter;
return this;
}
public final String getProcessName() {
return mProcessName;
}
public String getDefaultDir() {
public final String getDefaultDir() {
return mDefaultDir;
}
public String getDir() {
public final String getDir() {
return mDir == null ? mDefaultDir : mDir;
}
public String getFilePrefix() {
public final String getFilePrefix() {
return mFilePrefix;
}
public boolean isLogSwitch() {
public final boolean isLogSwitch() {
return mLogSwitch;
}
public boolean isLog2ConsoleSwitch() {
public final boolean isLog2ConsoleSwitch() {
return mLog2ConsoleSwitch;
}
public String getGlobalTag() {
public final String getGlobalTag() {
if (isSpace(mGlobalTag)) return "";
return mGlobalTag;
}
public boolean isLogHeadSwitch() {
public final boolean isLogHeadSwitch() {
return mLogHeadSwitch;
}
public boolean isLog2FileSwitch() {
public final boolean isLog2FileSwitch() {
return mLog2FileSwitch;
}
public boolean isLogBorderSwitch() {
public final boolean isLogBorderSwitch() {
return mLogBorderSwitch;
}
public boolean isSingleTagSwitch() {
public final boolean isSingleTagSwitch() {
return mSingleTagSwitch;
}
public char getConsoleFilter() {
public final char getConsoleFilter() {
return T[mConsoleFilter - V];
}
public char getFileFilter() {
public final char getFileFilter() {
return T[mFileFilter - V];
}
public int getStackDeep() {
public final int getStackDeep() {
return mStackDeep;
}
public int getStackOffset() {
public final int getStackOffset() {
return mStackOffset;
}
public int getSaveDays() {
public final int getSaveDays() {
return mSaveDays;
}
private static String getCurrentProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName.replace(":", "_");
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
@Override
public String toString() {
return "process: " + getProcessName()
......@@ -860,7 +855,11 @@ public final class LogUtils {
public abstract String format(T t);
}
private static class TagHead {
public interface IFileWriter {
void write(String file, String content);
}
private final static class TagHead {
String tag;
String[] consoleHead;
String fileHead;
......@@ -872,7 +871,7 @@ public final class LogUtils {
}
}
private static class LogFormatter {
private final static class LogFormatter {
static String object2String(Object object) {
if (object.getClass().isArray()) return array2String(object);
......
......@@ -14,9 +14,6 @@ import android.support.annotation.NonNull;
import android.support.annotation.RequiresPermission;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
......@@ -200,41 +197,15 @@ public final class ProcessUtils {
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isMainProcess() {
return Utils.getApp().getPackageName().equals(getCurrentProcessName());
return Utils.getApp().getPackageName().equals(Utils.getCurrentProcessName());
}
/**
* Return the name of current process.
* <p>It's faster than ActivityManager.</p>
*
* @return the name of current process
*/
public static String getCurrentProcessName() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
return Utils.getCurrentProcessName();
}
// public static String getCurrentProcessName() {
// ActivityManager am = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
// if (am == null) return "";
// List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
// if (info == null || info.size() == 0) return "";
// int pid = Process.myPid();
// for (ActivityManager.RunningAppProcessInfo aInfo : info) {
// if (aInfo.pid == pid) {
// if (aInfo.processName != null) {
// return aInfo.processName;
// }
// }
// }
// return "";
// }
}
......@@ -12,12 +12,17 @@ import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
......@@ -114,28 +119,6 @@ public final class Utils {
return app;
}
private static Application getApplicationByReflect() {
try {
@SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");
Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
Object app = activityThread.getMethod("getApplication").invoke(thread);
if (app == null) {
throw new NullPointerException("u should init first");
}
return (Application) app;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new NullPointerException("u should init first");
}
static ActivityLifecycleImpl getActivityLifecycle() {
return ACTIVITY_LIFECYCLE;
}
......@@ -189,6 +172,93 @@ public final class Utils {
}
}
static String getCurrentProcessName() {
String name = getCurrentProcessNameByFile();
if (!TextUtils.isEmpty(name)) return name;
name = getCurrentProcessNameByAms();
if (!TextUtils.isEmpty(name)) return name;
name = getCurrentProcessNameByReflect();
return name;
}
///////////////////////////////////////////////////////////////////////////
// private method
///////////////////////////////////////////////////////////////////////////
private static String getCurrentProcessNameByFile() {
try {
File file = new File("/proc/" + android.os.Process.myPid() + "/" + "cmdline");
BufferedReader mBufferedReader = new BufferedReader(new FileReader(file));
String processName = mBufferedReader.readLine().trim();
mBufferedReader.close();
return processName;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String getCurrentProcessNameByAms() {
ActivityManager am = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) return "";
List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
if (info == null || info.size() == 0) return "";
int pid = android.os.Process.myPid();
for (ActivityManager.RunningAppProcessInfo aInfo : info) {
if (aInfo.pid == pid) {
if (aInfo.processName != null) {
return aInfo.processName;
}
}
}
return "";
}
private static String getCurrentProcessNameByReflect() {
String processName = "";
try {
Application app = Utils.getApp();
Field loadedApkField = app.getClass().getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(app);
Field activityThreadField = loadedApk.getClass().getDeclaredField("mActivityThread");
activityThreadField.setAccessible(true);
Object activityThread = activityThreadField.get(loadedApk);
Method getProcessName = activityThread.getClass().getDeclaredMethod("getProcessName");
processName = (String) getProcessName.invoke(activityThread);
} catch (Exception e) {
e.printStackTrace();
}
return processName;
}
private static Application getApplicationByReflect() {
try {
@SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");
Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
Object app = activityThread.getMethod("getApplication").invoke(thread);
if (app == null) {
throw new NullPointerException("u should init first");
}
return (Application) app;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new NullPointerException("u should init first");
}
/**
* Set animators enabled.
*/
private static void setAnimatorsEnabled() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && ValueAnimator.areAnimatorsEnabled()) {
return;
......
......@@ -203,8 +203,7 @@
<activity
android:name=".feature.screen.ScreenActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:launchMode="singleTop" >
</activity>
android:launchMode="singleTop"></activity>
<activity
android:name=".feature.sdcard.SDCardActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册