Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Intent 的 Category 屬性實作:一鍵回到 Android 主畫面

編輯:Android 開發實例

Category 是 Intent 用來補充描述「意圖種類」的屬性。透過為 Intent 加上不同的 Category,我們可以更精準地告訴系統:究竟想要執行哪一類操作。以下這個簡潔的範例,示範如何利用 Intent.ACTION_MAIN 搭配 Intent.CATEGORY_HOME,模擬使用者按下 Home 鍵、回到裝置主畫面的效果。

程式文件:/Chapter06_Intent_Category/src/com/amaker/test/MainActivity.java

package com.amaker.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 測試 Intent 的 Category 屬性
 */
public class MainActivity extends Activity {
 private Button b1;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 b1 = (Button)findViewById(R.id.Button01);
 b1.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
 Intent i = new Intent();
 // 添加 Action 屬性
 i.setAction(Intent.ACTION_MAIN);
 // 添加 Category 屬性
 i.addCategory(Intent.CATEGORY_HOME);
 // 啟動 Activity
 startActivity(i);
 }
 });
 }
}

這裡的關鍵在於兩個設定的組合:ACTION_MAIN 用來標示這是一個「進入某個任務」的動作,而 CATEGORY_HOME 則明確指向「主畫面」這個目標。當兩者同時出現時,系統便會把使用者導向桌面(Home Screen),效果等同按下實體或虛擬的 Home 鍵。

佈局檔:/Chapter06_Intent_Category/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 
 <TextView 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" 
 android:text="Intent Category 測試" />
 
 <Button 
 android:id="@+id/Button01" 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" 
 android:text="回到Home"></Button>
 
</LinearLayout>

這個小範例清楚展示了 Category 在 Intent 匹配過程中的角色:它並非只用來「啟動某個元件」,更能作為一種語意標記,協助系統判斷該元件是否適合成為當前意圖的接收者。在後續的 Intent Filter 機制中,正是靠著 Category 的比對,才能精準地把隱式 Intent 導向正確的處理者。

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