Android四大應用組件(一)——Activity

目錄

一、基本理論

Activity概述

Intent概述

Intent的使用

Activity的使用

Activity的生命週期

TaskStack和lauchMode

設置監聽的四種方式

二、應用練習示例

功能描述

需求分析

界面展示

代碼示例

結果展示


一、基本理論

Activity概述

活動

四大應用組件之一

作用

提供能讓用戶操作並與之交互的界面

特點

1)它的類必須實現特定接口或繼承特定類

2)需要在配置文件中配置其全類名

3)它的對象不是通過new來創建的, 而是系統自動創建的

4)它的對象具有一定的生命週期, 它的類中有對應的生命週期回調方法

Intent概述

意圖

信使(Activity, Service, BroadcastReceiver三個組件間通信的信使)

分類:

1)顯式: 操作當前應用自己的組件

2)隱式: 操作其它應用自己的組件

Intent的使用

1). 創建:

顯式: Intent(Context context, Class activityClass)

隱式: Intent(String action) //與Activity與<intent-filter>的action匹配

2). 攜帶數據

額外: putExtra(String key, Xxx value) 內部用map容器保存

有特定前綴: setData(Uri data)  //tel:123123, smsto:123123

3). 讀取數據:

額外: Xxx getXxxExtra(String key)

有特定前綴: Uri getData()

Activity的使用

1). 定義

a. 定義一個類 extends Activity, 並重寫生命週期方法

b. 在功能清單文件中使用<activity>註冊

2). 啓動

a. 一般: startActivity(Intent intent)

b. 帶回調啓動: startActivityForResult(Intent intent, int requestCode)  並重寫: onActivityResult(int requestCode, int resultCode, Intent data)

3). 結束

a. 一般: finish()

b. 帶結果的: setResult(int resultCode, Intent data)

Activity的生命週期

1). Activity界面的狀態:

運行狀態: 可見也可操作

暫停狀態: 可見但不可操作

停止狀態: 不可見,但對象存在

死亡狀態: 對象不存在

2). Activity的生命週期流程:

          

onCreate() : 加載佈局和初始化的工作

onResume() : 只有經歷此方法, 才進入運行狀態

onDestroy() : 在對象死亡之前, 做一些收尾或清理的工作

TaskStack和lauchMode

TaskStack

1)在Android中,系統用Task Stack (Back Stack)結構來存儲管理啓動的Activity對象

2)一個應用啓動,系統就會爲其創建一個對應的Task Stack來存儲並管理該應用的Activity對象

3)只有最上面的任務棧的棧頂的Activity才能顯示在窗口中

lauchMode:

1)standard

標準模式,每次調用startActivity()方法就會產生一個新的實例。

2)singleTop

如果已經有一個實例位於Activity棧的頂部時,就不產生新的實例;如果不位於棧頂,會產生一個新的實例。

3)singleTask

只有一個實例, 默認在當前Task中

4)singleInstance

只有一個實例, 創建時會新建一個棧, 且此棧中不能有其它對象

設置監聽的四種方式

1. layout中:   android:οnclick=“方法名”

                     Activity中: public void 方法名(View v) {   }

2. view.setOnclickListener(new View.OnclickListener(){})

3. view.setOnclickListener(this)

4. view.setOnclickListener(onclickListener成員變量)

 

二、應用練習示例

功能描述

1). 輸入電話號, 點擊"打電話", 進入撥號界面, 且已輸入的指定的號碼

2). 輸入電話號, 長按"打電話", 直接打電話(進入撥打界面)

3). 輸入電話和短信內容, 點擊"發短信", 進入短信編輯界面, 且已有號碼和內容

4). 輸入電話和短信內容, 長按"發短信", 直接將短信發送給指定的手機號

需求分析

1. 界面佈局
    1). 分析: 垂直的LinearLayout+水平的LinearLayout
    2). 編碼
2. 在Activity中初始化需要操作的視圖對象
3. 給button設置點擊監聽
4. 給button設置長按監聽
5. 點擊打電話進入撥號界面
    1). 創建一個Intent(隱式)
    2). 攜帶數據
    3). startActivity(intent)
6. 長按打電話進入打電話的界面(需要配置權限)
    1). 創建一個Intent(隱式)
    2). 攜帶數據
    3). startActivity(intent)    
