"Android Advanced" Why do you create activity base classes and what are the common methods in the activity base class?

Source: Internet
Author: User

Now also is just basically completed their first business project, in the process of development, referring to a lot of people's code style, but with the accumulation of work experience, and finally began to slowly understand the importance of abstract ideas in object-oriented programming, this simple introduction of my little harvest.

first, In the current project is mainly used in the afinal framework, and this framework is really good, save a lot of work, in the process of writing activities, the basic is directly inherited from the Finalactivity class, so you can use this class for us to encapsulate a lot of methods, But as the project progresses slowly, some of the drawbacks of this direct inheritance framework class are beginning to show up slowly. The main thing is that extensibility is subject to some limitations, such as the activity, we generally do the initialization of the control, in order to make the code style more concise introduction, I usually in a separate Initview () method to implement the initialization of the control, This method is then called directly in OnCreate to initialize the control. In addition, in a lot of activity involving the network connection needs to detect the network situation, if the network situation problems, pop up a 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 in each activity to set it up. But since we are directly integrated from finalactivity, one implementation is to directly modify the source code of our finalactivity and add these common methods, but this modifies the source code of the external framework, increasing the coupling between the code, When we need to use this framework in another project, we need to change the source code, so that way to solve the problem, but not the best solution.

Another solution is for us to write another activity base class baseactivity, which is also inherited from Finalactivity, and in this base class we can implement some common methods, so that other activity inherits from our Baseactivity base class, you can either use the finalactivity inside the encapsulated method, or you can use some of the public methods we extend in the baseactivity. If we were to abstract a layer, we could abstract these common methods into an interface, and then our baseactivity implement the interface, which would also enable the extension of the program.

Here are some of the code I've compiled

The first is an abstraction of an activity interface.

/** * Activity support class interface, mainly defines the functions commonly used in activity * * @Package com.example.myallutils * * TODO * @author Zhaokaiqiang * * @time May 7, 2014 */public interface ibaseactivity {/** * Get Application Object * * @return */public Abstract Application Geta Pplication ();/** * Open service */public abstract void StartService ();/** * Stop service */public abstract void StopService ();/** * Determine if there is a network Connection, if not, the Network Settings dialog box, return False * * @return */public Abstract Boolean validateinternet ();/** * * Determine if there is a network connection, no return false * */pub Lic abstract Boolean hasinternetconnected ();/** * Exit application */public abstract void Isexit ();/** * Determine if GPS is turned on. * * @return */public Abstract Boolean Haslocationgps ();/** * Determine if the base station is 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 ();/** * Whether the user is online (the current network is not re-connected successfully) */public Boolean getuseronlinestate ();/** * Set user online status True online false not online * * @param isOnline */public void Setuseronlinestate (Boolean isOnline);/** * * Notification method is emitted. * * @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


/** * Activity base class, implements the Iactivitysupport interface * * @Package com.example.myallutils * * TODO * @author Zhaokaiqiang * * @time May 7, 2014 */public abstract class Baseactivity extends finalactivity implementsibaseactivity {protected Context MC Ontext = null;protected 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 services required to open * * @Overridepublic void StartService () {}/** * here to close all services that need to be opened */@Overridepublic void StopService () {}/ * * Stop the service and end all activity exit apps */@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 ();} /** * Determines if there is a network connection, does not 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;} /** * To determine if there is an Internet connection, if not, the Network Settings dialog box pops up and 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 (in Fo[i].getstate () = = NetworkInfo.State.CONNECTED) {return true;}}} Openwirelessset (); return false;} /** * Determine 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;}} /** * Determine 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 ("Detect 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, which will run as a click on the notification Message Bar Activityintent Notifyintent = new Intent (this, activity); Notifyintent.putextra ("tO ", to);//Create pendingintent as the activitypendingintent of the set deferred run appintent = pendingintent.getactivity (mcontext, 0, Notifyintent, 0);/* Create Notication, and set related parameters */notification Mynoti = new Notification ();//click Auto disappear mynoti.flags = Notification . flag_auto_cancel;/* Set statusbar Display icon */mynoti.icon = iconid;/* Set statusbar display text message */mynoti.tickertext = Contenttitle */* Set Notification when the default sound */mynoti.defaults = notification.default_sound;/* Set the parameters of the Notification 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, "Hee-ha");}}

After a few layers of abstraction, we can see that the extension of code and coupling has indeed been a certain improvement, this article only for the rookie, if there are people lucky to see this article, but also hope to teach one or two!



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.