Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách đăng ký Intent Filter tùy chỉnh cho BroadcastReceiver trong Android

Giới thiệu về Intent Filter

Intent Filter là thể hiện của lớp IntentFilter. Nó giúp Android hiểu được loại implicit intent nào mà component (Activity, Service, BroadcastReceiver) có thể xử lý. Thông tin này được khai báo trong AndroidManifest.xml (cho receiver tĩnh) hoặc đăng ký động trong code Java/Kotlin.

Android thực hiện 3 bài kiểm tra trước khi phân phát intent: Action test, Category test, Data test.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project, điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Đăng ký Broadcast Receiver" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Gửi Broadcast" />

</LinearLayout>

Bước 3: Viết logic (src/MainActivity.java)

package com.example.andy.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // BroadcastReceiver động - khai báo trong Activity
    private final BroadcastReceiver customReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Toast.makeText(MainActivity.this, "Nhận: " + action, Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnRegister = findViewById(R.id.btnRegister);
        Button btnSend = findViewById(R.id.btnSend);

        // Nút gửi broadcast
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.andy.CUSTOM_INTENT");
                // Có thể thêm data: intent.putExtra("key", "value");
                sendBroadcast(intent);
            }
        });

        // Nút đăng ký receiver
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentFilter filter = new IntentFilter("com.example.andy.CUSTOM_INTENT");
                // Có thể thêm action/category/data khác vào filter
                registerReceiver(customReceiver, filter);
                Toast.makeText(MainActivity.this, "Đã đăng ký receiver", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        // QUAN TRỌNG: Hủy đăng ký receiver động khi Activity không còn foreground
        try {
            unregisterReceiver(customReceiver);
        } catch (IllegalArgumentException e) {
            // Receiver chưa được đăng ký - bỏ qua
        }
    }
}

Giải thích luồng hoạt động

  1. Nhấn Đăng ký Broadcast Receiver → registerReceiver() với IntentFilter action tùy chỉnh
  2. Nhấn Gửi Broadcast → Tạo Intent cùng action → sendBroadcast()
  3. Hệ thống phân phát intent đến receiver đã đăng ký → onReceive() hiển thị Toast
  4. Khi Activity pause → unregisterReceiver() tránh rò rỉ bộ nhớ

Chạy ứng dụng

Kết nối thiết bị và chạy ứng dụng.

Cách đăng ký Intent Filter tùy chỉnh cho BroadcastReceiver trong Android

Nhấn "Đăng ký Broadcast Receiver" rồi "Gửi Broadcast":

Cách đăng ký Intent Filter tùy chỉnh cho BroadcastReceiver trong Android

Lưu ý quan trọng:
  • Receiver động: Đăng ký/hủy trong code (như ví dụ). Phải hủy trong onPause()/onDestroy().
  • Receiver tĩnh: Khai báo trong AndroidManifest.xml với <receiver>. Luôn hoạt động, kể cả khi app chưa chạy.
  • Từ Android 8.0 (API 26), nhiều broadcast ngầm bị hạn chế → ưu tiên receiver động hoặc JobScheduler/WorkManager.
  • Action nên dùng tên miền ngược (reverse domain) để tránh xung đột: com.tencongty.tenapp.ACTION