"Android Advanced" Why do we create activity base class activity what is the general base class method

Source: Internet
Author: User

Today, it can be regarded as just the basic completion of its first commercial project, in the development process, style, however with the accumulation of work experience. Finally beginning to understand the importance of abstract thought in object-oriented programming, this article briefly introduces a little bit of my harvest.

First of all, the afinal framework is mostly used in today's projects, and the framework is indeed quite good, saving a lot of effort. In the process of writing activities, the basic is directly inherited from the Finalactivity class, so that we can use this class to encapsulate a lot of methods, but as the project slowly advancing, such a direct inheritance framework class of some shortcomings also began to appear slowly. The basic thing is that extensibility is constrained by, for instance, the initialization of controls for activity. To make the code more straightforward, I usually initialize the control in a separate Initview () method, and then call this method directly in OnCreate to initialize the control. In addition, in a lot of activity involving the network connection needs to detect the network situation, assuming that the network condition is faulty, a popup dialog box to remind users to set up the network or check.

Like this, we'd better have a separate approach, so we don't have to write a lot of code to set up in every activity.

But because we are directly integrated from the finalactivity, so a solution is to directly change our finalactivity source code, add these public methods. However, this changes the external framework of the source code, add the coupling between the codes, when we need to use this framework in another project, we need to change the source code. So this is the way to solve the problem, but not the best way to solve it.

The second solution is for us to write another activity base class baseactivity, which is also inherited from Finalactivity, and in this base class we are able to implement some common methods. Such other activity is inherited from our baseactivity base class. It is possible to use a method that is encapsulated in finalactivity. We can also use some of the public methods that we extend in baseactivity. Let's say we're going to abstract another layer. We are able to abstract these common methods into an interface. Then our baseactivity implements this interface, which also enables the extension of the program.

Here are some of the code I've compiled

The first is an abstraction of an activity interface.

/** * Activity's support class interface, which mainly defines the functions often used in activity * * @Package com.example.myallutils * * TODO * @author Zhaokaiqiang * * @time May 7, 2014 */public interface ibaseactivity {/** * Get Application Object * * @return */public abstract Application ge Tapplication ();/** * Open service */public abstract void StartService ();/** * Stop service */public abstract void StopService ();/** * Infer if There is an Internet connection, if not, the Network Settings dialog box pops up. Returns false * * @return */public Abstract Boolean validateinternet ();/** * * Infer if there is a network connection, no return false * */public abstract Boolea n hasinternetconnected ();/** * Exit application */public abstract void Isexit ();/** * Infer whether the GPS is turned on. * * @return */public Abstract Boolean Haslocationgps ();/** * Infer if the base station is already open. */public Abstract Boolean haslocationnetwork ();/** * Check memory card. */public abstract void Checkmemorycard ();/** * Gets the progress bar. * * @return */public abstract progressdialog getprogressdialog ();/** * Returns the current activity context. */public abstract Context getcontext ();/** * Gets the sharedpreferences configuration of the currently logged-on user. */public sharedpreferences Getloginusersharedpre ();* * User is online (whether the current network is re-connected successfully) */public Boolean getuseronlinestate ();/** * Set user online status True online false not online * * @param isOnline */PUBL IC void Setuseronlinestate (Boolean isOnline);/** * * emits notification method. * * @param iconid * icon * @param contenttitle * Title * @param contenttext * content * @param act ivity */public void pushnotification (int iconid, string contenttitle,string contenttext, class<?> activity, string from);}


The following is an implementation of this interface, which is the base class for all activity


