[android learning] summary of android knowledge points

1. Android UI system

1) MVC, MVP of Android

For small projects, it can be divided as follows (mvp selection); for large projects, it can be divided into modules, and then the modules are distributed as follows.
Subcontracting (by function):
basal: base class;
surface (fragment, activity, broadcast, listener): interface class;
adapter: adapter class;
mvp (presenter, contract, view): mvp layer class;
util: general tool class ;
widget: custom View class;
entity: entity class;
Config.class
MyApplication

2)xml

The font is generally 34px, 30px, 28px, 26px, 24px, 22px
Small thin line 1px dddddd thick line 10px f5f5f5 Background color f5f5f5, the left and right distance of the app is 20px
theme color

3)Window 和 WindowManager

4) Pictures

Drawable

Bitmap loading and Cache

5) Other

The basic idea of ​​event notification implementation comes from the observer pattern. (Like Swing, both use the observer pattern)

6) Controls

View

②Title bar

7) Animation

8) Menu

When the Menu is displayed, the method onPrepareOptionsMenu will be called. You can also regenerate the items in the menu every time the menu is called. This is achieved by overriding onPrepareOptionsMenu. Menus that change frequently will be less efficient.

Call the Menu.addSubMenu() method to add a submenu to a menu item.

①Options menu Options menus

An Activity can only have one option menu, which is displayed at the bottom of the screen when the Menu key is pressed.

Override onCreateOptionsMenu to create options menu;
override onOptionsItemSelected to respond to options menu.

②Context menu Context menus

Register a context menu for any view in the Activity, "long press" appears.

Override onCreateContextMenu to create context menus;
override onContextItemSelected to respond to context menus.

③ Popup menus

Depends on a view in the Activity.

9) Splash interface

① function

Display the product's logo
initialization operation (create database, read configuration file)
Connect to the server to check software authorization
Connect to the server to check software updates

② Realize

Use handler delay, write the following code in the SplashActivity interface, and disable the return key.

private final int SPLASH_DISPLAY_LENGHT = 3000;
……
handler = new Handler();
        // 延迟SPLASH_DISPLAY_LENGHT时间然后跳转到MainActivity
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this,
                        MainActivity.class);
                startActivity(intent);
                SplashActivity.this.finish();
            }
        }, SPLASH_DISPLAY_LENGHT);

11) Screen resolution adaptive

①Component size: weight (layout_weight), specific pixel (dip) ②Picture
: drawable-hdpi, .9.png picture
③AndroidManifest.xml

<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:anyDensity = "true"/>

android:anyDensityThe value is true, the system will automatically find the corresponding folder according to the screen density.
If there are high-density images in drawable-hpdi and no corresponding image resources in the other two folders, the system will load the resources in drawable-hdpi.

2. Four major components + important components

1) Four components - Activity

Fragment related

2) Four major components - Service

3) Four major components - Content Provider

4) Four major components-BroadcastReceiver (broadcast receiver)

5) Important components - intent

3,Android JVM

1) Storage method (data persistence)

Data Persistence: Convert an in-memory data model to a storage model. ,

Other storage methods:
redis: an open source log-type, key-value database written in ANSI C language, supporting the network, and being memory-based and persistent.
sessionStorage: The life cycle is the current window or tab. Once the window or tab is permanently closed, all data stored through sessionStorage will be emptied.

①SQLite database

Store structured data. Click to view SQLite details

②File storage

Divided into internal storage and external storage (SD card) two storage methods.

a. The difference between File.mkdirs and File.mkdir

File.mkdirs creates files under multiple levels of directories.
File.mkdir can only create files in the second-level directory and only one level, and can only be created in the existing directory. For the path that does not actually exist, call the File.mkdirs() method.

b.onSaveInstanceState

Detailed explanation of onSaveInstanceState use - solution to the problem: after the android program crashes, the app is abnormal

③SharedPreferences

Shared parameters are stored in the form of key-value pairs. Click to view SharedPreferences details

④Network storage

Store data on the server.

⑤ContentProvider storage

Check out the four major components - Content Provider.
The purpose of ContentProvider is to expose data externally for other programs to query.

2) Android bottom layer

①Garbage collection mechanism (GC)

②Memory leak OOM (OutOfMemory)

JNI (Java Native Interface, java native interface) programming

3) Android system architecture

4) Digital Signature

5)DVM

Each Android application runs in a separate Dalvik virtual machine (that is, each Android application uses a Dalvik process). Dalvik is optimized for running multiple virtual machines efficiently at the same time, so the Android system can easily Applications are isolated.

Each Android application runs in its own process and has an independent Dalvik virtual machine instance, each DVM is a process in Linux, all Android application threads are for one Linux thread, DVM can therefore be more Depends on the thread scheduling and management mechanism of the operating system.

The Android runtime consists of two parts:

1) Android core library set

Provides most of the functions that the Java language core library can use.

2) Dalvik virtual machine

DVM is responsible for running Android applications.

