类android.os.strictmode.Violation源码实例Demo

下面列出了怎么用android.os.strictmode.Violation的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android_9.0.0_r45   文件: StrictMode.java
/** Create an instance of ViolationInfo initialized from an exception. */
ViolationInfo(Violation tr, int policy) {
    this.mViolation = tr;
    this.mPolicy = policy;
    violationUptimeMillis = SystemClock.uptimeMillis();
    this.numAnimationsRunning = ValueAnimator.getCurrentAnimationsCount();
    Intent broadcastIntent = ActivityThread.getIntentBeingBroadcast();
    if (broadcastIntent != null) {
        broadcastIntentAction = broadcastIntent.getAction();
    }
    ThreadSpanState state = sThisThreadSpanState.get();
    if (tr instanceof InstanceCountViolation) {
        this.numInstances = ((InstanceCountViolation) tr).getNumberOfInstances();
    }
    synchronized (state) {
        int spanActiveCount = state.mActiveSize;
        if (spanActiveCount > MAX_SPAN_TAGS) {
            spanActiveCount = MAX_SPAN_TAGS;
        }
        if (spanActiveCount != 0) {
            this.tags = new String[spanActiveCount];
            Span iter = state.mActiveHead;
            int index = 0;
            while (iter != null && index < spanActiveCount) {
                this.tags[index] = iter.mName;
                index++;
                iter = iter.mNext;
            }
        }
    }
}
 
源代码2 项目: android_9.0.0_r45   文件: StrictMode.java
/**
 * Create an instance of ViolationInfo initialized from a Parcel.
 *
 * @param unsetGatheringBit if true, the caller is the root caller and the gathering penalty
 *     should be removed.
 */
public ViolationInfo(Parcel in, boolean unsetGatheringBit) {
    mViolation = (Violation) in.readSerializable();
    int binderStackSize = in.readInt();
    for (int i = 0; i < binderStackSize; i++) {
        StackTraceElement[] traceElements = new StackTraceElement[in.readInt()];
        for (int j = 0; j < traceElements.length; j++) {
            StackTraceElement element =
                    new StackTraceElement(
                            in.readString(),
                            in.readString(),
                            in.readString(),
                            in.readInt());
            traceElements[j] = element;
        }
        mBinderStack.add(traceElements);
    }
    int rawPolicy = in.readInt();
    if (unsetGatheringBit) {
        mPolicy = rawPolicy & ~PENALTY_GATHER;
    } else {
        mPolicy = rawPolicy;
    }
    durationMillis = in.readInt();
    violationNumThisLoop = in.readInt();
    numAnimationsRunning = in.readInt();
    violationUptimeMillis = in.readLong();
    numInstances = in.readLong();
    broadcastIntentAction = in.readString();
    tags = in.readStringArray();
}
 
源代码3 项目: braintree_android   文件: DemoApplication.java
private void handleViolation(Violation v) {
    Throwable cause = v.getCause();

    if (classExistsInThrowable("com.cardinalcommerce.cardinalmobilesdk.Tasks.NewtworkTask.CentinelChallengeTask", "doInBackground", cause)) {
        Log.d("handleViolation", "Cardinal has been notified of this strict mode violation");
    } else if (classExistsInThrowable("com.cardinalcommerce.cardinalmobilesdk.Tasks.NewtworkTask.CentinelApiInitTask", "doInBackground", cause)) {
        Log.d("handleViolation", "Cardinal has been notified of this strict mode violation");
    } else {
        throw new RuntimeException(v.getCause());
    }
}
 
源代码4 项目: grpc-java   文件: StrictModeHelloworldActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  VmPolicy policy =
      new StrictMode.VmPolicy.Builder()
          .detectCleartextNetwork()
          .penaltyListener(
              MoreExecutors.directExecutor(),
              new OnVmViolationListener() {
                @Override
                public void onVmViolation(final Violation v) {
                  runOnUiThread(
                      new Runnable() {
                        @Override
                        public void run() {
                          new AlertDialog.Builder(StrictModeHelloworldActivity.this)
                              .setTitle("StrictMode VM Violation")
                              .setMessage(v.getLocalizedMessage())
                              .show();
                        }
                      });
                }
              })
          .penaltyLog()
          .build();
  StrictMode.setVmPolicy(policy);
  setContentView(R.layout.activity_strictmodehelloworld);
  sendButton = (Button) findViewById(R.id.send_button);
  hostEdit = (EditText) findViewById(R.id.host_edit_text);
  portEdit = (EditText) findViewById(R.id.port_edit_text);
  messageEdit = (EditText) findViewById(R.id.message_edit_text);
  resultText = (TextView) findViewById(R.id.grpc_response_text);
  resultText.setMovementMethod(new ScrollingMovementMethod());
}
 
