Broadcast Receiver trong Android Broadcast Receiver phản hồi các thông báo phát ra từ các ứng dụng khác hoặc từ chính hệ thống.. Ví dụ, các ứng dụng cũng có thể khởi tạo các tín hiệu br
Trang 1Broadcast Receiver trong Android
Broadcast Receiver phản hồi các thông báo phát ra từ các ứng dụng khác hoặc từ chính
hệ thống Những thông báo này đôi khi được gọi là các event hoặc intent Ví dụ, các ứng dụng cũng có thể khởi tạo các tín hiệu broadcast để thông báo cho ứng dụng khác biết rằng một số dữ liệu đã được về tới thiết vị và là có sẵn cho chúng để sử dụng, vì thế Broadcast Receiver thông dịch thông tin đó và khởi tạo hành động thích hợp
Sau đây là hai bước quan trọng để làm Broadcast Receiver làm việc cho các Intent: −
• Tạo Broadcast Receiver
• Đăng ký Broadcast Receiver
Có thể có một bước bổ sung nếu bạn đang triển khai các Custom Intent của bạn, thì khi đó bạn sẽ phải tạo và phát các Intent đó
Tạo Broadcast Receiver trong Android
Một Broadcast Receiver được triển khai như là một lớp con của lớp BroadcastReceiver và
ghi đè phương thức onReceive(), nơi mà mỗi thông báo được nhận như là một tham số của đối tượng Intent
public class MyReceiver extends BroadcastReceiver @Override public void onReceive( Context context, Intent intent) { Toast makeText(context,
"Intent Detected." , Toast LENGTH_LONG).show(); } }
Đăng ký Broadcast Receiver trong Android
Một ứng dụng nghe các Intent được phát ra cụ thể bằng cách đăng ký một Broadcast
Receiver trong AndroidManifest.xml file Giả sử chúng ta đang đăng ký MyReceiver cho
ACTION_BOOT_COMPLETED, mà được kích hoạt bởi hệ thống một khi hệ điều hành Android đã hoàn thành tiến trình boot
Trang 2BROADCAST-RECEIVER
<application android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name" android:theme = "@style/AppTheme"
<receiver android:name = "MyReceiver" > <intent-filter> <action
android:name = "android.intent.action.BOOT_COMPLETED" > </action>
</intent-filter> </receiver> </application>
Bây giờ, bất cứ khi nào thiết bị Android của bạn được boot, thì thông báo sẽ được nhận
bởiMyReceiver và trình triển khai logic bên trong phương thức onReceive() sẽ được thực
thi
Có một số system event được định nghĩa là là các trường final static trong lớp Intent Bảng
dưới liệt kê một số system event quan trọng:
android.intent.action.BATTERY_CHANGED Thông báo này chứa trạng thái nạp, mức độ, và
thông tin khác về pin
Trang 3android.intent.action.BATTERY_OKAY Chỉ rằng pin bây giờ là tốt sau khi low battery
android.intent.action.BOOT_COMPLETED Đây là tín hiệu broadcast thông báo sau khi hệ
thống đã kết thúc boot
bởi dữ liệu
điện) hoặc giao diện UI thích hợp khác để tạo một cuộc gọi
Tín hiệu Custom Intent
Nếu bạn muốn chính ứng dụng của bạn nên tạo và gửi các Custom Intent, thì khi đó bạn sẽ
phải tạo và gửi các Intent đó bằng việc sử dụng phương thức sendBroadcast() bên trong lớp Activity của bạn Nếu bạn sử dụng phương thức sendStickyBroadcast(Intent) thì Intent
làsticky, nghĩa là Intent bạn đang gửi vẫn ở đâu đó sau khi tín hiệu kết thúc
public void broadcastIntent( View view) { Intent intent = new Intent (); intent.setAction( "com.tutorialspoint.CUSTOM_INTENT" ); sendBroadcast(intent); }
Ở đây com.tutorialspoint.CUSTOM_INTENT cũng có thể được đăng ký theo cách tương tự
như chúng ta đã đăng ký intent được tạo ra từ hệ thống (system intent)
<application android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name" android:theme = "@style/AppTheme"
<receiver android:name = "MyReceiver" > <intent-filter> <action
android:name = "com.tutorialspoint.CUSTOM_INTENT" > </action>
</intent-filter> </receiver> </application>
Trang 4Ví dụ
Ví dụ này sẽ giải thích cách tạo BroadcastReceiver để chặn Custom Intent Khi bạn đã
quen với Custom Intent, bạn có thể lập trình ứng dụng để chặn các system intent Bạn theo
các bước sau để sửa đổi ứng dụng Android đã tạo trong chương Ví dụ Hello World − Bước Miêu tả
Application dưới một package là com.example.My Application như đã giải thích trong
chương Ví dụ Hello World
nghĩa một BroadcastReceiver
có bất cứ hạn chế nào Mỗi Intent bạn muốn chặn phải được đăng ký
trongAndroidManifest.xml file sử dụng thẻ <receiver />
5 Sửa đổi nội dung mặc định của res/layout/activity_main.xml file để bao một button để
thông báo Intent
6 Không cần sửa đổi string.xml file, Android Studio sẽ để ý điều đó
hiện trong ứng dụng
Sau đây là nội dung của activity file đã được sửa đổi src/com.example.My Application/MainActivity.java File này có thể bao các phương thức nền tảng Chúng ta
đã thêm phương thức broadcastIntent() để phát một Custom Intent
package com.example My Application ; import android.os Bundle ; import
android.app Activity ; import android.view Menu ; import android.content Intent ; import android.view View ; public class MainActivity extends Activity
@Override public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Trang 5setContentView( layout.activity_main); } @Override public
boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( menu.activity_main, menu); return true;
} // broadcast a custom intent public void broadcastIntent( View
view){ Intent intent = new Intent ();
intent.setAction( "com.tutorialspoint.CUSTOM_INTENT" );
sendBroadcast(intent); } }
Còn đây là nội dung của src/com.example.My Application/MyReceiver.java:
package com.example My Application ; import android.content BroadcastReceiver ;
import android.content Context ; import android.content Intent ; import
android.widget Toast ; public class MyReceiver extends BroadcastReceiver
@Override public void onReceive( Context context, Intent intent) {
Toast makeText(context, "Intent Detected." , Toast LENGTH_LONG).show(); } }
Sau đây là nội dung đã sửa đổi của AndroidManifest.xml file Ở đây, chúng ta đã thêm thẻ
<service /> để bảo vệ service:
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.My Application" android:versionCode = "1"
android:versionName = "1.0" <uses-sdk android:minSdkVersion = "8"
android:targetSdkVersion = "22" /> <application
android:icon = "@drawable/ic_launcher" android:label = "@string/app_name"
android:theme = "@style/AppTheme" <activity
android:name = ".MainActivity"
android:label = "@string/title_activity_main" <intent-filter>
<action android:name = "android.intent.action.MAIN" /> <category
android:name = "android.intent.category.LAUNCHER" /> </intent-filter>
</activity> <receiver android:name = "MyReceiver" >
<intent-filter> <action
android:name = "com.tutorialspoint.CUSTOM_INTENT" > </action>
</intent-filter> </receiver> </application>
</manifest>
Nội dung của res/layout/activity_main.xml để bao một button để phát Custom Intent −
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent" android:layout_height = "match_parent"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
android:paddingBottom = "@dimen/activity_vertical_margin"
tools:context = ".MainActivity" > <TextView
android:id = "@+id/textView1" android:layout_width = "wrap_content"
android:layout_height = "wrap_content" android:text = "Example of Broadcast"
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true" android:textSize = "30dp" />
Trang 6<TextView android:id = "@+id/textView2"
android:layout_width = "wrap_content" android:layout_height = "wrap_content"
android:text = "Tutorials point " android:textColor = "#ff87ff09"
android:textSize = "30dp" android:layout_above = "@+id/imageButton"
android:layout_centerHorizontal = "true" android:layout_marginBottom = "40dp"
/> <ImageButton android:layout_width = "wrap_content"
android:layout_height = "wrap_content" android:id = "@+id/imageButton"
android:src = "@drawable/abc" android:layout_centerVertical = "true"
android:layout_centerHorizontal = "true" /> <Button
android:layout_width = "wrap_content" android:layout_height = "wrap_content"
android:id = "@+id/button2" android:text = "Broadcast Intent"
android:onClick = "broadcastIntent" android:layout_below = "@+id/imageButton"
android:layout_centerHorizontal = "true" /> </RelativeLayout>
Và nội dung của res/values/strings.xml để định nghĩa hai hằng mới: −
<resources> <string name = "menu_settings" >Settings</string> <string
name = "title_activity_main" >My Application</string> </resources>
Chạy ứng dụng Hello World! vừa sửa đổi ở trên Giả sử bạn đã tạo AVD trong khi cài đặt
Để chạy ứng dụng từ Android Studio, mở activity file và nhấn biểu tượng Run từ thanh công cụ −
Trang 7Bây giờ, để phát Custom Intent, bạn nhấn vào nút Broadcast Intent nó sẽ
phát"com.tutorialspoint.CUSTOM_INTENT" mà sẽ bị chặn bởi BroadcastReceiver đã đăng
ký là MyReceiver và màn hình mô phỏng sẽ như sau: −
Trang 8Bạn có thể triển khai BroadcastReceiver khác để chặn các System intent như Bootup, date changed, low battery, …