Some basic knowledge in programming/computers

1. adb shell

Some common command line tools under adb shell:
pm : PackageManager, a package manager, used to manage the installation, uninstallation, query and more related operations of applications.
pm install …//
pm uninstall …//
pm list packages//Installed applications on the device
pm dump…//Get application details, such as package name, version number, permissions, etc.

am : Activity Manager, activity manager, used to manage activities on the device and the status of applications
am start…//
am stop…//
am force-stop…//
am broadcast //Send broadcast adb shell am broadcast -a com.example.myapp.CUSTOM_ACTION --es message “Hello, World!” ——-a parameter specifies the broadcast action (Action), –es parameter is used to add an additional string value, the key is message, the value is “ Hello, World!”

adb: Android Debug Bridge is the main command line tool for communicating with Android devices. It provides the ability to transfer files to and from the device, debug, install applications, and perform other operations.

ls : The ls command is used to list files and subdirectories in a directory. For example, ls /sdcard lists the files and directories on the device's memory card (SD card).

cd : The cd command is used to change the current working directory. For example, cd /sdcard changes the current directory to the device memory card.

mkdir : The mkdir command is used to create new directories. For example, mkdir /sdcard/new_directory creates a new directory named "new_directory" on the device memory card.

cp : The cp command is used to copy files or directories. For example, cp /sdcard/file.txt /sdcard/backup/file.txt can copy the file named "file.txt" to the directory named "backup".

mv : The mv command is used to move files or directories, and can also be used to rename files or directories. For example, mv /sdcard/file.txt /sdcard/new_location/file_new.txt moves the file to a new location and renames it to "file_new.txt".

rm : The rm command is used to delete files or directories. For example, rm /sdcard/file.txt can delete the file named "file.txt", rm -f deletes the folder directory

cat : The cat command is used to display the contents of a file. For example, cat /sdcard/file.txt prints the contents of the file to the command line interface.

chmod : The chmod command is used to change the permissions of a file or directory. For example, chmod 755 /sdcard/file.txt changes the file's permissions to 755.

2.json

When parsing json data, you can use GSON (an open source JSON library provided by Google). Gson can convert Java objects into JSON strings and JSON strings into Java objects. Gson provides more advanced features and flexibility, such as supporting custom serialization and deserialization rules, handling complex object relationships, date formatting, etc.

plugins {
    
    
    id 'kotlin-parcelize'
}
依赖:
implementation "com.google.code.gson:gson:2.9.1"

Serialization analysis:

@Parcelize
class ParsingObject(
    @SerializedName("event_code")//统一编码格式,将json里的下划线转化为驼峰格式
    val eventCode: Int = 10501,
    @SerializedName("event_code")
    val eventValue: Int,
    val event: String = "DEFAULT_VALUE",//默认值
    val params: FlightParams
) : Parcelable

jsonString
val gson = Gson()
val obj = gson.formJson<ParsingObject>(jsonString, ParsingObject::class.java)
然后解析相应对象即可

json内容是一个list
 val info = gson.fromJson(jsonString, Array<ParsingObject>::class.java).toList()

当json内有pair对时,pair对数量未知,且value类型未知
"params":{
    
    
	"key1":20,
	"key2":"value",
	"key3":true
}
@Parcelize
class ParseObject(val params : Map<String, @RawValue Any>) : Parcelable

jsonObject parsing:

//根据相应特征字段名获取
val jsonObject = JSONObject(jsonStr)
val jsonArray = jsonObject.getJSONArray("list")
val obj = jsonArray.getJSONObject(0)
val cityObj = obj.getJSONObject("cityInfo")

3. Read the files in the assets directory

AssetsManager object

1.context

//获取AssetManager对象
val assetManager = context.assets
//InputStream 流
val inputStream: InputStream = assetManager.open("filename.txt")
//BufferedReader逐行读取
val reader = BufferedReader(InputStreamReader(inputStream))
var line: String?
while (reader.readLine().also {
    
     line = it } != null) {
    
    
    // 处理每一行的内容
}
//关闭
reader.close()
inputStream.close()

2.resources

val assetManager = resources.assets
val inputStream: InputStream = assetManager.open("filename.txt")

3.Kotlin extension function

val assetManager = context.assets
val inputStream: InputStream = assetManager.open("filename.txt")

fun InputStream.readTextAndClose(charset: Charset = Charsets.UTF_8): String {
    
    
	return this.bufferedReader(charset).use {
    
     it.readText() }
}
val text: String = inputStream.readTextAndClose()

4. java spi

Core idea: Decoupled
SPI (Service Provider Interface) is a service discovery mechanism built into the JDK , which can be used to enable framework extensions and component replacement.

1. Define the interface and its implementation class

public interface IFather{
    
    ...}
public class Son implements IFather{
    
    ...}

2. Create a new META-INF/services directory under the resources directory.

Create a new file in the services directory. The file name is the directory of the interface class, and the file content is the class to be implemented.
File name: com.example.IFather
File content: com.example.Son

3.Load

ServiceLoader<IFather> s = ServiceLoader.load(IFather.class);
Iterator<IFather> it = s.iterator();
while(it.hasNext()) {
    
    
	IFather c = it.next();
	...
}

4. The implementation class must carry a constructor without parameters

5. Annotation

1 Annotation and 1 RetentionPolicy associated.
1 Annotation is associated with 1~n ElementTypes.
Annotation has many implementation classes, including: Deprecated, Documented, Inherited, Override, etc.
Insert image description here

package java.lang.annotation;
public interface Annotation {
    
    
    boolean equals(Object obj);
    int hashCode();
    String toString();
    Class<? extends Annotation> annotationType();
}

package java.lang.annotation;
public enum ElementType {
    
    
    TYPE,               /* 类、接口(包括注释类型)或枚举声明  */
    FIELD,              /* 字段声明(包括枚举常量)  */
    METHOD,             /* 方法声明  */
    PARAMETER,          /* 参数声明  */
    CONSTRUCTOR,        /* 构造方法声明  */
    LOCAL_VARIABLE,     /* 局部变量声明  */
    ANNOTATION_TYPE,    /* 注释类型声明  */
    PACKAGE             /* 包声明  */
}
@Target(ElementType.Type)//若有就表示用于指定的地方,若无则表示可用于任何地方

package java.lang.annotation;
public enum RetentionPolicy {
    
    
    SOURCE,            /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了  */
    CLASS,             /* 编译器将Annotation存储于类对应的.class文件中。默认行为  */
    RUNTIME            /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}
@Retention(RetentionPolicy.RUNTIME)//没有RetentionPolicy默认是CLASS
@Deprecated  -- @Deprecated 所标注内容,不再被建议使用。
@Override    -- @Override 只能标注方法,表示该方法覆盖父类中的方法。
@Documented  -- @Documented 所标注内容,可以出现在javadoc中。
@Inherited   -- @Inherited只能被用来标注“Annotation类型”,它所标注的Annotation具有继承性。
@Retention   -- @Retention只能被用来标注“Annotation类型”,而且它被用来指定AnnotationRetentionPolicy属性。
@Target      -- @Target只能被用来标注“Annotation类型”,而且它被用来指定AnnotationElementType属性。
@SuppressWarnings -- @SuppressWarnings 所标注内容产生的警告,编译器会对这些警告保持静默。

An example:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ServiceFunctionParameters {
    
    

    String NO_DEFAULT_VALUE = "OPEServiceFunctionParameters_NO_INPUT_PROVIDED";

    String description() default "";

    String name();

    String defaultValue() default NO_DEFAULT_VALUE;

    boolean required() default true;

    Class<?> type() default String.class;
}

    fun addCalendarSchedule(
        @ServiceFunctionParameters(
            name = "title",
            description = "你需要根据该日程主题给拟一个标题"
        ) title: String?,
        @ServiceFunctionParameters(
            name = "description",
            description = "日程的具体内容"
        ) description: String?,
        @ServiceFunctionParameters(
            name = "startTime",
            description = "日程开始时间,格式:yyyy-MM-dd HH:mm:ss"
        ) startTime: String?,
        @ServiceFunctionParameters(
            name = "endTime",
            description = "日程结束时间,格式:yyyy-MM-dd HH:mm:ss"
        ) endTime: String?,
    ) {
    
    ...}

6. Generics

1. Generic methods

