Android Development: A brief talk on MVP mode application and memory leak

Source: Internet
Author: User

Recently, bloggers began to practice the MVP model in the project, but unexpectedly found that the memory leak is more serious, but few people talk about this issue, prompting the publication of this article, this article assumes that the reader has understood the MVP architecture.

Author of this article: Xiong_it, Link: http://blog.csdn.net/xiong_it

About MVP

M-modle, data, logic operations layer, data acquisition, data persistence and preservation. such as network operations, database operations
V-view, interface display layer, the specific embodiment of Android in Activity,fragment
P-presenter, mediator, connects Modle,view layer while holding modle reference and view interface reference

Excerpt from Ruan Yi Feng's Great God Blog: MVC,MVP and MVVM icons

Note: Unlike mvc,activity,fragment, it is often used as a controller and view, which adds to its responsibilities. In the MVP, Activity,fragment is used only as a view layer display

Sample code

Author of this article: Xiong_it, Link: http://blog.csdn.net/xiong_it

Modle Layer Operations

 Public  class testmodle implements imodle{    PrivateCallbacklistener callback; Public Testmodle(Callbacklistener callback) { This. callback = callback; } Public  interface callbacklistener {        voidOngetdata (String data); } Public void GetData() {NewThread () { Public void Run() {Callback.ongetdata ("returned data");    }}.start (); }}

View Layer

//Abstract View layer Public  interface testviewinterf extends IView {    voidOngetdata (String data);}//Specific view layer Public  class mainactivity extends Activity implements Testviewinterf {    PrivateTestpresenter Mtestpresenter;@Override     Public void onCreate(@Nullable Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);The //View layer delegates the task of acquiring data to the mediator, presenter, and passing in its own instance object, implementing the Testviewinterf interfaceMtestpresenter =NewTestpresenter ( This);    Mtestpresenter.getdata (); }@Override     Public void Ongetdata(String data) {//view layer only for data displayShowtoast (data); }Private void Showtoast(String Toast) {Toast.maketext ( This, Toast, Toast.length_long). Show (); }}

Presenter Intermediary

 Public  class testpresenter implements IPresenter{Imodle Modle; IView view; Public Testpresenter(IView view) { This. view = view; } Public void GetData() {//The operation to get data is actually performed at the modle levelModle =NewTestmodle (NewCallbacklistener () { Public void Ongetdata(String data) {if(View! =NULL) {view.ongetdata (data);        }            }        });    Modle.getdata (); }}

According to OOP, Java should be interface-oriented, in order to be compliant with the OCP principle. The example code above omits the more abstract interface Imodle,iview,ipresenter, and the actual MVP practice typically introduces generics to make it more extensible.

Google has provided the relevant sample code and added a constraint to the MVP: contract, which defines the MVP interface for each module.
Google MVP Sample Code:https://github.com/googlesamples/android-architecture

Memory leak issues

Visible from the presenter, the view interface object is held in the This interface object is actually Mainactivity.this,modle also has the presenter object instance, when mainactivity to destroy, presenter Modle in the acquisition of data, then the problem comes, the activity can be destroyed normally?
the answer is NO!
When Modle gets the data, it always holds the presenter object, and the presenter object holds the activity object, and the GC chain does not cut and the activity cannot be fully recycled.
In other words: Presenter not destroyed, activity will not be properly recycled.

Solve the MVP's memory leak

Presenter performs a resource release operation when the activity's OnDestroy method callback, or uses a soft reference that is easier to recycle when presenter references the View object.
For example code:
Activity

@Override    publicvoidonDestroy() {        super.onDestroy();        mPresenter.destroy();    }

Presenter

publicvoiddestroy() {    null;    ifnull) {        modle.cancleTasks();    }}

Modle

publicvoidcancleTasks() {    // TODO 终止线程池ThreadPool.shutDown(),AsyncTask.cancle(),或者调用框架的取消任务api}

Author of this article: Xiong_it, Link: http://blog.csdn.net/xiong_it

Personal Summary

Because the MVP interface is programmed to accommodate changes in requirements, the MVP is suitable for larger projects, because it simplifies activity and fragmnt, greatly reducing the amount of code in the view layer, compared to the amount of code in MVC that activity,fragment thousands of lines, It's elegant!

After the above operation, because the MVP caused by the memory leak is almost solved, I wish you a happy code! Welcome to the message area to communicate correct.

Android Development: A brief talk on MVP mode application and memory leak

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.