Monday, November 16, 2015

Whats minimum you can do to detect activity leaks in an Android App ?

Just enable the strict mode. Assuming you are coding at midnight and still want to make sure that there are no lingering activity leaks in your app , you think its too much to force a heap dump and analyze that in MAT / JHAT , well here comes the StrictMode to your rescue.

 if (BuildConfig.DEBUG) {  
   StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
       .detectAll()  
       .penaltyLog()  
       .build()); 
   StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
       .detectAll()  
       .penaltyLog()  
       .penaltyDeathOnNetwork()  
       .build());  
 }   

It totally came to me as a surprise but yeh its true and its awesome

Stack

com.cricket.material E/StrictMode: 
class com.cricket.material.cricket.Summary.LiveScoreSummaryDetail; 
instances=2; limit=1 
com.cricket.material E/StrictMode: 
android.os.StrictMode$InstanceCountViolation:  
class com.cricket.material.cricket.Summary.LiveScoreSummaryDetail;  
instances=2; limit=1
com.cricket.material E/StrictMode: 
at android.os.StrictMode.setClassInstanceLimit(StrictMode.java:1)

Explanation :

Take a look at  StrictMode
/**
2324 If this is a instance count violation, the number of instances in memory,
2325 else -1.
2326 */
2327 public long numInstances = -1;

2188 Returns an object that is used to track instances of activites.
2189 The activity should store a reference to the tracker object in one of 
     its fields.
2190 * @hide
2191 */
2192 public static Object trackActivity(Object instance) {
2193       return new InstanceTracker(instance);
2194}

Note:

Please take this opportunity to understand other useful features of StrictMode
  • NetworkOnMainThread exception

No comments:

Post a Comment