Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Android development, may cause a memory leak problem     - Oracle inverted reverse function (Database)

- Oracle Automatic Diagnostic Repository (Automatic Diagnostic Repository, ADR) (Database)

- View processes and threads under Linux (Linux)

- Visual Studio Code experience (Linux)

- Java Builder mode (Programming)

- Performance Optimization: Using Ramlog transfer log files to memory (Linux)

- Linux port mapping system (routing and forwarding) (Server)

- Disk Management LVM (Linux)

- Ora-1092: OPI colleague K aborting process --- killed by OO Well killer (Database)

- iptables allow only specific ip address to access the specified port (Linux)

- ctop: monitor container performance Linux command line artifact (Linux)

- How to track performance issues when using the Unity Game Development Android (Programming)

- Linux Network Security: nmap port scanning software (Linux)

- Linux --- manual release system cache (Linux)

- Java learning problems encountered (Programming)

- Wi-Fi hackers use to attack your seven methods (Linux)

- Oracle query start with connect by tree (Database)

- Merge Sort (Programming)

- Two strokes to improve development productivity Struts2 (Programming)

- Eight sorting algorithm implemented in Python (Programming)

 
         
  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:      
 
- BusyBox build root file system (Linux)
- Learning the Linux powerful network management capabilities (Linux)
- Github with .gitignore ignore specified file (Linux)
- Tmux Getting Start (Linux)
- Linux operating system security settings initial understanding (Linux)
- Linux System Getting Started Learning: Using the Linux command line detected DVD burner name and write speeds (Linux)
- Linux program analysis tool: ldd and nm (Linux)
- Linux settings Java_home (Linux)
- Two kinds of agents of Spring AOP (Programming)
- MySQL & NoSQL - Memcached widget (Database)
- CentOS 6.5 / Linux restart network card being given Determining if ip address x.x.x.x is already in use (Linux)
- Analysis of MySQL Dockerfile 5.6 (Database)
- FastDFS installation and deployment (Server)
- How to install Eclipse Luna IDE on CentOS 7 / RHEL 7 (Linux)
- Singleton (Linux)
- Linux modify the system time (Linux)
- Five Linux user space debugging tool (Linux)
- GEC2440 easiest a kernel compile Linux2.6.30.4 (Programming)
- GAMIT10.5 under CentOS installation (Linux)
- CentOS 7 virt-manager can not connect a local hypervisor (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.