1. 程式人生 > 其它 >Unit1 The first code

Unit1 The first code

Unit1 The first code

1.1 Android系統架構

1、Linux核心,為裝置的硬體提供底層驅動,如顯示、音訊、照相機、藍芽、WiFi驅動等。

2、系統執行庫層,通過C/C++庫為系統提供主要特性支援,且還有Android執行時庫,提供核心庫,允許開發者使用Java語言編寫應用。

3、應用框架層,提供各種API。

4、應用層,應用程式。

Android應用開發特色:

1、四大元件:Activity、Service、BroadcastReceiver、ContentProvider。
Activity:表層介面。
Service:後臺執行。
BroadcastReceiver:接發廣播資訊。
ContentProvider:實現應用程式間的共享資料。

2、豐富的系統控制元件。

3、SQLite資料庫:輕量級、運算速度極快的嵌入式關係型資料庫。

4、強大的多媒體:豐富的多媒體服務。

1.2 HelloWorld專案執行過程分析

1、app.src.main.res.AndroidMainfest.xml 整個Android專案的配置檔案。

<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

上述程式碼對MainActivity進行註冊,沒有在AndroidMainfest.xml中註冊的Activity註冊的Activity是無法使用的。

2、app.src.main.java.com.example.helloworld.MainActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

P.S.Android程式的設計講究邏輯和試圖分離,不推薦在Activity中直接編寫介面。

由setContentView(R.layout.activity_main)可以看出該setContentView()方法給當前的Activity引入activity_main佈局,則"Hello World!"在此定義。

3、app.src.main.res.layout.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

控制元件Textview中的"Hello World"

1.3 詳解內容

"drawable"開頭的目錄是用以存放圖片
"mipmap"開頭的目錄是用以存放應用圖示
"values"是用以存放字串、樣式、顏色等配置
"layout"是用以存放佈局檔案

1、使用資源方式:

1)定義一個應用程式名的字串

<resources>
    <string name="app_name">HelloWorld</string>
</resources>

​ 2)引用該字串
在程式碼中通過 R.string.app_name 可以獲得該字串的引用
在XML中通過 @string/app_name 可以獲得該字串的引用

2、詳解 build.gradle檔案略,詳情見書P22

1.4 掌握日誌工具的使用

使用Android的日誌工具Log,減少sout和println()的使用
等級:Log.v()—>Log.d()—>Log.i()—>Log.w()—>Log.e()
詳情見書P25