android.os.Debug Java Examples

The following examples show how to use android.os.Debug. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BlockMonitorManager.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/**
 * 通知卡顿
 *
 * @param blockInfo
 */
void notifyBlockEvent(BlockInfo blockInfo) {
    blockInfo.concernStackString = BlockCanaryUtils.concernStackString(mContext, blockInfo);
    blockInfo.time = System.currentTimeMillis();
    if (!TextUtils.isEmpty(blockInfo.concernStackString)) {
        //卡顿 debug模式下会造成卡顿
        if (DokitConstant.APP_HEALTH_RUNNING && !Debug.isDebuggerConnected()) {
            addBlockInfoInAppHealth(blockInfo);
        }
        showNotification(blockInfo);
        if (mBlockInfoList.size() > MAX_SIZE) {
            mBlockInfoList.remove(0);
        }
        mBlockInfoList.add(blockInfo);
        if (mOnBlockInfoUpdateListener != null) {
            mOnBlockInfoUpdateListener.onBlockInfoUpdate(blockInfo);
        }
    }

}
 
Example #2
Source File: BenchmarkStats.java    From ig-json-parser with MIT License 6 votes vote down vote up
/** Grabs the post-snapshot. */
synchronized void after() {
  mAfterTimestamp = SystemClock.elapsedRealtime();
  Debug.stopAllocCounting();
  Debug.getMemoryInfo(mMemoryInfoAfter);

  mAllocCount = Debug.getGlobalAllocCount();
  mAllocSize = Debug.getGlobalAllocSize();
  mFreeCount = Debug.getGlobalFreedCount();
  mFreeSize = Debug.getGlobalFreedSize();

  if (mState != State.BEFORE_CALLED) {
    throw new IllegalStateException("unexpected state");
  }
  mState = State.AFTER_CALLED;
}
 
Example #3
Source File: MainActivity.java    From fresco with MIT License 6 votes vote down vote up
private void updateStats() {
  final Runtime runtime = Runtime.getRuntime();
  final long heapMemory = runtime.totalMemory() - runtime.freeMemory();
  final StringBuilder sb = new StringBuilder(DEFAULT_MESSAGE_SIZE);
  // When changing format of output below, make sure to sync "run_comparison.py" as well
  sb.append("Heap: ");
  appendSize(sb, heapMemory);
  sb.append(" Java ");
  appendSize(sb, Debug.getNativeHeapSize());
  sb.append(" native\n");
  appendTime(sb, "Avg wait time: ", mPerfListener.getAverageWaitTime(), "\n");
  appendNumber(sb, "Requests: ", mPerfListener.getOutstandingRequests(), " outsdng ");
  appendNumber(sb, "", mPerfListener.getCancelledRequests(), " cncld\n");
  final String message = sb.toString();
  mStatsDisplay.setText(message);
  FLog.i(TAG, message);
}
 
Example #4
Source File: AwShellApplication.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    AwShellResourceProvider.registerResources(this);

    CommandLine.initFromFile("/data/local/tmp/android-webview-command-line");

    if (CommandLine.getInstance().hasSwitch(CommandLine.WAIT_FOR_JAVA_DEBUGGER)) {
       Log.e(TAG, "Waiting for Java debugger to connect...");
       Debug.waitForDebugger();
       Log.e(TAG, "Java debugger connected. Resuming execution.");
    }

    ResourceExtractor.setMandatoryPaksToExtract(MANDATORY_PAKS);
    ResourceExtractor.setExtractImplicitLocaleForTesting(false);
    LibraryLoader.setLibraryToLoad(LIBRARIES);
    AwBrowserProcess.loadLibrary();
    AwBrowserProcess.start(this);
}
 
Example #5
Source File: DdmHandleProfiling.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private Chunk handleMPSEOrSPSE(Chunk request, String type) {
    if (DEBUG) {
        Log.v("ddm-heap", type + " prof stream end");
    }

    try {
        Debug.stopMethodTracing();
    } catch (RuntimeException re) {
        Log.w("ddm-heap", type + " prof stream end failed: "
            + re.getMessage());
        return createFailChunk(1, re.getMessage());
    }

    /* VM sent the (perhaps very large) response directly */
    return null;
}
 
