Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android development, may cause a memory leak problem     - Java Generics (Programming)

- C ++ precision performance test function (Programming)

- Oracle conditional select statements and looping statements (Database)

- Getting the Linux shell variable test (Programming)

- Vagrant Getting Start (Linux)

- Python 2.7.9 Installation on Linux CentOS 6.6 (Linux)

- Linux operating system ARP Spoofing Defense (Linux)

- How do I switch from NetworkManager to systemd-network on Linux (Linux)

- Hibernate4 The Hello World (basic environmental structures) (Programming)

- Linux ACL permissions (Linux)

- Linux 0.12 kernel and modern kernels difference in memory management (Linux)

- Boost notes --Thread - problems encountered in the initial use on Ubuntu (Programming)

- CentOS7 install MySQL5.6.22 (Linux)

- Ordinary users how to use the firewall software (Linux)

- Iptables principle (Linux)

- Linux set the maximum number of open files nofile and nr_open, file-max Description (Linux)

- Linux mention the right notes (Linux)

- CentOS 5.5 kernel upgrade installation iftop (Linux)

- Security: set limits on password (Linux)

- Ubuntu Thunderbird 24.4.0 (Linux)

 
         
  Android development, may cause a memory leak problem
     
  Add Date : 2018-11-21      
         
         
         
  In the Android coding, there will be some simple wording and coding practices, would lead us to have a lot of code memory leak problems. Here to do a summary of known bugs (some of which are personal summary and reference to other blogger, expressed thanks for this).

This article will be updated regularly, their encounter memory leak issues related to record and provide solutions.

1, error when writing a single case often appears.

The wrong way:

 public class Foo {
      private static Foo foo;
      private Context mContext;
      private Foo (Context mContext) {
           this.mContext = mContext;
      }
      // Ordinary single cases, non-thread-safe
      public static Foo getInstance (Context mContext) {
           if (foo == null)
                foo = new Foo (mContext);
           return foo;
      }
      public void otherAction () {
           mContext.xxxx ();
           ....
      }
 }
wrong reason:

If we use Foo.getInstance or elsewhere in the Activity A (), we always easily write a "this" or "mContext" (this variable also points to this). Imagine, we used the current Foo is a singleton, meaning that will always exist after being initialized and memory, in order to facilitate the future when we will not be called to create the Foo object. But the Foo "mContext" variable will always be held in Activity A "Context", resulting in even performed onDestroy Activity A method, will not be able to destroy themselves. But "applicationContext" is different, it has been associated with the presence of our application (middle may also be destroyed, but will automatically reCreate), so do not worry about the Foo "mContext" will hold a reference to an Activity, allowed It can not be destroyed.

The right way:

 public class Foo {
      private static Foo foo;
      private Context mContext;
      private Foo (Context mContext) {
           this.mContext = mContext;
      }
      // Ordinary single cases, non-thread-safe
      public static Foo getInstance (Context mContext) {
           if (foo == null)
                foo = new Foo (mContext.getApplicationContext ());
           return foo;
      }
      public void otherAction () {
           mContext.xxxx ();
           ....
      }
 }
2, the use of anonymous inner classes when recurring error

The wrong way:

 public class FooActivity extends Activity {
      private TextView textView;
      private Handler handler = new Handler () {
           @override
           public void handlerMessage (Message msg) {
           }
      };
      @override
      public void onCreate (Bundle bundle) {
           super.onCreate (bundle);
           setContextView (R.layout.activity_foo_layout);
           textView = (TextView) findViewById (R.id.textView);
           handler.postDelayed (new Runnable () {
                @override
                public void run () {
                     textView.setText ( "ok");
                };
           }, 1000 * 60 * 10);
      }
 }
wrong reason:

When we execute the finish method FooActivity of delayed messages exist before being processed main thread message queue for 10 minutes, and this message also contains a reference to the Handler, and Handler is an instance of an anonymous inner class, which hold out FooActivity references, so it can not cause the FooActivity recovery, which led to a lot of resources can not be held FooActivity recovery, so the more memory leaks.

Note that the above new Runnable here is the anonymous inner class implementations, the same will hold FooActivity references will prevent FooActivity be recycled.

A static anonymous inner class instance does not hold a reference to the outer class.

The right way:

public class FooActivity extends Activity {
     private TextView textView;
     private static class MyHandler extends Handler {
     private final WeakReference mActivity;
     public MyHandler (FooActivity activity) {
          mActivity = new WeakReference (activity);
     }
     @Override
     public void handleMessage (Message msg) {
          FooActivity activity = mActivity.get ();
               if (activity! = null) {
                    ....
               }
          }
     }
     private final MyHandler handler = new MyHandler (this);
     @override
     public void onCreate (Bundle bundle) {
          super.onCreate (bundle);
          setContextView (R.layout.activity_foo_layout);
          textView = (TextView) findViewById (R.id.textView);
          handler.postDelayed (new MyRunnable (textView), 1000 * 60 * 10);
     }
     private static class MyRunnable implements Runnable {
          private WeakReference textViewWeakReference;
          public MyRunnable (TextView textView) {
               textViewWeakReference = new WeakReference (textView);
          }
               @override
               public void run () {
                    final TextView textView = textViewWeakReference.get ();
                    if (textView! = null) {
                         textView.setText ( "OK");
                    }
               };
     }
}
3, on the use of handler