All generic method declarations have a type parameter declaration section (delimited by angle brackets) that precedes the method's return type.
Each type parameter declaration part contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier that specifies the name of a generic type.
Type parameters can be used to declare return value types and can serve as placeholders for the actual parameter types obtained by generic methods.
The declaration of a generic method body is the same as for other methods. Note that type parameters can only represent reference types, not primitive types (such as int, double, char, etc.).

public class GenericMethod {
    
    
   //泛型方法
   public static <E> void printArray( E[] inputArray ) {
    
    
         // 输出数组元素            
         for ( E element : inputArray ) {
    
            
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }
 
    public static void main( String args[] ) {
    
    
        // 创建不同类型数组: Integer, Double 和 Character
        Integer[] intArray = {
    
     1, 2, 3, 4, 5 };
        Double[] doubleArray = {
    
     1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = {
    
     'H', 'E', 'L', 'L', 'O' };
 
        System.out.println( "整型数组元素为:" );
        printArray( intArray  ); // 传递一个整型数组
 
        System.out.println( "\n双精度型数组元素为:" );
        printArray( doubleArray ); // 传递一个双精度型数组
 
        System.out.println( "\n字符型数组元素为:" );
        printArray( charArray ); // 传递一个字符型数组
    } 
}

整型数组元素为:
1 2 3 4 5 

双精度型数组元素为:
1.1 2.2 3.3 4.4 

字符型数组元素为:
H E L L O 

2. Generic classes

The declaration of a generic class is similar to the declaration of a non-generic class, except that a type parameter declaration part is added after the class name. Like the generic method, the type parameter declaration part of the generic class also contains one or more type parameters. Parameters Separate them with commas. A generic parameter, also known as a type variable, is an identifier used to specify the name of a generic type. Because they accept one or more parameters, these classes are called parameterized classes or parameterized types.

public class Box<T> {
    
    
  private T t;
  public void add(T t) {
    
    
    this.t = t;
  }
  public T get() {
    
    
    return t;
  }
  public static void main(String[] args) {
    
    
    Box<Integer> integerBox = new Box<Integer>();
    Box<String> stringBox = new Box<String>();
    integerBox.add(new Integer(10));
    stringBox.add(new String("测试"));
    System.out.printf("整型值为 :%d\n\n", integerBox.get());//整型值为 :10
    System.out.printf("字符串为 :%s\n", stringBox.get());//字符串为 :测试
  }
}

3. Type wildcard

Type wildcards are generally used? instead of specific type parameters

import java.util.*;
 
public class GenericTest {
    
    
    public static void main(String[] args) {
    
    
        List<String> name = new ArrayList<String>();
        List<Integer> age = new ArrayList<Integer>();
        List<Number> number = new ArrayList<Number>();
        name.add("icon");
        age.add(18);
        number.add(314);
        getData(name);//data :icon
        getData(age);//data :18
        getData(number);//data :314
   }
   public static void getData(List<?> data) {
    
    
      System.out.println("data :" + data.get(0));
   }
}

The upper limit of type wildcards is defined by ? extends Class, that is, it can only be Class or its subclasses

import java.util.*;
 
public class GenericTest {
    
    
     
    public static void main(String[] args) {
    
    
        List<String> name = new ArrayList<String>();
        List<Integer> age = new ArrayList<Integer>();
        List<Number> number = new ArrayList<Number>();
        name.add("icon");
        age.add(18);
        number.add(314);
        //getUperNumber(name);//String非Number的子类
        getUperNumber(age);//
        getUperNumber(number);//
   }

   public static void getUperNumber(List<? extends Number> data) {
    
    
          System.out.println("data :" + data.get(0));
       }
}

The upper limit of type wildcard is defined by ? superClass, that is, it can only be Class and its upper parent type, such as object

7. Mono responsive programming

Asynchronous programming, processing time-consuming logic. mono is used to handle asynchronous sequences containing zero or one element.

val mono = Mono.fromCallable{
    
    
	......//耗时逻辑
}
mono.subscribe{
    
    result ->
	Log.d(TAG,"....")
}//只有subscribe这里订阅了,fromCallable里的耗时逻辑才会执行

val mono = Mono.just{
    
    
	...
}
同样需要订阅

//让耗时逻辑在子线程中执行
mono.subscribeOn(Schedulers.Parallel())
mono.subscribeOn(Schedulers.boundedElastic())

Guess you like

Origin blog.csdn.net/ppss177/article/details/132363875