編輯: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")。
Android IMF 輸入法框架實戰:SoftKeyboard 範例逐行剖析
Android 的 IMF(Input Method Framework,輸入法框架)從 SDK 1.5 起正式對外開放。想真正把輸入法開發搞懂,最經典的教材莫過於官方附
Android 定時器的三種寫法,以及 removeCallbacks 為什麼會失效
定時器的實作方式有好幾種,這裡整理三種常見寫法,並著重說明其中最容易讓人踩坑的一個細節。 方式一:Handler + Runnable Handler handler
Android JetPlayer 教學:用 JetCreator 製作互動式音樂內容
Android 平台內建了 JET 引擎,讓應用程式能播放具互動性的 JET 音訊內容——這是一種把音樂拆成多個片段(segment)、可依遊戲狀態即時排列播放的格式,特
Android 對話框彈出位置與透明度的實作詳解
預設的對話框總是顯示在畫面正中央,但實際開發中,我們常常需要調整它的位置(例如置於螢幕上方或下方),或是做出透明、半透明乃至背景模糊的效果。要達成這些客製化需求,關鍵在於