Example #6
Source File: EventProcessor.java    From StallBuster with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(Message msg) {
    // TODO uncomment below code when release
    if (Debug.isDebuggerConnected()) {
        return true;
    }
    Event event = (Event) msg.obj;
    if (event != null) {
        try {
            processEvent(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
        event.recycle();
    }
    // return true, so handler won't process this msg again, since we have event recycled here
    return true;
}
 
Example #7
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
public void startProfiling() {
    if (profileFd == null || profiling) {
        return;
    }
    try {
        Debug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
                8 * 1024 * 1024, 0);
        profiling = true;
    } catch (RuntimeException e) {
        Slog.w(TAG, "Profiling failed on path " + profileFile);
        try {
            profileFd.close();
            profileFd = null;
        } catch (IOException e2) {
            Slog.w(TAG, "Failure closing profile fd", e2);
        }
    }
}
 
Example #8
Source File: PLA_AbsListView.java    From EverMemo with MIT License 6 votes vote down vote up
void start(int initialVelocity) {
	initialVelocity = modifyFlingInitialVelocity(initialVelocity);

	int initialY = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
	mLastFlingY = initialY;
	mScroller.fling(0, initialY, 0, initialVelocity,
			0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);

	if(DEBUG)
		Log.d(TAG, String.format("String Fling: [%d, %d] to [%d]", initialY, initialVelocity, mScroller.getFinalY()));

	mTouchMode = TOUCH_MODE_FLING;
	post(this);

	if (PROFILE_FLINGING) {
		if (!mFlingProfilingStarted) {
			Debug.startMethodTracing("AbsListViewFling");
			mFlingProfilingStarted = true;
		}
	}
}
 
Example #9
Source File: CommonLiveUI.java    From likequanmintv with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDestroy() {
    if (playerHolder!=null){
        playerHolder.release();
        playerHolder=null;
    }
    verticalControll.onDestroy();
    horizontalControll.onDestroy();
    super.onDestroy();

    Debug.stopMethodTracing();


}
 
Example #10
Source File: Instrumentation.java    From droidel with Apache License 2.0 5 votes vote down vote up
/**
 * This method will start profiling if isProfiling() returns true. You should
 * only call this method if you set the handleProfiling attribute in the 
 * manifest file for this Instrumentation to true.  
 */
public void startProfiling() {
    if (mThread.isProfiling()) {
        File file = new File(mThread.getProfileFilePath());
        file.getParentFile().mkdirs();
        Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
    }
}
 
Example #11
Source File: HprofCatcher.java    From hprof-tools with MIT License 5 votes vote down vote up
@Override
public void uncaughtException(Thread thread, Throwable ex) {
    try {
        String fileName = mContext.getFilesDir().getAbsolutePath() + "/" + System.currentTimeMillis() + ".hprof";
        Log.d(TAG, "Writing memory dump to: " + fileName);
        Debug.dumpHprofData(fileName);
    }
    catch (Throwable t) {
        // Make sure we don't throw any new exception here!
        Log.e(TAG, "Failed to write memory dump", t);
    }
    mOldHandler.uncaughtException(thread, ex);
}
 
Example #12
Source File: HeapDump.java    From zjdroid with Apache License 2.0 5 votes vote down vote up
public static void dumpHeap(String filename) {
	try {
		Debug.dumpHprofData(filename);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #13
Source File: MemoryUtil.java    From MemoryMonitor with MIT License 5 votes vote down vote up
/**
 * 获取应用实际占用内存
 *
 * @param context
 * @param pid
 * @return 应用pss信息KB
 */
public static PssInfo getAppPssInfo(Context context, int pid) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    Debug.MemoryInfo memoryInfo = am.getProcessMemoryInfo(new int[]{pid})[0];
    PssInfo pssInfo = new PssInfo();
    pssInfo.totalPss = memoryInfo.getTotalPss();
    pssInfo.dalvikPss = memoryInfo.dalvikPss;
    pssInfo.nativePss = memoryInfo.nativePss;
    pssInfo.otherPss = memoryInfo.otherPss;
    return pssInfo;
}
 
Example #14
Source File: InputMonitor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void freezeInputDispatchingLw() {
    if (!mInputDispatchFrozen) {
        if (DEBUG_INPUT) {
            Slog.v(TAG_WM, "Freezing input dispatching");
        }

        mInputDispatchFrozen = true;

        if (DEBUG_INPUT || true) {
            mInputFreezeReason = Debug.getCallers(6);
        }
        updateInputDispatchModeLw();
    }
}
 
Example #15
Source File: AndroidJUnitRunner.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle arguments) {
  super.onCreate(arguments);
  this.arguments = arguments;
  parseRunnerArgs(this.arguments);

  if (waitForDebugger(runnerArgs)) {
    Log.i(LOG_TAG, "Waiting for debugger to connect...");
    Debug.waitForDebugger();
    Log.i(LOG_TAG, "Debugger connected.");
  }

  // We are only interested in tracking usage of the primary process.
  if (isPrimaryInstrProcess(runnerArgs.targetProcess)) {
    usageTrackerFacilitator = new UsageTrackerFacilitator(runnerArgs);
  } else {
    usageTrackerFacilitator = new UsageTrackerFacilitator(false);
  }


  for (ApplicationLifecycleCallback listener : runnerArgs.appListeners) {
    ApplicationLifecycleMonitorRegistry.getInstance().addLifecycleCallback(listener);
  }

  addScreenCaptureProcessors(runnerArgs);

  if (runnerArgs.orchestratorService != null && isPrimaryInstrProcess(runnerArgs.targetProcess)) {
    // If orchestratorService is provided, and we are the primary process
    // we await onOrchestratorConnect() before we start().
    orchestratorListener = new OrchestratedInstrumentationListener(this);
    orchestratorListener.connect(getContext());
  } else {
    // If no orchestration service is given, or we are not the primary process we can
    // start() immediately.
    start();
  }
}
 
Example #16
Source File: Instrumentation.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Deprecated
public void stopAllocCounting() {
    Runtime.getRuntime().gc();
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();
    Debug.stopAllocCounting();
}
 
Example #17
Source File: TaskPersister.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
void saveImage(Bitmap image, String filePath) {
    synchronized (this) {
        int queueNdx;
        for (queueNdx = mWriteQueue.size() - 1; queueNdx >= 0; --queueNdx) {
            final WriteQueueItem item = mWriteQueue.get(queueNdx);
            if (item instanceof ImageWriteQueueItem) {
                ImageWriteQueueItem imageWriteQueueItem = (ImageWriteQueueItem) item;
                if (imageWriteQueueItem.mFilePath.equals(filePath)) {
                    // replace the Bitmap with the new one.
                    imageWriteQueueItem.mImage = image;
                    break;
                }
            }
        }
        if (queueNdx < 0) {
            mWriteQueue.add(new ImageWriteQueueItem(filePath, image));
        }
        if (mWriteQueue.size() > MAX_WRITE_QUEUE_LENGTH) {
            mNextWriteTime = FLUSH_QUEUE;
        } else if (mNextWriteTime == 0) {
            mNextWriteTime = SystemClock.uptimeMillis() + PRE_TASK_DELAY_MS;
        }
        if (DEBUG) Slog.d(TAG, "saveImage: filePath=" + filePath + " now=" +
                SystemClock.uptimeMillis() + " mNextWriteTime=" +
                mNextWriteTime + " Callers=" + Debug.getCallers(4));
        notifyAll();
    }

    yieldIfQueueTooDeep();
}
 
Example #18
Source File: LockPatternView.java    From android-lockpattern with Apache License 2.0 5 votes vote down vote up
private void handleActionUp(MotionEvent event) {
    // report pattern detected
    if (!mPattern.isEmpty()) {
        mPatternInProgress = false;
        cancelLineAnimations();
        notifyPatternDetected();
        invalidate();
    }
    if (PROFILE_DRAWING) {
        if (mDrawingProfilingStarted) {
            Debug.stopMethodTracing();
            mDrawingProfilingStarted = false;
        }
    }
}
 
Example #19
Source File: MemInfoViewModule.java    From DebugOverlay-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataAvailable(MemInfo data) {
    ActivityManager.MemoryInfo systemMemInfo = data.getSystemMemInfo();
    Debug.MemoryInfo procMemInfo = data.getProcessMemInfo();

    if (DebugOverlay.isDebugLoggingEnabled()) {
        Log.d(TAG, "MemTotal(MB):" + DECIMAL_FORMAT.format(systemMemInfo.totalMem / 1048576f));
        Log.d(TAG, "MemAvail(MB):" + DECIMAL_FORMAT.format(systemMemInfo.availMem / 1048576f));
        Log.d(TAG, "MemThreshold(MB):" + DECIMAL_FORMAT.format(systemMemInfo.threshold / 1048576f));
        Log.d(TAG, "TotalPss(MB):" + DECIMAL_FORMAT.format(procMemInfo.getTotalPss() / 1024f));
        Log.d(TAG, "TotalPrivateDirty(MB):" + DECIMAL_FORMAT.format(procMemInfo.getTotalPrivateDirty() / 1024f));
    }
    
    if (memInfoTxtView != null) {
        StringBuilder builder = new StringBuilder(HEADER);
        builder.append(DECIMAL_FORMAT.format(systemMemInfo.availMem / 1048576f)).append(" ")
                .append(DECIMAL_FORMAT.format(procMemInfo.getTotalPss() / 1024f)).append(" ")
                .append(DECIMAL_FORMAT.format(procMemInfo.getTotalPrivateDirty() / 1024f));

        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(builder.toString());
        if (systemMemInfo.lowMemory) {
            spannableBuilder.setSpan(
                    new TextAppearanceSpan(memInfoTxtView.getContext(), R.style.debugoverlay_LowMemoryTextAppearance),
                    HEADER.length(),
                    spannableBuilder.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
        }
        memInfoTxtView.setText(spannableBuilder);
    }
}
 
Example #20
Source File: Instrumentation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Deprecated
public void startAllocCounting() {
    // Before we start trigger a GC and reset the debug counts. Run the 
    // finalizers and another GC before starting and stopping the alloc
    // counts. This will free up any objects that were just sitting around 
    // waiting for their finalizers to be run.
    Runtime.getRuntime().gc();
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();

    Debug.resetAllCounts();
    
    // start the counts
    Debug.startAllocCounting();
}
 
Example #21
Source File: Instrumentation.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a bundle with the current results from the allocation counting.
 */
public Bundle getAllocCounts() {
    Bundle results = new Bundle();
    results.putLong("global_alloc_count", Debug.getGlobalAllocCount());
    results.putLong("global_alloc_size", Debug.getGlobalAllocSize());
    results.putLong("global_freed_count", Debug.getGlobalFreedCount());
    results.putLong("global_freed_size", Debug.getGlobalFreedSize());
    results.putLong("gc_invocation_count", Debug.getGlobalGcInvocationCount());    
    return results;
}
 
Example #22
Source File: Instrumentation.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * This method will start profiling if isProfiling() returns true. You should
 * only call this method if you set the handleProfiling attribute in the 
 * manifest file for this Instrumentation to true.  
 */
public void startProfiling() {
    if (mThread.isProfiling()) {
        File file = new File(mThread.getProfileFilePath());
        file.getParentFile().mkdirs();
        Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
    }
}
 
Example #23
Source File: TaskRecord.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Reorder the history stack so that the passed activity is brought to the front.
 */
final void moveActivityToFrontLocked(ActivityRecord newTop) {
    if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE,
            "Removing and adding activity " + newTop
            + " to stack at top callers=" + Debug.getCallers(4));

    mActivities.remove(newTop);
    mActivities.add(newTop);

    // Make sure window manager is aware of the position change.
    mWindowContainerController.positionChildAtTop(newTop.mWindowContainerController);
    updateEffectiveIntent();

    setFrontOfTask();
}
 
Example #24
Source File: Instrumentation.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * This method will start profiling if isProfiling() returns true. You should
 * only call this method if you set the handleProfiling attribute in the 
 * manifest file for this Instrumentation to true.  
 */
public void startProfiling() {
    if (mThread.isProfiling()) {
        File file = new File(mThread.getProfileFilePath());
        file.getParentFile().mkdirs();
        Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
    }
}
 
Example #25
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Logs a warning if the system process directly called a method such as
 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
 * The "AsUser" variants allow us to properly enforce the user's restrictions.
 */
private void warnIfCallingFromSystemProcess() {
    if (Process.myUid() == Process.SYSTEM_UID) {
        Slog.w(TAG, "Calling a method in the system process without a qualified user: "
                + Debug.getCallers(5));
    }
}
 
Example #26
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private void validateServiceIntent(Intent service) {
    if (service.getComponent() == null && service.getPackage() == null) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
            IllegalArgumentException ex = new IllegalArgumentException(
                    "Service Intent must be explicit: " + service);
            throw ex;
        } else {
            Log.w(TAG, "Implicit intents with startService are not safe: " + service
                    + " " + Debug.getCallers(2, 3));
        }
    }
}
 
