Reprint please indicate the source of Wang 亟亟 's Daniel Road
Its easy-to-hold, its non-trillion easy to seek, its crisp and easy, its micro-easy to disperse. For it is not, the rule is not chaos. EnCircle of wood, born in margins, nine-storey platform, starting from the base of soil; If the person loses, the holder loses it. is to do without the Saints do not lose, no hold no loss. The people engaged, often in a few into and defeated. If you start with caution, there is no defeat. is to the sage desire, not expensive goods, learn not to learn, complex all the past, in order to complement the nature of everything and dare not.
As a series of topics in the first article, this article is a small dystocia, the middle mixed with some work, some egg pain (learning cars, etc.), to say the truth, after doing a coder found spare time is really not too much .... Alas... The first 5 6 articles of the entire column will be simpler and more manageable.
Package directory:
Okay, no more nonsense, go to the chase.
What does this article do?
Simple encapsulation of the most commonly used activity we normally use to meet the underlying needs
What is encapsulation? What are the benefits of encapsulation?
1. Combine abstract data with behavior (or function) to form an organic whole.
2. To enhance security and simplify programming, the user does not need to know the specifics of the implementation, but only to use the members of the class with specific access rights through the external interface.
This article is from defining our own baseapplication and baseactivity
Why would you do that?
The vernacular version: What initializes, splinters a whole bunch of toast dialog tools all in, let the subsequent activity of the business clearer.
each time the example is to write their own thoughts, quality, good or bad objective forgive
Baseactivity
Public class baseapplication extends application{ / * Initialize tag * */ Private StaticString Tag=baseapplication.class.getname ();/*activity Heap * / PrivateStack<activity> Activitystack =NewStack<activity> ();@Override Public void onCreate() {Super. OnCreate (); LOGUTILS.D (tag,tag+"---onCreate ()"); Printappparameter (); }/ * Print out the parameters of some apps * / Private void Printappparameter() {LOGUTILS.D (TAG,"OS:"+build.version.release +" ( "+ Build.VERSION.SDK_INT +" )"); Devicemgr.scrsize realsize = Devicemgr.getscreenrealsize ( This); LOGUTILS.D (TAG,"screen Size:"+ REALSIZE.W +"X"+ realSize.h); } Public void addactivity(FinalActivity Curat) {if(NULL= = Activitystack) {Activitystack =NewStack<activity> (); } activitystack.add (Curat); } Public void removeactivity(FinalActivity Curat) {if(NULL= = Activitystack) {Activitystack =NewStack<activity> (); } activitystack.remove (Curat); }//Get last activity PublicActivitycurrentactivity() {Activity activity = activitystack.lastelement ();returnActivity }//Returns the total number of activity in the village Public int howmanyactivities() {returnActivitystack.size (); }//Close all activity Public void finishallactivities() { for(inti =0, size = Activitystack.size (); i < size; i++) {if(NULL! = Activitystack.get (i)) {activitystack.get (i). Finish (); }} activitystack.clear (); }}
The above is a more commonly used implementation that declares an Stack<Activity> activity that is not destory in the process of storing the project. Write a few common additions and deletions, and then print out the properties of some apps.
What else can you do in application?
Initializes third-party controls, such as initialize Imageloader, with operations such as SP, cache, etc.
Called in the OnCreate method
//创建默认的ImageLoader配置参数 configuration = ImageLoaderConfiguration .createDefault(this); withconfiguration. ImageLoader.getInstance().init(configuration);
Write some common methods such as Toast Dialog etc.
Simplified toast
publicvoidshowMyToast(finalint textResId) { showMyToast(curAT, textResId, Toast.LENGTH_LONG); }
Quit App
public void exit() { TRIeIDLog.logD(TAG, "finishAllActivities..."); finishAllActivities(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); }
Such methods can be written in application.
Then we'll look at our baseactivity.
Public Abstract class baseactivity extends Activity {Inputmethodmanager _inputmethodmanager;protectedResources Res;protectedBaseapplication Baseapp;protected Static FinalString TAG = BaseActivity.class.getName ();@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (GetLayout ()); res = This. Getapplicationcontext (). Getresources (); Baseapp = (baseapplication) This. Getapplication (); _inputmethodmanager = (Inputmethodmanager) getsystemservice (Context.input_method_service); This. GetWindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); FindByID (); Setlistener (); Logic (); Baseapp.addactivity ( This); }@Override Public Boolean ontouchevent(Motionevent event) {if(event.getaction () = = Motionevent.action_down) {if(Getcurrentfocus ()! =NULL&& Getcurrentfocus (). Getwindowtoken ()! =NULL) {_inputmethodmanager.hidesoftinputfromwindow (Getcurrentfocus (). Getwindowtoken (), Inputmethodmanager.hide_not_always); } }return Super. Ontouchevent (event); }@Override protected void OnPause() {Super. OnPause (); }@Override protected void Onresume() {Super. Onresume (); }@Override protected void OnDestroy() {Super. OnDestroy (); Baseapp.removeactivity ( This); }//findbyid protected Abstract void FindByID();//setlistener protected Abstract void Setlistener();//logic protected Abstract void Logic();protected Abstract int GetLayout();//Whether the minimum SDK is supported protected Boolean ISSUPPORTEDSDK(intSdkvercode) {LOGUTILS.D (TAG,"Issupportedsdk-configutil.min_sdk_ver_code = \" "+ Configutil.min_sdk_ver_code +"\""); LOGUTILS.D (TAG,"Issupportedsdk-sdkvercode = \" "+ Sdkvercode +"\"");returnSdkvercode >= Configutil.min_sdk_ver_code; }//Network error type protected int Getnetworkerrortip(intCode) {LOGUTILS.D (TAG,"Getnetworkerrortip-code = \" "+ code +"\"");intTextresid = R.string.error_network_time_out;Switch(code) { CaseRespHandleListener.ErrCode.ERR_NETWORK_NOT_AVAILABLE:textResId = r.string.error_network_not_available; Break; CaseRespHandleListener.ErrCode.ERR_SERVER_ERROR:textResId = R.string.error_network_server_busy; Break; CaseRespHandleListener.ErrCode.ERR_TIME_OUT: CaseRespHandleListener.ErrCode.ERR_CLIENT_ERROR: CaseRespHandleListener.ErrCode.ERR_UNKNOWN_ERROR: Break;default: Break; } LOGUTILS.D (TAG,"getnetworkerrortip-textresid = \" "+ Textresid +"\"");returnTextresid; }}
The tool interface of network judgment
Resphandlelistener
Public interface resphandlelistener {Class Errcode { Public Static Final intErr_succeed =0; Public Static Final interr_network_not_available =-1; Public Static Final intErr_time_out =-2; Public Static Final intErr_server_error =-3; Public Static Final intErr_client_error =-4; Public Static Final intErr_unknown_error =-5; }voidOnError (intcode);voidOnreqbegin ();voidOnreqend (String jsonresp);}
Analysis:
Some of the methods in the previous baseapplication were called in the Baseactivity, and the baseactivity also made a simple encapsulation of our oncreate, separating the business logic from the control snap operations.
(Specific use, will be posted later)
So what else can we do in the baseactivity?
Toast can also be done here, dialog is the same
protectedvoidshowErrorToast(int code) { baseApp.showMyToast(this, getNetworkErrorTip(code)); }
Network Judgment Tool Class Getnetworkerrortip ()
Screen information can also be obtained here by default, as well as some hardware conditions such as NFC BLE (This section will be written in the next post)
Next, post the demo code
Public class mainactivity extends baseactivity implements View. Onclicklistener {Button button;@Override protected void FindByID() {button= (button) Findviewbyid (R.id.button); }@Override protected void Setlistener() {Button.setonclicklistener ( This); }@Override protected void Logic() {LOGUTILS.D ("-------->logic", Add (1,3)); }@Override protected int GetLayout() {returnR.layout.activity_main; }@Override Public void OnClick(View v) {if(V.getid () ==r.id.button) {Toast.maketext (mainactivity). This,"Click on the button", Toast.length_short). Show (); } }Private int Add(intAintb) {returnA+b; }}
Run effect
To do so, mother no longer worry about my OnCreate method hundreds of line, no longer worry about me less findbyid a control, of course, you can further simplify the package with generics <T> to control the operation, this will be written in the following article.
Third-party libraries used:
A very simple log library
‘com.apkfuns.logutils:library:1.0.6‘
Source: http://yunpan.cn/cmNbQInJuKHXw Access Password 4a23
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Start from the beginning of the baseapplication/activity code