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

Android 開發入門筆記:Activity、Intent 與廣播接收器一次搞懂

編輯:關於 Android 程式設計

這份筆記把 Android 入門階段最容易卡住的觀念整理成十三個主題,從資源目錄、Activity 生命週期,一路寫到廣播與本地廣播。適合搭配官方教學一起閱讀。

一、資源目錄怎麼分工

  • res/assets:放音樂等大型原始檔,不會被編譯進資源表,需用 AssetManager 讀取。
  • res/raw:同樣可放音樂,但會被編譯並生成資源 ID,可用 getResources().openRawResource() 開啟。
  • res/drawable:放圖片與 shape、selector 等可繪製資源。

差別的核心在於「要不要資源 ID」。需要程式碼直接參照的放 raw,純粹當檔案讀的放 assets。

二、把 Activity 設為啟動畫面

在 AndroidManifest.xml 的 Activity 節點內加上 MAIN/LAUNCHER 意圖篩選:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

三、隱藏標題列

在 setContentView() 之前呼叫以下方法,順序錯了就不會生效:

requestWindowFeature(Window.FEATURE_NO_TITLE);

四、Toast 與 Menu

Toast.makeText(FirstActivity.this, "You clicked Button 1", Toast.LENGTH_SHORT).show();

選單則是重寫 onCreateOptionsMenu() 以 inflate 選單 XML,再於 onOptionsItemSelected() 中判斷 item.getItemId() 分派處理。

五、銷毀 Activity 的兩種方式

最直接的是按返回鍵;若要在程式碼中關閉,呼叫 finish():

button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

六、Intent 在 Activity 之間穿梭

顯式 Intent:明確指定目標類別。

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

隱式 Intent:只宣告 action 與 category,由系統找出能處理的元件。

Intent intent = new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("com.example.activitytest.MY_CATEGORY");
startActivity(intent);

七、借用系統能力

開啟瀏覽器與撥號介面,都是隱式 Intent 的經典應用:

// 開啟瀏覽器
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.baidu.com"));
startActivity(intent);

// 開啟撥號介面(注意是 DIAL,不是 CALL)
Intent dial = new Intent(Intent.ACTION_DIAL);
dial.setData(Uri.parse("tel:10086"));
startActivity(dial);

兩者的差別值得記住:ACTION_DIAL 只把號碼帶進撥號盤,使用者仍需按下通話鍵;ACTION_CALL 會直接撥出,需要 CALL_PHONE 權限,誤用風險高。

八、Activity 之間傳遞資料

往下一頁傳值,用 putExtra():

String data = "Hello SecondActivity";
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("extra_data", data);
startActivity(intent);

下一頁在 onCreate() 中接收:

Intent intent = getIntent();
String data = intent.getStringExtra("extra_data");
Log.d("SecondActivity", data);

回傳值給上一頁,則要用 startActivityForResult():

// 第一個 Activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 1);

// 第二個 Activity 設定結果後關閉
Intent result = new Intent();
result.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, result);
finish();

// 第一個 Activity 接收
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
        String returnedData = data.getStringExtra("data_return");
        Log.d("FirstActivity", returnedData);
    }
}

九、Activity 生命週期

正常啟動時依序走 onCreate → onStart → onResume。

被新頁面完全覆蓋時走 onPause → onStop;返回時走 onRestart → onStart → onResume。

只是被半透明頁面或彈出對話框遮擋時,只走 onPause,返回時只走 onResume。

最終關閉時依序走 onPause → onStop → onDestroy。

十、Activity 被系統回收怎麼辦

記憶體吃緊時,處於 Stop 狀態的 Activity 可能被回收。使用者返回時頁面仍在,但走的是 onCreate() 而非 onRestart(),此前的暫存狀態會全部流失。

解法是重寫 onSaveInstanceState(Bundle outState),在可能回收前把資料放進 Bundle,再在 onCreate(Bundle savedInstanceState) 中從這個參數取出。

十一、四種啟動模式

  • standard:預設模式,每次啟動都新建一個實例入棧。
  • singleTop:若目標已位於堆疊頂端則重用它,否則照樣新建。
  • singleTask:整個工作區只保留一個實例,其上的 Activity 會被清出。
  • singleInstance:使用獨立的回傳堆疊,可讓不同應用共用同一個 Activity 實例。

十二、R 檔案突然找不到

多數情況是資源檔有誤或快取壞掉,執行 Build → Rebuild Project(或 Clean Project)通常就能恢復。

十三、廣播機制

類型:標準廣播完全非同步,所有接收器幾乎同時收到;有序廣播同步依序傳遞,優先級高者先收到,且可攔截。

動態註冊:在程式碼中建立 IntentFilter 並呼叫 registerReceiver(),記得一定要在 onDestroy() 中 unregisterReceiver(),否則會造成記憶體洩漏。

intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkChangeReceiver);
}

建立接收器:繼承 BroadcastReceiver 並重寫 onReceive()。

class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "network changes", Toast.LENGTH_SHORT).show();
    }
}

靜態註冊:在 AndroidManifest.xml 中以 <receiver> 搭配 <intent-filter> 宣告,即使 App 未啟動也能被系統喚起。

發送廣播:標準廣播用 sendBroadcast(),有序廣播用 sendOrderedBroadcast(),並可用 android:priority 控制順序;若在 onReceive() 中呼叫 abortBroadcast(),後續接收器就收不到了。

本地廣播:透過 LocalBroadcastManager 發送,廣播只在 App 內部流動,既不必擔心第三方竊聽,也不會被外部濫發,是安全性更好的選擇。

localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(new Intent("com.example.broadcasttest.LOCAL_BROADCAST"));
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
localBroadcastManager.unregisterReceiver(localReceiver);

把這十三個主題走過一遍,Activity 與廣播這兩大基礎就算站穩了。接下來再往 Service、ContentProvider 與自定義 View 推進,會順手很多。

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