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

Intent 的 ComponentName 屬性:精準指定目標元件的显式跳轉

編輯:Android 開發實例

ComponentName(元件名稱)是 Intent 中最直接的一種定位方式。當你明確知道要啟動哪個元件時,只要設定 ComponentName,系統便會毫不猶豫地把 Intent 送達該元件,這就是所謂的「顯式 Intent」。以下範例示範如何透過 ComponentName 跨套件啟動另一個 Activity,並在目標頁面中讀取元件名稱資訊。

程式文件:/Chapter06_Intent_ComponentName/src/com/amaker/ch06/app/MainActivity.java

package com.amaker.ch06.app;

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

/**
 * 測試 Intent 的 ComponentName 屬性
 */
public class MainActivity extends Activity {
 private Button btn;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 btn = (Button)findViewById(R.id.myButton01);
 btn.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
 // 實例化組件名稱
 ComponentName cn = new ComponentName(MainActivity.this, "com.amaker.ch06.app1.MyActivity");
 Intent intent = new Intent();
 // 為 Intent 設置組件名稱屬性
 intent.setComponent(cn);
 startActivity(intent);
 }
 });
 }
}

目標頁面 MyActivity 則可透過 getComponent() 取得元件名稱,進一步讀出套件名稱與類別名稱:

package com.amaker.ch06.app1;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import com.amaker.ch06.app.R;

/**
 * 測試 Intent 的 ComponentName 屬性
 */
public class MyActivity extends Activity {
 private TextView tv;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.my_layout);
 Intent intent = this.getIntent();
 ComponentName cn = intent.getComponent();
 String packageName = cn.getPackageName();
 String className = cn.getClassName();
 tv = (TextView)findViewById(R.id.TextView01);
 tv.setText("組件包名稱:"+packageName+"\n"+"組件類名稱:"+className);
 }
}

佈局檔 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"
 >
 <Button 
 android:text="測試Intent的組件名稱屬性" 
 android:id="@+id/myButton01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"></Button>
</LinearLayout>

與依賴 Intent Filter 比對的隱式 Intent 不同,顯式 Intent 憑藉 ComponentName 便能精準命中目標,無須經過濾器篩選。這種方式常用於同一個應用內部的頁面跳轉,因為開發者往往清楚每個元件的確切位置。若想跨應用啟動他人元件,則需留意目標元件是否對外開放(例如是否設定了 android:exported="true")。

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