0

Broadcast Receiver Trong Android

1. Giới thiệu về Broadcast Receiver trong Android

Broadcast Receiver là một trong các thành phần chính của android các bạn có thể hiểu nó như một bộ thu các bản tin cần thiết cho apps. Các bản tin được thu ở đây chính là các intent. Các bạn có thể thu các Intent sẵn có của hệ điều hành ví dụ như: tin nhắn đến, cuộc gọi đến, trạng thái của điện thoại, trạng thái của pin… Ngoài ra các bạn cũng có thể thu Intent của chính các bạn gửi ra để làm một nhiệm vụ gì đó (có thể dùng để start service khi cần).

2. Demo ứng dụng nhận tin nhắn

Để các bạn có thể hiểu về Broadcast Receiver mình làm một app đơn giản có chức năng thu các tin nhắn đến, khi có tin nhắn đến mình sẽ log số điện thoại và nội dung tin nhắn đến. Ngoài ra mình còn tạo một buton để send một Intent và tự thu intent đó bằng receiver.

B1. Tạo project mới

B2. Cấp quyền nhận tin nhắn trong AndroidMainifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="devpro.com.broadcastreceiverdemo">
    <uses-permission android:name="android.permission.RECEIVE_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

B3. Thiết kế giao diện

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="devpro.com.broadcastreceiverdemo.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

B4. Xử lý code trong MainActivity.java

 package devpro.com.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsMessage;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    BroadcastReceiver receiver = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //tạo bộ lọc để lắng nghe tin nhắn gửi tới
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        //tạo bộ lắng nghe
        receiver = new BroadcastReceiver() {
            //chú ý là dữ liệu trong tin nhắn được lưu trữ trong arg1
            @Override
            public void onReceive(Context context, Intent intent) {
                processReceive(context, intent);
            }
        };

        //đăng ký bộ lắng nghe vào hệ thống
        registerReceiver(receiver, filter);
    }

    protected void onDestroy() {
        super.onDestroy();
        //hủy bỏ đăng ký khi tắt ứng dụng
        unregisterReceiver(receiver);
    }

    public void processReceive(Context context, Intent intent) {
        //Thông báo khi có tin nhắn mới
        Toast.makeText(context, "Có 1 tin nhắn mới", Toast.LENGTH_LONG).show();
        TextView txtContent = (TextView) findViewById(R.id.txtContent);
        //pdus để lấy gói tin nhắn
        String sms_extra = "pdus";
        Bundle bundle = intent.getExtras();
        //bundle trả về tập các tin nhắn gửi về cùng lúc
        Object[] objArr = (Object[]) bundle.get(sms_extra);
        String sms = "";
        //duyệt vòng lặp để đọc từng tin nhắn
        for (int i = 0; i < objArr.length; i++) {
            //lệnh chuyển đổi về tin nhắn createFromPdu
            SmsMessage smsMsg = SmsMessage.
                    createFromPdu((byte[]) objArr[i]);
            //lấy nội dung tin nhắn
            String body = smsMsg.getMessageBody();
            //lấy số điện thoại tin nhắn
            String address = smsMsg.getDisplayOriginatingAddress();
            sms += address + ":\n" + body + "\n";
        }
        //hiển thị lên giao diện
        txtContent.setText(sms);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí