Wealth will come from hard work, a man must read five books.

What does StrictMode detect?

StrictMode mainly checks two issues: TreadPolicy and VmPolicy.

How does StrictMode work?

StrictMode is most commonly used to catch unexpected disk or network access on the main thread of an application, where UI operations are received and animated. Keeping disk and network operations off the main thread makes applications smoother and more responsive. You can also prevent the ANR dialog from being displayed to the user by keeping the main thread of your application responsive.

Note that even though the disk on an Android device is typically located in flash memory, many devices have very limited concurrency running file systems on top of that memory. In general, almost all disk access is fast, but in some cases, the access speed can be significantly reduced when certain processes are doing some I/O in the background. If possible, it is best to assume that this situation is not fast.

ThreadPolicy ThreadPolicy

  • DetectAll () turned on for all possible problems;
  • To call slow detections, use detectCustomSlowCalls() to turn on;
  • DetectDiskReads () enabled for disk reads;
  • DetectDiskWrites () enabled;
  • Network operation, with detectNetwork() enabled;
  • DetectResourceMismatches () enabled to detect mismatches between defined resource types and getter calls;
  • DetectUnbufferedIo () for unbuffered input/output operations.

VmPolicy VmPolicy

  • DetectAll () turned on for all possible problems;
  • DetectActivityLeaks using detectacvityleaks ();
  • Authority detection, detectContentUriWithoutPermission open ();
  • Not closed Closable object leak, use detectLeakedClosableObjects open ();
  • Leakage of Sqlite object, use the detectLeakedSqlLiteObjects () open;
  • Check the number of instances, using setClassInstanceLimit().
  • And so on…

StrictMode principles and skills

The detect method starting with the name specifies the problem we should look for. The method penalty, which begins with the name, specifies the action to take when a problem is detected. As many detect and penalty methods can be invoked as needed. The order is trivial: all measures apply to all detected problems.

How to use StrictMode?

Add StrictMode checks before the Application, Activity, or other Application component application.oncreate () method is executed.

public void onCreate() {
     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new ThreadPolicy.Builde()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new VmPolicy.Builde()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }
     super.onCreate();
 }

Copy the code

What about the observations?

  • StrictMode information is filtered by logat in AS IDE
  • Adb logcat filters StrictMode information

Field experience

(1) Practical operation environment

  • Optional, use your own environment and code as well
  • SamplePop code download
  • The SamplePop environment is as follows:

Android Studio 4.0 Gradle Version 6.1.1 Android API Version 30

(2) File writing thread check

One example: check for file writes in the main thread

(2.1) The code enables all ThreadPolicy and VmPolicy violation detection

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { / / code to enable all the ThreadPolicy and VmPolicy violation detection StrictMode. SetThreadPolicy (new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WriteToFileInMainThread (); } /** ** writeToFileInMainThread() {File destFile = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).getPath(), "StrictModeTest.txt"); try { destFile.createNewFile(); destFile.setWritable(true); OutputStream output = new FileOutputStream(destFile, true); output.write("IO operation".getBytes()); output.flush(); output.close(); } catch (Exception e) { e.printStackTrace(); }}}Copy the code

(2.2) Run the application and observe the output of logcat

(2.3) Troubleshoot StrictMode check errors

/** * public void writeToFileInSubThread() {new Thread(new Runnable() {@override public void run() { writeToFileInMainThread(); } }).start(); }Copy the code

(3) Check for memory leakage

One example: memory leak checks

(3.1) Cause LeakActivity to leak memory

public class LeakActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leak); ActivityManager.getInstance().mActivities.add(this); }}Copy the code

(3.2) Partial implementation of mActivities in ActivityManager

public class ActivityManager { private static ActivityManager mInstance = new ActivityManager(); public ArrayList<Activity> mActivities = new ArrayList<>(); private ActivityManager(){ } public static ActivityManager getInstance() { return mInstance; }}Copy the code

(3.3) Causing a memory leak

Repeatedly opening LeakActivity from MainActivity, returning, and opening it again, causing a memory leak.

    public void onLeakActivityStart(View view) {
        Log.d(TAG, "onLeakActivityStart: ");
        startActivity(new Intent(this, LeakActivity.class));
    }
Copy the code

(3.4) Run the application and observe the output of logcat

(4) Detection of class instance leakage

For example: custom detection class instance leakage

(4.1) Enable instance detection, and a memory leak is reported when more than one instance of the LeakActivity class occurs

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().setClassInstanceLimit(LeakActivity.class, 1).penaltyLog().build());
Copy the code

(4.2) Run the application and observe the output of logcat

(5) Time-consuming call – noteSlowCall

For example: Time-consuming call (noteSlowCall)

(5.1) Time-consuming call detection is applicable to user-defined task execution classes, such as

public class FastRunTask { private static final int MAX_RUN_VALID_DURATION = 300; public void execute(Runnable task) { long startTime = SystemClock.uptimeMillis(); task.run(); long useTime = SystemClock.uptimeMillis() - startTime; if (useTime > MAX_RUN_VALID_DURATION) { StrictMode.noteSlowCall("FastRunTask note slow call use time : [" + useTime + "]"); }}}Copy the code

(5.2) Perform time-consuming tasks

public void onFastRunTask(View view) { Log.d(TAG, "onFastRunTask: "); FastRunTask fastRunTask = new FastRunTask(); fastRunTask.execute(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }}}); }Copy the code

(5.3) Run the application and observe the output of logcat

(6) StrictMode summary

  • Main Purpose: Find operations that might run for a long time, such as network or database operations that you might inadvertently perform in the main thread.
  • Note:

StrictMode cannot monitor disk I/O and network requests in the JNI. Not all violations need to be resolved in the application. For example, some IO operations must be performed in the main thread. StrictMode usually gives a higher time than the actual situation and is not the real time data.

  • How to fix the problem: If you find that you feel there is a problem with the violation, there are all kinds of tools to help resolve these problems: threads,Handler.AsyncTask.IntentServiceAnd so on.

Note: StrictMode is not a security mechanism and cannot guarantee that all disks or network access will be found. Although state does propagate across process boundaries when Binder calls are made, it is ultimately a best-for-all mechanism. Future versions of Android may perform more (or less) operations, so you should never enable StrictMode in a published application.

Enable StrictModel to see your own project

Xiaobian extension links

  • SamplePop code download
  • Android Performance Optimization family Bucket

Refer to the link

  • This is the first article that should be read

Like a bright moon cloud river, such as the body of a breeze flow wave

❤ ❤ than heart