源代码5 项目: android_9.0.0_r45   文件: StrictMode.java
/** Called on a thread policy violation. */
void onThreadViolation(Violation v);
 
源代码6 项目: android_9.0.0_r45   文件: StrictMode.java
/** Called on a VM policy violation. */
void onVmViolation(Violation v);
 
源代码7 项目: android_9.0.0_r45   文件: StrictMode.java
void startHandlingViolationException(Violation e) {
    final ViolationInfo info = new ViolationInfo(e, mPolicyMask);
    info.violationUptimeMillis = SystemClock.uptimeMillis();
    handleViolationWithTimingAttempt(info);
}
 
源代码8 项目: android_9.0.0_r45   文件: StrictMode.java
void onThreadPolicyViolation(final ViolationInfo info) {
    if (LOG_V) Log.d(TAG, "onThreadPolicyViolation; policy=" + info.mPolicy);

    if (info.penaltyEnabled(PENALTY_GATHER)) {
        ArrayList<ViolationInfo> violations = gatheredViolations.get();
        if (violations == null) {
            violations = new ArrayList<>(1);
            gatheredViolations.set(violations);
        }
        for (ViolationInfo previous : violations) {
            if (info.getStackTrace().equals(previous.getStackTrace())) {
                // Duplicate. Don't log.
                return;
            }
        }
        violations.add(info);
        return;
    }

    // Not perfect, but fast and good enough for dup suppression.
    Integer crashFingerprint = info.hashCode();
    long lastViolationTime = 0;
    if (mLastViolationTime != null) {
        Long vtime = mLastViolationTime.get(crashFingerprint);
        if (vtime != null) {
            lastViolationTime = vtime;
        }
    } else {
        mLastViolationTime = new ArrayMap<>(1);
    }
    long now = SystemClock.uptimeMillis();
    mLastViolationTime.put(crashFingerprint, now);
    long timeSinceLastViolationMillis =
            lastViolationTime == 0 ? Long.MAX_VALUE : (now - lastViolationTime);

    if (info.penaltyEnabled(PENALTY_LOG)
            && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
        sLogger.log(info);
    }

    final Violation violation = info.mViolation;

    // The violationMaskSubset, passed to ActivityManager, is a
    // subset of the original StrictMode policy bitmask, with
    // only the bit violated and penalty bits to be executed
    // by the ActivityManagerService remaining set.
    int violationMaskSubset = 0;

    if (info.penaltyEnabled(PENALTY_DIALOG)
            && timeSinceLastViolationMillis > MIN_DIALOG_INTERVAL_MS) {
        violationMaskSubset |= PENALTY_DIALOG;
    }

    if (info.penaltyEnabled(PENALTY_DROPBOX) && lastViolationTime == 0) {
        violationMaskSubset |= PENALTY_DROPBOX;
    }

    if (violationMaskSubset != 0) {
        violationMaskSubset |= info.getViolationBit();

        final boolean justDropBox = (info.mPolicy & THREAD_PENALTY_MASK) == PENALTY_DROPBOX;
        if (justDropBox) {
            // If all we're going to ask the activity manager
            // to do is dropbox it (the common case during
            // platform development), we can avoid doing this
            // call synchronously which Binder data suggests
            // isn't always super fast, despite the implementation
            // in the ActivityManager trying to be mostly async.
            dropboxViolationAsync(violationMaskSubset, info);
        } else {
            handleApplicationStrictModeViolation(violationMaskSubset, info);
        }
    }

    if ((info.getPolicyMask() & PENALTY_DEATH) != 0) {
        throw new RuntimeException("StrictMode ThreadPolicy violation", violation);
    }

    // penaltyDeath will cause penaltyCallback to no-op since we cannot guarantee the
    // executor finishes before crashing.
    final OnThreadViolationListener listener = sThreadViolationListener.get();
    final Executor executor = sThreadViolationExecutor.get();
    if (listener != null && executor != null) {
        try {
            executor.execute(
                    () -> {
                        // Lift violated policy to prevent infinite recursion.
                        ThreadPolicy oldPolicy = allowThreadViolations();
                        try {
                            listener.onThreadViolation(violation);
                        } finally {
                            setThreadPolicy(oldPolicy);
                        }
                    });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "ThreadPolicy penaltyCallback failed", e);
        }
    }
}
 
