Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 調用系統郵件元件(Intent 匹配流程解析)

編輯:關於 Android 程式設計

本文說明如何透過 Intent 調用系統郵件元件,並釐清 Intent 的匹配流程。

程式碼如下:

public class MainActivity extends Activity {
    private View vClick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setClickListener();
    }
    private void initView() {
        vClick = findViewById(R.id.tv_click);
    }
    private void setClickListener() {
        vClick.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMail();
            }
        });
    }
    protected void sendMail() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:pzfpang451@163.com"));
        startActivity(intent);
    }
}

清單檔的 intent-filter 配置:

<intent-filter>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
    <data android:scheme="mailto"/>
    <category android:name="android.intent.category.APP_BROWSER"/>
    <category android:name="android.intent.category.DEFAULT"/>
</intent-filter>

Intent 的匹配流程

調用郵件元件的關鍵在於 Intent 的匹配知識:

  1. 首先需在清單檔的 Activity 中配置 action 標籤(此處指明調用系統郵件元件 android.intent.action.SENDTO),並設定 data 標籤(對應的 uri 資料,格式為 scheme://host:port/path),再添加 category 標籤。
  2. 調用 startActivity() 時,系統會默認為 Intent 添加 <category android:name="android.intent.category.DEFAULT" />,因此一般開發不會出錯;若需其他種類則必須在清單檔配置,否則會匹配失敗(NO_MATCH_CATEGORY)。

匹配總結:

  • Intent 首先與 intent-filter 的 action 相匹配,若為空則匹配失敗(NO_MATCH_ACTION)。
  • 若 action 匹配成功,再比較 Intent 的 data 與 type 與 intent-filter 中的 data、type,匹配度大於 0 則成功,小於 0 則失敗(NO_MATCH_DATA、NO_MATCH_TYPE)。
  • 最後比較 category 資訊,若 Intent 的 category 與 intent-filter 中的資訊相符則成功,否則失敗(NO_MATCH_CATEGORY)。

這些 NO_MATCH 返回值都是十六進位值,一般最高位為 0 表示成功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved