Android App Framework design base class Baseactivity

Source: Internet
Author: User

Android App Framework design base class Baseactivity

Writing base class Baseactivity
-The ability to share the parent class within a subclass of OOP to improve the reusability of the Code
-The base class is written according to the actual project situation, some may be very simple such as just display "about" information, business functions very few you can not inherit the base class to expand

Baseactivity inherit activity or fragmentactivity or something? Also according to your technical requirements, because there are many ways to solve the problem, or you do not have to write the base class can also complete the work.
Our goal is to write better code, improve code reusability, extensibility, and especially teamwork, which is one of the reasons why OOP occurs.

What should be written about the base class? The common code.

    • Network Environment Monitoring
    • Unified Data Interface
    • The life cycle different methods should do things

Just at work, look at spring source code does not know why engage so many interfaces and objects, a layer of. With the accumulation of experience, we know the benefits of OOP.

Below we write a base class that is not complex. Suppose our business is the company's mobile OA system we need to manage our employees.
Abstraction of an employee

//domine is a generic entity class that can be useful later as a generic parameter Public  class Employee extends domine {    Private Static Final LongSerialversionuid =1L Public Employee() {    } PublicString FullName; PublicString Mobiletel; PublicString email; PublicString EmpNo;}//Can add public properties Public  class Domine implements Serializable {    Private Static Final LongSerialversionuid =1L Public Domine() {    } Public intId PublicString desc;}

Model of data interaction

publicclass MData<T> implements Serializable {    privatestaticfinallong1L;    public String id;    public String type;    public T dataList;//多种类型数据,一般是List集合,比如获取所有员工列表}

Here is the data callback interface, we need to notify the UI to get the data from the network side

publicinterface IDataCallback<T> {//我们一样传入通用类型    publicvoidonNewData(T data);    publicvoidonError(String msg,int code);}

The following is an independent out of a uihandler, generally written in the activity inside as the inner class, I have no

 Public  class uihandler extends Handler {    PrivateIhandler handler;//callback interface, message passed to registrant     Public Uihandler(Looper Looper) {Super(Looper); } Public Uihandler(Looper Looper,ihandler handler) {Super(Looper); This. handler = handler; } Public void SetHandler(Ihandler handler) { This. handler = handler; }@Override     Public void Handlemessage(Message msg) {Super. Handlemessage (msg);if(Handler! =NULL) {handler.handlemessage (msg);//Have a message, just deliver}    }} Public  interface ihandler {     Public void Handlemessage(Message msg);}

We have the basics, and now we're combining them into the baseactivity.

 Public Abstract  class baseactivity extends Activity {    //You can put constants in a single class     Public Static FinalString Action_network_change ="Android.net.conn.CONNECTIVITY_CHANGE"; Public Static FinalString Action_push_data ="Fm.data.push.action"; Public Static FinalString action_new_version ="Apk.update.action";protected StaticUihandler handler =NewUihandler (Looper.getmainlooper ());//Data callback interface, both passing Domine of the subclass entity    protectedidatacallback<mdata<? Extends domine>> Datacallback; Public baseactivity() {    }//This place has a kind of "template method" design pattern look like    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        SetBase ();        SetHandler ();    Initcontentview (savedinstancestate); }Private void SetHandler() {Handler.sethandler (NewIhandler () { Public void Handlemessage(Message msg) {handler (msg);//The method to be submitted to the subclass implementation with the message}        }); }//Initialize Ui,setcontentview, etc.    protected Abstract void Initcontentview(Bundle savedinstancestate);//May be full screen or no actionbar etc.    Private void SetBase() {requestwindowfeature (window.feature_no_title);//Case}protected void Addleftmenu(BooleanEnable) {//If your project has a skid bar to handle this method        if(enable) {//can have slide bar}Else{        }    }//Komi class processing messages    protected Abstract void Handler(Message msg);//Screen switch, keyboard, etc.    @Override     Public void onconfigurationchanged(Configuration newconfig) {Super. onconfigurationchanged (Newconfig); }@Override    protected void onrestoreinstancestate(Bundle savedinstancestate) {Try{Super. Onrestoreinstancestate (Savedinstancestate); }Catch(Exception e) {        }    }@Override    protected void Onresume() {Super. Onresume ();//You can add multiple action capturesIntentfilter filter =NewIntentfilter ();        Filter.addaction (Action_network_change);        Filter.addaction (Action_push_data);        Filter.addaction (action_new_version); Registerreceiver (receiver, filter);//may also send statistics, such as third-party SDK to do statistical requirements}@Override    protected void OnPause() {Super. OnPause (); Unregisterreceiver (receiver);//may also send statistics, such as third-party SDK to do statistical requirements} broadcastreceiver receiver =NewBroadcastreceiver () {@Override         Public void OnReceive(context context, Intent Intent) {//Handle various situationsString action = Intent.getaction ();if(Action_network_change.equals (ACTION)) {//Network Changes                //Handling network problems}Else if(Action_push_data.equals (ACTION)) {//may have new dataBundle B = Intent.getextras (); Mdata<employee> Mdata = (mdata<employee>) b.get ("Data");if(Datacallback! =NULL) {//Data NotificationDatacallback.onnewdata (Mdata); }            }Else if(Action_new_version.equals (ACTION)) {//May find a new version                //Versiondialog may be the version prompt if you need to download the dialog box}        }    }; Public void Setdatacallback(idatacallback<mdata< extends domine>> datacallback) { This. Datacallback = Datacallback; }}

With the base class now write a subclass activity

 Public  class employeedisplayactivity extends baseactivity implements Idatacallback<mdata<? extends Domine>> { //Implement data callback interface     Public employeedisplayactivity() {    }@Override    protected void Initcontentview(Bundle savedinstancestate)        {Setcontentview (R.layout.activity_main);    LoadData (); }Private void LoadData() {Setdatacallback ( This);//Set callback function        //We can also pass this callback to other classes that fetch data, such as HTTP fetch data        //such as Httclient.get (Url,this);}@Override     Public void Onnewdata(mdata<? extends domine> data) {//update UI Update UI Data        Finallist<employee> list = (list<employee>) data.datalist; Handler.post (NewRunnable () { Public void Run() {//Update UI}        });//orHandler.sendemptymessage (0);//Notify Handler}@Override     Public void OnError(FinalString msg,Final intCode) {Handler.post (NewRunnable () { Public void Run() {//Notification error message}        });//orHandler.sendemptymessage (0);//Notify Handler}@Override    protected void Handler(Message msg) {//We can process the data message.        Switch(msg.what) { Case 0: Break; Case-1: Break;default: Break; }    }}

UML diagrams

This article has written the basic baseactivity code, obviously cannot be perfect, needs unceasingly to study and the improvement, has the question to welcome the discussion, Thanks.

Android App Framework design base class Baseactivity

Related Article

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.