4. Process and synchronization

1) IPC (Inter-Process Communication)

During socket transmission, the stream is closed

The android side receives data through the socket and generates garbled characters

socket ECONNRESET exception

The socket is connected for a long time, causing the problem of data sticking

android network connection - main thread connection error

2) Thread and asynchronous task mechanism

3) Threads and thread pools

4) Implementation of daemon process and detailed explanation of process pulling

5) Message mechanism Handler

6) Resource pool

The objects that provide resource pools in Android are:
-Message
provides a message pool, and there is a static method Obtain to get objects from the message pool.

–AsynTask
AsynTask is modified from the thread pool. By default, the pool provides (number of cores + 1) threads for concurrent operations, and supports a maximum of (number of cores * 2 + 1) threads, after which other tasks will be discarded.

–ThreadPool
Thread does not provide resource pools by default unless managed by a thread pool ThreadPool.

For Looper, each Looper creates a message queue and thread object, but not a resource pool.

5, Basic knowledge of Android

1) Project structure

Project structure

src

Store java source code

gen

Root directory. Store the configuration files automatically generated by the system, such as R files, class libraries, and jar packages.
R.java function: The
development tools are automatically generated, and various resource IDs are stored to facilitate finding the corresponding resources. At the same time, resources not used by R.java will not be compiled into the software.

assets

Store resource files (web pages, pictures, audio).
It will not automatically occupy the size of the generated apk file, and will only be generated when it is applied.
The files in the assets directory need to be accessed with the help of AssetManager.

AssetManager a = getAssets()  ;
//fileName为assets目录下需要访问的文件的名称
InputStream is = a.open(fileName) ;
//然后就可以通过输入流来读取fileName的内容了

bin

Automatically generated compiled files.

libs

Third-party jar package

res

Images, layout files, menu layout files, values ​​folder: strings, numbers, colors, styles, etc.
AndroidManifest.xml: manifest file, configure application-related information: package name, permissions, components.
The system will generate corresponding resource IDs for all resources in the res directory.

raw

in the res directory.
The files in the res/raw directory, some documents say that they will be compiled into binary, some documents say that they will not.
Android cannot directly open the database file in the res raw directory, but needs to copy the file to a certain directory in the phone memory or SD card when the program starts for the first time, and then open the database file.

InputStream is = getResources().openRawResource(R.id.fileNameID) ;
//R.id.fileNameID为需要访问的文件对应的资源ID.接着我们就可以通过输入流来读取相应文件的内容了。

defalut.properties

Store project environment information.

What is the difference between the asset folder and the raw folder?

The same point of res/raw and assets:

The files in the two directories will be stored in the apk package intact after being packaged, and will not be compiled into binary.

The difference between res/raw and assets:

1) The files in res/raw will be mapped to the R.java file, and the resource ID, namely R.raw.filename, will be used directly when accessing; the files in the assets folder will not be mapped to R.java, and the accessed When you need the AssetManager class.
2) res/raw cannot have a directory structure, while assets can have a directory structure, that is, a folder can be created under the assets directory
3) Example of reading file resources:
read file resources under res/raw, in the following ways Get the input stream to do:

InputStream is = getResources().openRawResource(R.raw.filename); 

Read the file resources under assets, and obtain the input stream for write operations in the following ways

AssetManager am = null; 
am = getAssets(); 
InputStream is = am.open("filename"); )

2) Advantages and disadvantages of Android system

Five major deficiencies:
①Security and privacy
②Not the largest operator that sells Android phones first ③Operators
can still affect Android phones
④Reduced users of similar models: lack of programs for unified
models Reliance on third parties and lack of product uniformity.

Advantages:
① Large market share ② Rapid development of
applications
③ Help from smart manufacturers
④ Cheap mobile phones but not low performance
⑤ Many models and excellent hardware configuration

3) Common tools in the Android SDK-tools directory

①android

②apkbuilder

for packaging apk

③ddms (Dalvik Debug Monitor Service, Dalvik Debug Monitor Service)

This tool integrates with Dalvik (a virtual machine (VM) customized for the Android platform), allowing you to manage processes and assist with debugging on an emulator or device.
DDMS is a program execution viewer that can see information such as threads and stacks.

Functions: Take
screenshots for the test device;
select a specific process to debug, generate trace data, observe heap and thread information;
kill the process;
Logcat. Log information is divided into 5 levels: Log.v (VERBOSE) detailed information, Log.d (DEBUG) debug message, Log.i (INFO) notification message, Log.w (WARN) warning message, Log.e (ERROR) ) Error messages
Broadcast status information;
simulate phone calls;
receive SMS;
virtual geographic coordinates, etc.

Work:
DDMS will set up the link between IDE and test terminal (Emulator or connected device), they will be applied to the connection of the test terminal, when a new test terminal is connected, DDMS will capture the terminal ID and establish debugging through adb , so as to achieve the purpose of sending commands to the test terminal.

④draw9patch