源代码9 项目: android_9.0.0_r45   文件: StrictMode.java
/** @hide */
public static void onVmPolicyViolation(Violation originStack) {
    onVmPolicyViolation(originStack, false);
}
 
源代码10 项目: android_9.0.0_r45   文件: StrictMode.java
/** @hide */
public static void onVmPolicyViolation(Violation violation, boolean forceDeath) {
    final boolean penaltyDropbox = (sVmPolicy.mask & PENALTY_DROPBOX) != 0;
    final boolean penaltyDeath = ((sVmPolicy.mask & PENALTY_DEATH) != 0) || forceDeath;
    final boolean penaltyLog = (sVmPolicy.mask & PENALTY_LOG) != 0;
    final ViolationInfo info = new ViolationInfo(violation, sVmPolicy.mask);

    // Erase stuff not relevant for process-wide violations
    info.numAnimationsRunning = 0;
    info.tags = null;
    info.broadcastIntentAction = null;

    final Integer fingerprint = info.hashCode();
    final long now = SystemClock.uptimeMillis();
    long lastViolationTime;
    long timeSinceLastViolationMillis = Long.MAX_VALUE;
    synchronized (sLastVmViolationTime) {
        if (sLastVmViolationTime.containsKey(fingerprint)) {
            lastViolationTime = sLastVmViolationTime.get(fingerprint);
            timeSinceLastViolationMillis = now - lastViolationTime;
        }
        if (timeSinceLastViolationMillis > MIN_VM_INTERVAL_MS) {
            sLastVmViolationTime.put(fingerprint, now);
        }
    }
    if (timeSinceLastViolationMillis <= MIN_VM_INTERVAL_MS) {
        // Rate limit all penalties.
        return;
    }

    if (penaltyLog && sLogger != null && timeSinceLastViolationMillis > MIN_LOG_INTERVAL_MS) {
        sLogger.log(info);
    }

    int violationMaskSubset = PENALTY_DROPBOX | (ALL_VM_DETECT_BITS & sVmPolicy.mask);

    if (penaltyDropbox) {
        if (penaltyDeath) {
            handleApplicationStrictModeViolation(violationMaskSubset, info);
        } else {
            // Common case for userdebug/eng builds.  If no death and
            // just dropboxing, we can do the ActivityManager call
            // asynchronously.
            dropboxViolationAsync(violationMaskSubset, info);
        }
    }

    if (penaltyDeath) {
        System.err.println("StrictMode VmPolicy violation with POLICY_DEATH; shutting down.");
        Process.killProcess(Process.myPid());
        System.exit(10);
    }

    // If penaltyDeath, we can't guarantee this callback finishes before the process dies for
    // all executors. penaltyDeath supersedes penaltyCallback.
    if (sVmPolicy.mListener != null && sVmPolicy.mCallbackExecutor != null) {
        final OnVmViolationListener listener = sVmPolicy.mListener;
        try {
            sVmPolicy.mCallbackExecutor.execute(
                    () -> {
                        // Lift violated policy to prevent infinite recursion.
                        VmPolicy oldPolicy = allowVmViolations();
                        try {
                            listener.onVmViolation(violation);
                        } finally {
                            setVmPolicy(oldPolicy);
                        }
                    });
        } catch (RejectedExecutionException e) {
            Log.e(TAG, "VmPolicy penaltyCallback failed", e);
        }
    }
}
 
 类所在包
 同包方法