From the beginning, click "Start with BaseApplication/Activity" and click "applicationactivity ".

Source: Internet
Author: User

From the beginning, click "Start with BaseApplication/Activity" and click "applicationactivity ".
Reprinted, please indicate the path of the great ox from Wang Xiaoying

Its security is easy to maintain, and it is not easy to seek; its security is easy to disperse. For nothing, Governance for nothing. The wood of the hug, born at the end of the ml; the Nine-layer platform, started from the ground; a journey of thousands of miles, began in the foot. If the provider fails, the provider loses. It is because the sage does not do anything, so there is no failure, no failure. People often fail to do so. If you start with caution, there will be no failure. It is because the holy people do not want, not expensive and rare goods, do not learn, restore the people's place, to supplement the nature of all things and do not dare.

As the first article of the series of topics, this article is a little difficult, with some work-related issues in the middle, some egresses (such as learning cars). To be honest, after Coder, I found that not too much spare time .... Alas... The first five or six articles of the entire column will be relatively simple and convenient.

Package directory:

Good. You don't need to get started.

What is this article?
Simple encapsulation of the most commonly used Activity to meet basic requirements

What is encapsulation? What are the advantages of encapsulation?
1. Combine abstract data with behaviors (or functions) to form an organic whole.
2. Enhanced security and simplified programming. Users only need to use class members with specific access permissions through external interfaces without having to know the specific implementation details.

This article defines our own BaseApplication and BaseActivity.

Why?
Vernacular version: We will drop all the Toast Dialog tools in initialization to make the subsequent activities clearer.

Every example is written by yourself. Quality is objective. Sorry.

BaseActivity

Public class BaseApplication extends Application {/** initialization TAG **/private static String TAG = BaseApplication. class. getName ();/* Activity heap */private Stack <Activity> activityStack = new Stack <Activity> (); @ Override public void onCreate () {super. onCreate (); LogUtils. d (TAG, TAG + "--- onCreate ()"); printAppParameter ();}/* print out some app parameters */private void printAppParameter () {LogUtils. d (TAG, "OS:" + Build. VERSI ON. RELEASE + "(" + Build. VERSION. SDK_INT + ")"); DeviceMgr. scrSize realSize = DeviceMgr. getScreenRealSize (this); LogUtils. d (TAG, "Screen Size:" + realSize. w + "X" + realSize. h);} public void addActivity (final Activity curAT) {if (null = activityStack) {activityStack = new Stack <Activity> ();} activityStack. add (curAT);} public void removeActivity (final Activity curAT) {if (null = activ ItyStack) {activityStack = new Stack <Activity> ();} activityStack. remove (curAT);} // obtain the last public Activity currentActivity () {Activity = activityStack. lastElement (); return activity;} // returns the total number of activities in the village. public int howManyActivities () {return activityStack. size () ;}// close all activities public void finishAllActivities () {for (int I = 0, size = activityStack. size (); I <size; I ++ ){ If (null! = ActivityStack. get (I) {activityStack. get (I). finish () ;}} activityStack. clear ();}}

The above is a commonly used implementation, which declaresStack<Activity>Used to store activities that are not Destory during the project process. Write several operations that are commonly used for adding, deleting, and querying, and print out some APP attributes.

What else can I do in the Application?
Initialize third-party controls such as ImageLoader and Sp and cache operations.
Call in onCreate Method

// Create the default ImageLoader configuration Parameter ImageLoaderConfiguration configuration = ImageLoaderConfiguration. createDefault (this); // Initialize ImageLoader with configuration. ImageLoader. getInstance (). init (configuration );

Compile some common methods such as toast Dialog

Simplified toast

public void showMyToast(final Activity curAT, int textResId) {        showMyToast(curAT, textResId, Toast.LENGTH_LONG);    }

Exit 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 the Application.

Let's take a look at our BaseActivity.

Public abstract class BaseActivity extends Activity {InputMethodManager _ inputMethodManager; protected Resources res; protected BaseApplication baseApp; protected static final String TAG = BaseActivity. class. getName (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (getLayout (); res = this. getApplicationContext (). getResources (); ba SeApp = (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 protected boolean isSupportedSDK (int sdkVerCode) {LogUtils. d (TAG, "isSupportedSDK-ConfigUtil. MIN_SDK_VER_CODE = \ "" + ConfigUtil. MIN_SDK_VER_CODE + "\" "); LogUtils. d (TAG, "isSupportedSDK-sdkVerCode = \" "+ sdkVerCode +" \ ""); return sdkVerCode> = ConfigUtil. MIN_SDK_VER_CODE;} // network error type protected int getNetworkErrorTip (int code) {LogUtils. d (TAG, "getNetworkErrorTip-code = \" "+ code +" \ ""); int textResId = R. string. error_network_time_out; switch (code) {case RespHandleListener. errCode. ERR_NETWORK_NOT_AVAILABLE: textResId = R. string. error_network_not_available; break; case RespHandleListener. errCode. ERR_SERVER_ERROR: textResId = R. string. error_network_server_busy; break; case RespHandleListener. errCode. ERR_TIME_OUT: case RespHandleListener. errCode. ERR_CLIENT_ERROR: case RespHandleListener. errCode. ERR_UNKNOWN_ERROR: break; default: break;} LogUtils. d (TAG, "getNetworkErrorTip-textResId = \" "+ textResId +" \ ""); return textResId ;}}

Tool interface for network judgment
RespHandleListener

public interface RespHandleListener {     class ErrCode {        public static final int ERR_SUCCEED = 0;        public static final int ERR_NETWORK_NOT_AVAILABLE = -1;        public static final int ERR_TIME_OUT = -2;        public static final int ERR_SERVER_ERROR = -3;        public static final int ERR_CLIENT_ERROR = -4;        public static final int ERR_UNKNOWN_ERROR = -5;    }     void onError(int code);     void onReqBegin();     void onReqEnd(String jsonResp);}
Analysis:

Previously, some methods in BaseApplication were called in BaseActivity, while BaseActivity encapsulated our onCreate in a simple way to separate the business logic from the control capture operations.
(The specific usage will be posted later)

So what else can we do in BaseActivity?

The toast can also be made here, and the Dialog is the same.

protected void showErrorToast(int code) {        baseApp.showMyToast(this, getNetworkErrorTip(code));    }

Tool class for network judgment getNetworkErrorTip ()
Screen information can also be obtained here by default, and some hardware conditions suchNFC BLE(This chapter is written in the next blog)

Next, paste 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 () {return R. layout. activity_main ;}@ Override public void onClick (View v) {if (v. getId () = R. id. button) {Toast. makeText (MainActivity. this, "click", Toast. LENGTH_SHORT ). show () ;}} private int add (int a, int B) {return a + B ;}}

Running Effect

In this way, my mom no longer worries about the hundreds of lines of my onCreate method, and no longer worries about the lack of a findById control. Of course, I can further encapsulate the generic type.<T>To further simplify the control operations, which will be written in a later article.

Third-party libraries used:
A simple logstore

compile 'com.apkfuns.logutils:library:1.0.6'

Source code: http://yunpan.cn/cmNbQInJuKHXw access password 4a23

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.