The Draw 9-patch tool allows you to easily create NinePatch graphics using what you see is what you get (WYSIWYG) editors. It can also preview stretched images, highlighting content areas.

⑤emulator (Android emulator)

AVD Manager (Android Virtual Device Manager):
Configurable: screen resolution (Skin), buffer size (RAM), SD card support (SD Card Support), keyboard support.
Cannot configure Bluetooth support.

⑥mksdcard

Helps you create a disk image, which you can use in the emulator environment to emulate an external memory card (eg SD card).

⑦sqlite3

This tool allows you to easily access SQLite data files. These data files are created and used by Android applications.

⑧aidl (Android Interface Description Language, Android Interface Description Language)

Code that allows you to generate interfaces between processes, such as interfaces that a service might use.
The content of the aidl file is similar to the java code; create a Service (service), and return the object that implements the aidl interface in the onBind (Intent intent) method of the service; the method corresponding to the interface of aidl cannot be preceded by an access permission modifier.

The data types supported by AIDL are:
i> Simple Java programming language types that do not require import declarations: int boolean, etc.
ii>String, CharSequence do not need special declaration
iii>List, Map and Parcelables types
(the data members contained in these types can only be simple data types, String and other supported types.

⑨TraceView

Program performance analyzer.
It is a data collection and analysis tool specific to the Android platform. It is mainly used to analyze the hotspot of applications in Android. TraceView itself is just a data analysis tool, and data collection needs to use the Debug class in the Android SDK or use the DDMS tool.

4) platform-tools directory

Common tools are:

①aapt

②adb

③dx

④aidl

6,demo

Detect the android home screen and switch the app from the background to the foreground

keep the screen always on

ping different networks and return network status

Disconnection and reconnection mechanism

Solve the problem of heap packets during data transmission through regular expressions

px and dip conversion

GPS on

Check whether the GPS is turned on, if not, jump to the GPS interface for the user to turn on.

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            // 判断GPS是否正常启动
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                ToastUtil.showShort(context, "未开启位置服务,请开启GPS导航");
                // 返回开启GPS导航设置界面
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, 0);
                return;
            }

7. Application

1) Token login

①Definition

Token is a string of strings generated by the server as a token for the client to request. After logging in for the first time, the server generates a Token and returns the Token to the client. In the future, the client only needs to bring this token. Token can come to request data, no need to bring user name and password again.

② role

The purpose of Token is to verify the user's login status and reduce the pressure on the server, reduce frequent database queries, and make the server more robust.

Token is that the client frequently requests data from the server, and the server frequently goes to the database to query the username and password and compare them to determine whether the username and password are correct or not, which increases the burden on the server.

③Apply

i> After the user successfully logs in for the first time, the server will generate a token value, save it in the database and return it to the client.
ii> After the client gets the token value, use sp to save it.
iii> When the client sends a network request again (usually not a login request), it will attach the token value to the parameter and send it to the server.
iv> After the server receives the client's request, it takes out the token value and saves it locally (database). ) to compare the token values.
If two token values ​​are the same, it means that the user is in the logged-in state.
Without this token value, no login is successful.
If the token values ​​are different: it means that the original login information has expired, and the user should log in again.

2) Login verification

Get focus through .requestFocus() to improve user experience

                String Str_name = et_username.getText().toString().trim();
                String Str_psw = et_password.getText().toString().trim();
                if (null != Str_name && Str_name.equals("")) {
                    showCustomToast("用户名不能为空");
                    et_username.requestFocus();
                } else if (null != Str_psw && Str_psw.equals("")) {
                    showCustomToast("密码不能为空");
                    et_password.requestFocus();
                } else if (Str_psw.contains("卍")) {
                    showCustomToast("密码不能含有特殊字符");
                    et_password.requestFocus();
                } else if (Str_psw.length() < 6) {
                    showCustomToast("密码不能少于6位");
                    et_password.requestFocus();
                } else {
                    tryLogin(Str_name, Str_psw);
                }

3) log

android offline log file printing

8. Problem solving

1) eclipse cannot find the device, adb needs to be restarted

Write a .bat file with the following content:
(Note: Please replace cd /d D:\android-sdks\platform-tools with your own adb.exe path)

@echo off   

taskkill /F /IM adb.exe  
echo Kill完成...  
pause 
echo 重启开始...  
cd /d D:\android-sdks\platform-tools  
adb devices  

pause. & exit 

2) Other

①The methods that may need to be rewritten when using Menu in android are: onCreateOptionMenu() and onOptionItemSelected().
eclipse editor garbled solution

Detailed explanation of configChanges - the solution to the problem: after the phone switches fonts, the app crashes abnormally

When eclipse creates an app, there is more appcompat_v7

Android development mistakenly deleted appcompat_v7

Replace “…” with ellipsis character (…, &&;#8230;) ?

eclipse ‘Launching Hello’has encountered a problem

9. Grammar

Common Manager

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325534445&siteId=291194637