After using handler, remember to call handler.removeCallbacksAndMessages (object token) in onDestroy inside;

@Override
protected void onDestroy () {
    super.onDestroy ();
    handler.removeCallbacksAndMessages (null);
    // RemoveCallbacksAndMessages, if the argument is null, they can get rid of all the current handler associated with Runnable and Message.
    // We call the second method onDestroy will not happen in a memory leak.
}
4, InputMethodManager memory leak phenomenon

Phenomenon:. InputMethodManager hold a Activity, causing the Activity can not be recovered if the Activity is opened again, the old would be freed, but the new opening will be unable to continue to hold a release appears on the recovery screen.

This issue is part of a system problem. Now known are:> Samsung note3 N9008 official ROM 4.4.2> Amagatarai k_touch_v9 official ROM 4.0.4

Here we are just given a solution specific Solutions please refer to the following: [Android] [Memory Leak] InputMethodManager phenomenon and resolve memory leaks

Use the following code to call the Activity of onDestroy in.

public static void fixInputMethodManagerLeak (Context destContext) {
  if (destContext == null) {
    return;
  }
  InputMethodManager imm = (InputMethodManager) destContext.getSystemService (Context.INPUT_METHOD_SERVICE);
  if (imm == null) {
    return;
  }
  String [] arr = new String [] { "mCurRootView", "mServedView", "mNextServedView"};
  Field f = null;
  Object obj_get = null;
  for (int i = 0; i     String param = arr [i];
    try {
      f = imm.getClass () getDeclaredField (param).;
      if (f.isAccessible () == false) {
        f.setAccessible (true);
      } // Author: sodino mail: sodino@qq.com
      obj_get = f.get (imm);
      if (obj_get! = null && obj_get instanceof View) {
        View v_get = (View) obj_get;
        if (v_get.getContext () == destContext) {// referenced context is held InputMethodManager want to destroy targets
          f.set (imm, null); // set empty, destroyed node path to gc
        } Else {// not want to destroy the target, that is, again into another interface, do not deal with, to avoid affecting the original logic, there is nothing further for the cycle
          }
          break;
        }
      }
    } Catch (Throwable t) {
      t.printStackTrace ();
    }
  }
}
Developers need to pay attention in order to avoid a memory leak point:

* Do not make reference to the life cycle longer than the Activity object to hold the Activity

* Try to use the Application Context instead of Context Activity

* Do not use the Activity in non-static inner classes, because non-static inner classes implicitly holds the outer class reference to an instance (specifically can see fine words Java: "failure" of the private modifier understand). If you use static inner classes, instances of external references as weak references to hold.

* Garbage collection does not resolve memory leaks, garbage collection mechanism about Android

Get context of the method and the use of context and applicationContext difference:

* View.getContext, returns the current Context Object View object, usually are show Activity object.

* Activity.getApplicationContext, get the current Activity Context object resides (application) process, we usually use the Context object, to give priority to the global process of Context.

* ContextWrapper.getBaseContext (): used to obtain a decorated ContextWrapper before Context, you can use this method, this method is not much in the actual development, is not recommended.

* Activity.this returns the current Activity instance, if it is required to use UI controls Activity as Context objects, but the default Toast actually use ApplicationContext to be.

Number one: Start Activity in these classes is possible, but you need to create a new task. Generally not recommended.

Number 2: In these classes to layout inflate is legal, but will use the system default theme style, if you customize some styles may not be used.

Number 3: is null allow the receiver, at 4.2 or above version for acquiring sticky broadcast the current value. (Can ignore)

Note: ContentProvider, BroadcastReceiver reason in the above table, because its internal process has a context for use.

Well, here we look at the table, look at the focus and Application Activity, you can see, and UI related methods basically do not recommend or not use Application, and the first three basic operations can not appear in the Application. In fact, just a little grasp, all with the UI-related, should be used to deal with Activity as Context; some other examples of operation, Service, Activity, Application, etc. can, of course, a reference to the note holders Context prevent memory leak.
     
         
         
         
  More:      
 
- Apache POI Excel Document Processing (Linux)
- Netfilter / Iptables Comments (Linux)
- Merge Sort (Programming)
- PXE + Kickstart automatically install CentOS 6.5 (Linux)
- LaTeX Getting Started Tutorial (Linux)
- Linux network monitoring strategy (Linux)
- Java Set and List in the relationship and difference (Programming)
- Linux raw socket (Programming)
- Django 1.8 TEMPLATE_DIRS configuration and STATICFILES_DIRS (Server)
- Install and configure GO 1.2.1 under CentOS 6.5 (Linux)
- Linux non-graphical interface to install Oracle Database (Database)
- MySQL In can not be overridden with an internal connection (Database)
- HttpClient Tutorial (Programming)
- To configure linux transparent firewall (Linux)
- FileZilla FTP && TLS connection settings of (Linux)
- About phpwind 5.01-5.3 0day analysis of the article (Linux)
- Linux, Apache Web site security settings (Linux)
- Linux Desktop allows exceptionally different launch applications (Linux)
- RHEL5.x RHEL6.x replace CentOS yum source (Linux)
- nginx.conf Optimization (Server)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.