/** * base class for activity. Implements the Iactivitysupport interface * * @Package com.example.myallutils * * TODO * @author Zhaokaiqiang * * @time May 7, 2014 */public abstract class Baseactivity extends finalactivity implementsibaseactivity {protected Context Mcontext = Null;pro tected sharedpreferences preferences;protected MyApplication myapplication;protected ProgressDialog pg = NULL; protected Notificationmanager Notificationmanager; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); mcontext = This;preferences = Getsharedpreferences ("TAG", 0); NotificationManager = (Notificationmanager) getsystemservice (notification_service);p g = new ProgressDialog (mcontext); myApplication = ( MyApplication) getapplication ();} /** * Initialize page layout */abstract void Iniview (), @Overrideprotected void OnStart () {Super.onstart ();} @Overrideprotected void Onresume () {Super.onresume ();} @Overrideprotected void OnPause () {super.onpause ();} @Overrideprotected void OnStop () {super.onstop ();} @Overridepublic void OnDestroy () {Super.ondestroy ();} @Overridepublic ProgressDialog Getprogressdialog () {return PG;} /** * Here to open all the services required to open * * @Overridepublic void StartService () {}/** * here to close all services required to open * * @Overridepublic void StopService () {}/ * * Stop the service and end the full activity exit app */@Overridepublic void Isexit () {new Alertdialog.builder (Mcontext). Settitle ("OK to exit?"). Setneutralbutton ("OK", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {stopservice (); Myapplication.exit ();}}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {dialog.cancel ();}}). Show ();} /** * Infer If there is a network connection, no return false */@Overridepublic Boolean hasinternetconnected () {Connectivitymanager manager = ( Connectivitymanager) Mcontext.getsystemservice (Context.connectivity_service), if (manager! = null) {Networkinfo Network = Manager.getactivenetworkinfo (); if (network! = null && network.isconnectedorconnecting ()) {returntrue;}} return false;} /** * Infer If there is an Internet connection, if not. The Network Settings dialog box pops up. Returns false */@Overridepublic Boolean validateinternet () {Connectivitymanager manager = (Connectivitymanager) Mcontext.getsystemservice (Context.connectivity_service); if (manager = = null) {Openwirelessset (); return false;} else { Networkinfo[] info = manager.getallnetworkinfo (), if (info! = null) {for (int i = 0; i < info.length; i++) {if (Info[i]. GetState () = = NetworkInfo.State.CONNECTED) {return true;}}} Openwirelessset (); return false;} /** * Infer if the GPS location service is on/@Overridepublic Boolean Haslocationgps () {Locationmanager manager = (Locationmanager) Mcontext.getsystemservice (Context.location_service); if (manager.isproviderenabled ( Android.location.LocationManager.GPS_PROVIDER) {return true;} else {return false;}} /** * Infer If base station positioning is on/@Overridepublic Boolean haslocationnetwork () {Locationmanager manager = (Locationmanager) Mcontext.getsystemservice (Context.location_service); if (manager.isproviderenabled ( Android.location.LocationManager.NETWORK_PROVIDER) {return true;} else {return false;}} /** * Check memory card readable */@Overridepublic void Checkmemorycard () {if (! Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ())) {new Alertdialog.builder (Mcontext). Settitle ("Test memory Card"). Setmessage ("Please check memory card"). Setpositivebutton ("Settings", new Dialoginterface.onclicklistener () {@ overridepublic void OnClick (Dialoginterface dialog,int which) {dialog.cancel (); Intent Intent = new Intent ( settings.action_settings); mcontext.startactivity (intent);}}). Setnegativebutton ("Exit", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int which) {dialog.cancel ();}}). Create (). Show ();}} /** * Open Network Settings dialog box */public void Openwirelessset () {Alertdialog.builder dialogbuilder = new Alertdialog.builder (mContext); Dialogbuilder.settitle ("Network Settings"). Setmessage ("Check Network"). Setpositivebutton ("Network Settings", New Dialoginterface.onclicklistener ( {@Overridepublic void OnClick (Dialoginterface dialog,int which) {dialog.cancel (); Intent Intent = new Intent ( Settings.action_wireless_settings); mcontext.startactivity (intent);}}). Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface dialog, int Whichbutton) {dialog.cancel ();}}); Dialogbuilder.show ();} /** * off keyboard */public void Closeinput () {Inputmethodmanager Inputmethodmanager = (inputmethodmanager) getSystemService ( Context.input_method_service); if (Inputmethodmanager! = null && this.getcurrentfocus () = null) { Inputmethodmanager.hidesoftinputfromwindow (This.getcurrentfocus (). Getwindowtoken (), InputMethodManager.HIDE_NOT _always);}}            /** * * Issue notification * * @param iconid * icon * @param contenttitle * Title * @param contenttext * You content * @param activity */@SuppressWarnings ("deprecation") public void pushnotification (int iconid, String Contentti Tle,string ContentText, class<?> activity, String to) {//Create a new intent. The activityintent notifyintent = new Intent (this, activity) will be executed as a click on the notification Message Bar, Notifyintent.putextra ("tO ", to);//Create pendingintent as set deferred execution activitypendingintent appintent = pendingintent.getactivity (mcontext, 0, Notifyintent, 0);/* Create Notication, and set the relevant number */notification Mynoti = new Notification ();//Click on your own initiative to disappear Mynoti.flags = notification.flag_auto_cancel;/* Set statusbar Display icon */mynoti.icon = iconid;/* Set StatusBar display of text information */mynoti.tickertext = contenttitle;/* Settings Notification occurs when the default sound is issued */mynoti.defaults = notification.default_sound;/* Set Notification The number of messages in the message Bar */mynoti.setlatesteventinfo (Mcontext, Contenttitle, contenttext,appintent);/* Send notification */ Notificationmanager.notify (0, Mynoti);} /** * Returns the context object */@Overridepublic Context GetContext () {return mcontext;} /** * Returns the Sharedpreferences object of the logged-on user */@Overridepublic sharedpreferences Getloginusersharedpre () {return preferences;} /** * Get user Online Status */@Overridepublic Boolean getuseronlinestate () {return false;} /** * Set User Online status */@Overridepublic void Setuseronlinestate (Boolean isOnline) {}}

This can be used in our defined activity.


/** *  * @Package com.example.myallutils *  *          TODO * @author Zhaokaiqiang *  * @time May 6, 2014 */public class Mainactivity extends Baseactivity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Iniview (); } @Overridevoid Iniview () {mcontext = This;validateinternet (); Pushnotification (R.drawable.ic_launcher, "test", "Content test", Otheractivity.class, "hehe");}

After several layers of abstraction. As we can see, the extensibility and coupling of the code has certainly improved. This article is for beginners only, assuming that a bull is fortunate enough to see this article. Also hope to be able to advise one or two!



Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

"Android Advanced" Why do we create activity base class activity what is the general base class method

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.