🎯 隱式跳轉 = 給 Android 發一張“任務説明書”
任務説明書裏面有三樣東西:
- Action(動作) —— 我要幹什麼
- Data(數據內容) —— 我要對什麼幹
- Category(類別提示) —— 有什麼特殊要求
Android 會根據這三條信息,去找能處理這個任務的 Activity。
🌟1. Action —— “你要幹什麼事?”
可以類比成:動詞
|
Action
|
現實含義
|
|
VIEW
|
我想“看”點東西
|
|
SEND
|
我想“分享”東西
|
|
DIAL
|
我想“打電話”
|
|
EDIT
|
我想“編輯內容”
|
|
自定義 Action
|
我想執行某個自家 App 的操作
|
new Intent(Intent.ACTION_VIEW);
意思就是:
“我要看點東西!”
這個東西是什麼?需要靠 Data 來説明。
🌟 2. Data —— “你要處理的是什麼東西?”
可以類比成:名詞
例如:
|
Data
|
表示的東西
|
|
|
一個網頁
|
|
|
一個電話號碼
|
|
|
一個地理位置
|
|
|
一張圖片
|
|
|
一個視頻文件
|
舉例:
intent.setData(Uri.parse("https://www.baidu.com"));
就是告訴系統:
我要看(VIEW)一個網頁(Data)。
於是系統就會找瀏覽器來處理。
🌟 3. Category —— “補充説明”
可以類比成:備註信息
比如常見的:
|
Category
|
説明
|
|
DEFAULT
|
普通的、常規的啓動方式
|
|
BROWSABLE
|
可以從瀏覽器裏打開
|
|
LAUNCHER
|
要顯示在桌面上
|
最最重要的是:
📌 如果你要使用隱式跳轉,目標 Activity 的 intent-filter 必須包含 DEFAULT
<category android:name="android.intent.category.DEFAULT"/>
沒有這個就無法啓動(超級常見的坑)。
🎁 用一個生活例子把三者串起來(最通俗)
假設你是 Android,你收到一張任務説明書:
📄 任務説明書:
- Action:VIEW(我想“看”)
- **Data:https://baidu.com**(我要“看網頁”)
- Category:DEFAULT(普通方式打開即可)
你(Android)會怎麼做?
→ 去找所有能 看網頁 的應用
→ 找到 Chrome、瀏覽器、Edge、QQ 瀏覽器
→ 如果用户設置過默認瀏覽器,就直接打開
→ 沒設置就彈一個“選擇應用”窗口讓用户選
測試代碼:
package com.example.phonecall;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDial = findViewById(R.id.btn_dial);
btnDial.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 創建隱式意圖
Intent intent = new Intent(Intent.ACTION_DIAL);
// 設置電話號碼,tel:xxx 是 Data
intent.setData(Uri.parse("tel:10086"));
// 啓動撥號界面
startActivity(intent);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<Button
android:id="@+id/btn_dial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打開撥號界面(ACTION_DIAL)"/>
</LinearLayout>