Example #27
Source File: LockPatternView.java    From GestureLock with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!mInputEnabled || !isEnabled()) {
        return false;
    }

    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            handleActionDown(event);
            return true;
        case MotionEvent.ACTION_UP:
            handleActionUp(event);
            return true;
        case MotionEvent.ACTION_MOVE:
            handleActionMove(event);
            return true;
        case MotionEvent.ACTION_CANCEL:
            if (mPatternInProgress) {
                mPatternInProgress = false;
                resetPattern();
                notifyPatternCleared();
            }
            if (PROFILE_DRAWING) {
                if (mDrawingProfilingStarted) {
                    Debug.stopMethodTracing();
                    mDrawingProfilingStarted = false;
                }
            }
            return true;
    }
    return false;
}
 
Example #28
Source File: LockPatternView.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    if (!mInputEnabled || !isEnabled()) {
        return false;
    }

    switch(event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            handleActionDown(event);
            return true;
        case MotionEvent.ACTION_UP:
            handleActionUp(event);
            return true;
        case MotionEvent.ACTION_MOVE:
            handleActionMove(event);
            return true;
        case MotionEvent.ACTION_CANCEL:
            if (mPatternInProgress) {
                mPatternInProgress = false;
                resetPattern();
                notifyPatternCleared();
            }
            if (PROFILE_DRAWING) {
                if (mDrawingProfilingStarted) {
                    Debug.stopMethodTracing();
                    mDrawingProfilingStarted = false;
                }
            }
            return true;
    }
    return false;
}
 
Example #29
Source File: HeapStatsLogger.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void log() {
    Log.i(TAG, "heap_stats " +
          // Format is "key=value unit", and it'll be parsed by the test
          // runner in order to be added to the bot graphs.
          "gc_count=" + Debug.getGlobalGcInvocationCount() + " times " +
          "alloc_count=" + Debug.getGlobalAllocCount() + " times " +
          "alloc_size=" + Debug.getGlobalAllocSize() + " bytes " +
          "freed_count=" + Debug.getGlobalFreedCount() + " times " +
          "freed_size=" + Debug.getGlobalFreedSize() + " bytes"
    );
}
 
Example #30
Source File: Instrumentation.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Deprecated
public void startAllocCounting() {
    // Before we start trigger a GC and reset the debug counts. Run the 
    // finalizers and another GC before starting and stopping the alloc
    // counts. This will free up any objects that were just sitting around 
    // waiting for their finalizers to be run.
    Runtime.getRuntime().gc();
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();

    Debug.resetAllCounts();
    
    // start the counts
    Debug.startAllocCounting();
}