Enable Strict Mode in Android.

StrictMode works on a set of policies. There are presently two categories of policies: VM policies and thread policies. The former represent bad coding practices that pertain to your entire application, notably leaking SQLite Cursor objects and kin. The latter represent things that are bad when performed on the main application thread, notably flash I/O and network I/O.

The simplest thing to do is call the static enableDefaults() method on StrictMode from onCreate() of your first activity.

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

public class FilesDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (BuildConfig.DEBUG
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                       StrictMode.setThreadPolicy(buildPolicy());
        }
    }

   private StrictMode.ThreadPolicy buildPolicy() {
          return(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
   }
}

Here, we are asking to flag all faults (detectAll()), logging any violations to LogCat(penaltyLog()).

BuildConfig.DEBUG is a flag that indicates if we are on a debug build or not. The BuildConfig class is code-generated alongside the R class, in whatever Java package we declared in the <manifest> element of our manifest.

Note that StrictMode will also report leaked open files. For example, if you create a FileOutputStream on a File and fail to close() it later, when the FileOutputStream (and related objects) are garbage-collected, StrictMode will report to you the fact that you failed to close the stream.

Comments

Popular posts from this blog

Offers on Friday, April 24, 2020

Fatal: LoadModule: error loading module 'mod_sql_mysql.c'