7. 點擊發短信進入短信編輯界面
    1). 創建一個Intent(隱式)
    2). 攜帶數據(號碼/內容)
    3). startActivity(intent)    
8. 長按發短信直接發短信(需要配置權限)
    1). 得到SmsManager的對象
    2). 發送文本信息(短信)

界面展示

代碼示例

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="電話號碼:" />

        <EditText
            android:id="@+id/et_main_number"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:ems="10"
            android:hint="請輸入手機號碼" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="短信內容:" />

        <EditText
            android:id="@+id/et_main_sms"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:ems="10"
            android:hint="請輸入短信內容" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="41dp"
        android:orientation="horizontal">


        <Button
            android:id="@+id/btn_main_call"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="打電話" />

        <Button
            android:id="@+id/btn_main_send"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="發短信" />
    </LinearLayout>



</LinearLayout>

MainActivity.java

package com.example.app01_activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_main_number;
    private EditText et_main_sms;
    private Button btn_main_call;
    private Button btn_main_send;
    private View.OnLongClickListener OnLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (v == btn_main_call) {
//                Toast.makeText(MainActivity.this, "打電話長按事件", Toast.LENGTH_SHORT).show();
                //創建一個隱式intent對象
                Intent intent = new Intent(Intent.ACTION_CALL);
                //攜帶數據
                String number = et_main_number.getText().toString();
                intent.setData(Uri.parse("tel:" + number));
                //startActivity(intent)
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return false;
                }
                startActivity(intent);


            } else if (v == btn_main_send) {
//                Toast.makeText(MainActivity.this, "發短信長按事件", Toast.LENGTH_SHORT).show();
                //得到SmsManager的對象
                SmsManager smsManager = SmsManager.getDefault();
                //發送文本信息
                String number = et_main_number.getText().toString();
                String sms = et_main_sms.getText().toString();
                smsManager.sendTextMessage(number,null,sms,null,null);

            }
            //返回true表示此事件已經被消費了,不會再觸發點擊事件
            return true;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化視圖對象
        et_main_number = findViewById(R.id.et_main_number);
        et_main_sms = findViewById(R.id.et_main_sms);
        btn_main_call = findViewById(R.id.btn_main_call);
        btn_main_send = findViewById(R.id.btn_main_send);
        //給視圖對象設置點擊監聽
        btn_main_call.setOnClickListener(this);
        btn_main_send.setOnClickListener(this);
        //給視圖對象設置長按監聽
        btn_main_call.setOnLongClickListener(OnLongClickListener);
        btn_main_send.setOnLongClickListener(OnLongClickListener);
    }

    @Override
    public void onClick(View v) {
        if (v == btn_main_call) {
//            Toast.makeText(this,"打電話點擊事件",Toast.LENGTH_SHORT).show();
            //創建一個隱式intent對象
//            05-13 18:14:19.695 1509-1880/system_process I/ActivityManager: Start proc 4325:com.android.dialer/u0a4 for activity com.android.dialer/.DialtactsActivity
            String action = "android.intent.action.DIAL";
            Intent intent = new Intent(action);
            //攜帶數據
            String number = et_main_number.getText().toString();
            intent.setData(Uri.parse("tel:"+number));
            //startActivity(intent)
            startActivity(intent);

        } else if (v == btn_main_send) {
//            Toast.makeText(this, "發短信點擊事件", Toast.LENGTH_SHORT).show();
            //創建一個隱式intent對象
            String action = "android.intent.action.SENDTO";
            Intent intent = new Intent(action);
            //攜帶數據
            String number = et_main_number.getText().toString();
            intent.setData(Uri.parse("smsto:"+number));
            String sms = et_main_sms.getText().toString();
            intent.putExtra("sms_body",sms);
            //startActivity(intent)
            startActivity(intent);

        }
    }

}

結果展示

1). 輸入電話號, 點擊"打電話", 進入撥號界面, 且已輸入的指定的號碼

2). 輸入電話號, 長按"打電話", 直接打電話(進入撥打界面)

3). 輸入電話和短信內容, 點擊"發短信", 進入短信編輯界面, 且已有號碼和內容

4). 輸入電話和短信內容, 長按"發短信", 直接將短信發送給指定的手機號

啓動另外一個模擬器接收短信

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章