Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android development, may cause a memory leak problem     - Ceph tuning --Journal and tcmalloc (Server)

- When Vim create Python scripts, vim autocomplete interpreter and encoding method (Programming)

- C / C ++ language usage summary of const (Programming)

- Linux use glibc2 library and crypt () function to generate the user password (Programming)

- Orionode source Linux Mint installation (Linux)

- Linux System Getting Started Learning: The Linux logrotate (Linux)

- Docker use Dockerfile created since the launch of the service support SSH container mirror (Server)

- CoreCLR compiled in Linux CentOS (Linux)

- Bash added to the Vi mode indicator (Linux)

- Java Class file format parsing (Programming)

- Unable to start the network after restart clone a virtual machine (Linux)

- The Gitlab migrated to Docker container (Server)

- Python-- for anomalies and reflection of objects articles (Programming)

- MySQL management partition table (Database)

- Common DDOS attacks (Linux)

- The REVERSE function of DB2 (Database)

- Oracle 11g partition maintenance (two) - Coalescing Partitions (Database)

- Ubuntu 14.04 LTS installed Hadoop 1.2.1 (distributed cluster mode) (Server)

- Use the vi text editor and copy and paste Linux tips (Linux)

- Linux operating system set up to effectively prevent ARP attacks (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:      
 
- Linux System Getting Started Learning: modify environment variables in Linux PATH (Linux)
- To setup CentOS LAMP environment (Server)
- The istgt PSD on ported to Mac OS X (Linux)
- mysqldump implement database logical backup (Database)
- MySQL is configured to access external networks under Ubuntu (Database)
- Python2 ---- function using dictionaries (Programming)
- Ubuntu users install the Download Manager software Xdman 5.0 (Linux)
- CentOS boot image to achieve semi-automatic installation (Linux)
- 10 Best Swift Tutorial examples (Programming)
- RedHat Redis Linux installation (Database)
- FastDFS installation and deployment (Server)
- Ubuntu 12.04 configure NVIDIA CUDA 5.5 Record (Linux)
- MD5 and simple to use (Linux)
- Ubuntu install the camera driver (Linux)
- The basic method RHEL6 (CentOS6) used in the source package compiled RPM: Upgrade OpenSSH articles (Linux)
- Help you make Git Bisect (Linux)
- Easy to install CentOS 6.6 desktop environment (Linux)
- DB2 manually create a library (Database)
- How to find the available network adapter on Ubuntu (Linux)
- Killall five options you might not know (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.