Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor #108

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

You can watch releases [on Maven](https://oss.sonatype.org/content/groups/public/com/github/markzhai/).


## Version 1.5.1 *(2017-08-19)*

1. refactor this framework;
2. change class `BlockCanaryContext` to `DefaultBlockInterceptor`.


## Version 1.5 *(2017-02-26)*

Debug mode stop monitor.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ public class DemoApplication extends Application {
}
```

Implement your application `BlockCanaryContext` context (strongly recommend you to check all these configs):
Implement your application `BlockInterceptor` context (strongly recommend you to check all these configs, or you can use DefaultBlockInterceptor directly.):
```java
public class AppBlockCanaryContext extends BlockCanaryContext {
public class AppBlockCanaryContext extends BlockInterceptor {

/**
* Implement in your project.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
*/
package com.github.moduth.blockcanary;

import android.os.Environment;
import android.content.Context;
import android.os.Looper;

import com.github.moduth.blockcanary.interceptor.BlockInterceptor;
import com.github.moduth.blockcanary.interceptor.DefaultBlockInterceptor;
import com.github.moduth.blockcanary.internal.BlockInfo;
import com.github.moduth.blockcanary.sampler.CpuSampler;
import com.github.moduth.blockcanary.sampler.StackSampler;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
Expand All @@ -32,54 +34,62 @@ public final class BlockCanaryInternals {
StackSampler stackSampler;
CpuSampler cpuSampler;

/**
* Null object pattern
*/
private static final BlockInterceptor NULL_OBJ = new DefaultBlockInterceptor();

private static BlockCanaryInternals sInstance;
private static BlockCanaryContext sContext;
private static Context sContext;

private List<BlockInterceptor> mInterceptorChain = new LinkedList<>();

public BlockCanaryInternals() {

private BlockCanaryInternals() {
stackSampler = new StackSampler(
Looper.getMainLooper().getThread(),
sContext.provideDumpInterval());

cpuSampler = new CpuSampler(sContext.provideDumpInterval());

setMonitor(new LooperMonitor(new LooperMonitor.BlockListener() {

@Override
public void onBlockEvent(long realTimeStart, long realTimeEnd,
long threadTimeStart, long threadTimeEnd) {
// Get recent thread-stack entries and cpu usage
ArrayList<String> threadStackEntries = stackSampler
.getThreadStackEntries(realTimeStart, realTimeEnd);
if (!threadStackEntries.isEmpty()) {
BlockInfo blockInfo = BlockInfo.newInstance()
.setMainThreadTimeCost(realTimeStart, realTimeEnd, threadTimeStart, threadTimeEnd)
.setCpuBusyFlag(cpuSampler.isCpuBusy(realTimeStart, realTimeEnd))
.setRecentCpuRate(cpuSampler.getCpuRateInfo())
.setThreadStackEntries(threadStackEntries)
.flushString();
LogWriter.save(blockInfo.toString());

if (mInterceptorChain.size() != 0) {
for (BlockInterceptor interceptor : mInterceptorChain) {
interceptor.onBlock(getContext().provideContext(), blockInfo);
}
getInterceptor(0).provideDumpInterval());
cpuSampler = new CpuSampler(getInterceptor(0).provideDumpInterval());
// set Looper printer
monitor = new LooperMonitor(mBlockListener, getInterceptor(0).provideBlockThreshold(), getInterceptor(0).stopWhenDebugging());

LogWriter.cleanObsolete();
}


LooperMonitor.BlockListener mBlockListener = new LooperMonitor.BlockListener() {
@Override
public void onBlockEvent(long realTimeStart, long realTimeEnd, long threadTimeStart, long threadTimeEnd) {
// Get recent thread-stack entries and cpu usage
ArrayList<String> threadStackEntries = stackSampler
.getThreadStackEntries(realTimeStart, realTimeEnd);
if (!threadStackEntries.isEmpty()) {
BlockInfo blockInfo = BlockInfo.newInstance()
.setQualifier(getInterceptor(0).provideQualifier())
.setUid(getInterceptor(0).provideUid())
.setNetwork(getInterceptor(0).provideNetworkType())
.setMainThreadTimeCost(realTimeStart, realTimeEnd, threadTimeStart, threadTimeEnd)
.setCpuBusyFlag(cpuSampler.isCpuBusy(realTimeStart, realTimeEnd))
.setRecentCpuRate(cpuSampler.getCpuRateInfo())
.setThreadStackEntries(threadStackEntries)
.flushString();
LogWriter.save(blockInfo.toString());

if (mInterceptorChain.size() != 0) {
for (BlockInterceptor interceptor : mInterceptorChain) {
interceptor.onBlock(BlockCanaryInternals.getContext(), blockInfo);
}
}
}
}, getContext().provideBlockThreshold(), getContext().stopWhenDebugging()));
}
};

LogWriter.cleanObsolete();
}

/**
* Get BlockCanaryInternals singleton
*
* @return BlockCanaryInternals instance
*/
static BlockCanaryInternals getInstance() {
public static BlockCanaryInternals getInstance() {
if (sInstance == null) {
synchronized (BlockCanaryInternals.class) {
if (sInstance == null) {
Expand All @@ -91,69 +101,32 @@ static BlockCanaryInternals getInstance() {
}

/**
* set {@link BlockCanaryContext} implementation
* set Context
*
* @param context context
* @param context You should pass a Application Context
*/
public static void setContext(BlockCanaryContext context) {
public static void setContext(Context context) {
sContext = context;
}

public static BlockCanaryContext getContext() {
public static Context getContext() {
return sContext;
}

void addBlockInterceptor(BlockInterceptor blockInterceptor) {
mInterceptorChain.add(blockInterceptor);
}

private void setMonitor(LooperMonitor looperPrinter) {
monitor = looperPrinter;
}

long getSampleDelay() {
return (long) (BlockCanaryInternals.getContext().provideBlockThreshold() * 0.8f);
}

static String getPath() {
String state = Environment.getExternalStorageState();
String logPath = BlockCanaryInternals.getContext()
== null ? "" : BlockCanaryInternals.getContext().providePath();

if (Environment.MEDIA_MOUNTED.equals(state)
&& Environment.getExternalStorageDirectory().canWrite()) {
return Environment.getExternalStorageDirectory().getPath() + logPath;
}
return getContext().provideContext().getFilesDir() + BlockCanaryInternals.getContext().providePath();
}

static File detectedBlockDirectory() {
File directory = new File(getPath());
if (!directory.exists()) {
directory.mkdirs();
if ( blockInterceptor != null ) {
mInterceptorChain.add(blockInterceptor);
}
return directory;
}

public static File[] getLogFiles() {
File f = detectedBlockDirectory();
if (f.exists() && f.isDirectory()) {
return f.listFiles(new BlockLogFileFilter());
public BlockInterceptor getInterceptor(int pos) {
if ( pos < 0 || mInterceptorChain.size() <= pos ) {
return NULL_OBJ;
}
return null;
return mInterceptorChain.get(pos) ;
}

private static class BlockLogFileFilter implements FilenameFilter {

private String TYPE = ".log";

BlockLogFileFilter() {

}

@Override
public boolean accept(File dir, String filename) {
return filename.endsWith(TYPE);
}
public long getSampleDelay() {
return (long) (getInterceptor(0).provideBlockThreshold() * 0.8f);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import android.os.Handler;
import android.os.HandlerThread;

final class HandlerThreadFactory {
public final class HandlerThreadFactory {

private static HandlerThreadWrapper sLoopThread = new HandlerThreadWrapper("loop");
private static HandlerThreadWrapper sWriteLogThread = new HandlerThreadWrapper("writer");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@
*/
package com.github.moduth.blockcanary;

import android.os.Environment;
import android.util.Log;

import com.github.moduth.blockcanary.interceptor.BlockInterceptor;
import com.github.moduth.blockcanary.internal.BlockInfo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Locale;
Expand Down Expand Up @@ -66,7 +69,7 @@ public static void cleanObsolete() {
@Override
public void run() {
long now = System.currentTimeMillis();
File[] f = BlockCanaryInternals.getLogFiles();
File[] f = getLogFiles();
if (f != null && f.length > 0) {
synchronized (SAVE_DELETE_LOCK) {
for (File aF : f) {
Expand All @@ -83,7 +86,7 @@ public void run() {
public static void deleteAll() {
synchronized (SAVE_DELETE_LOCK) {
try {
File[] files = BlockCanaryInternals.getLogFiles();
File[] files = getLogFiles();
if (files != null && files.length > 0) {
for (File file : files) {
file.delete();
Expand All @@ -99,7 +102,7 @@ private static String save(String logFileName, String str) {
String path = "";
BufferedWriter writer = null;
try {
File file = BlockCanaryInternals.detectedBlockDirectory();
File file = detectedBlockDirectory();
long time = System.currentTimeMillis();
path = file.getAbsolutePath() + "/"
+ logFileName + "-"
Expand Down Expand Up @@ -138,6 +141,49 @@ private static String save(String logFileName, String str) {
}

public static File generateTempZip(String filename) {
return new File(BlockCanaryInternals.getPath() + "/" + filename + ".zip");
return new File(getPath() + "/" + filename + ".zip");
}


private static String getPath() {
String state = Environment.getExternalStorageState();
BlockInterceptor interceptor = BlockCanaryInternals.getInstance().getInterceptor(0) ;
String logPath = interceptor == null ? "" : interceptor.providePath();

if (Environment.MEDIA_MOUNTED.equals(state)
&& Environment.getExternalStorageDirectory().canWrite()) {
return Environment.getExternalStorageDirectory().getPath() + logPath;
}
return BlockCanaryInternals.getContext().getFilesDir() + interceptor.providePath();
}

static File detectedBlockDirectory() {
File directory = new File(getPath());
if (!directory.exists()) {
directory.mkdirs();
}
return directory;
}

public static File[] getLogFiles() {
File f = detectedBlockDirectory();
if (f.exists() && f.isDirectory()) {
return f.listFiles(new BlockLogFileFilter());
}
return null;
}

private static class BlockLogFileFilter implements FilenameFilter {

private String TYPE = ".log";

BlockLogFileFilter() {

}

@Override
public boolean accept(File dir, String filename) {
return filename.endsWith(TYPE);
}
}
}
Loading