SlideShare a Scribd company logo
1 of 18
ANDROID NÂNG CAO
Bài 3:

Broadcast Receiver
Nội dung bài học
●

Send broadcast một Intent.

●

System broadcast.

●

Hiện thực Broadcast Receiver.

●

Vòng đời của Broadcast Receiver.

●

Hạn chế của Broadcast Receiver.

●

Đăng ký broadcast receiver bằng code.

●

Disable receiver đã đăng ký trong manifest.

●

Sticky Broadcast Intent
Send broadcast một Intent
●

Send trong cùng một process.

●

Send cho toàn hệ thống.
Send broadcast một Intent
●

Send trong cùng một process:
●

Sử dụng các phương thức sau đây để send broadcast một
Intent trong một process:
–
–

LocalBroadcastManager#sendBroadcast →
asynchronous
LocalBroadcastManager#sendBroadcastSync → nếu
có receiver cho Intent thì phương thức này sẽ block và
ngay lập tức gọi receiver thực thi.
Send broadcast một Intent
●

Send cho toàn bộ hệ thống:
●

Sử dụng các phương thức sau đây để send broadcast
một Intent cho toàn bộ hệ thống:
–
–

Context#sendBroadcast → asynchronous, unordered
Context#sendOrderedBroadcast:
●
●

●
●

One receiver at a time.
The order is configured by android:priority. If the priorities are
same, the order is undetermined.
The result of the first receiver is passed to the next one.
We can abort the broadcast to stop the result propogate.
System Broadcast
●

●

Trong Android nhiều system event được hệ
thống gửi đến toàn bộ các ứng dụng trong hệ
thống dưới dạng các broadcast intent. Các intent
này có các action định nghĩa dưới dạng các biến
final static trong lớp Intent cũng như các lớp
khác như TelephonyManager.
Một số event quan trọng:
●

Intent.ACTION_BOOT_COMPLETED

●

Intent.ACTION_BATTERY_LOW

●

Intent.ACTION_BATTERY_OKAY
Hiện thực Broadcast Receiver
●

Kế thừa lớp BroadcastReceiver.

●

Hiện thực phương thức onReceiver.

●

Đăng ký receiver vào AndroidManifest.xml
Hiện thực Broadcast Receiver
●

Kế thừa lớp BroadcastReceiver.

●

Hiện thực phương thức onReceiver.

●

Đăng ký receiver vào AndroidManifest.xml
Hiện thực Broadcast Receiver
public class SampleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Nếu cần chúng ta cần kiểm tra action của intent chúng ta nhận
// đúng là action mà chúng ta mong đợi rồi mới thực hiện
// phần nghiệp vụ
Intent service = new Intent(context, SampleService.class);
context.startService(service);
}
}
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<receiver android:name="SampleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
...
Hiện thực Broadcast Receiver
●

Lưu ý:
●

●

●

Nếu chương trình cài đặt ở SD Card (thuộc tính location) thì
chương trình không nhận được sự kiện
ACTION_BOOT_COMPLETED vì sự kiện này xảy ra trước
khi chương trình thực thi. Trong tình huống này chúng ta
dùng sự kiện:
ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
Trên các điện thoại HTC, sự kiện này cũng không nhận được
khi chạy dưới chế độ “Fast Boot”.
Từ Android 3.0, người dùng cần start ứng dụng ít nhất 1 lần
thì ứng dụng mới nhận sự kiện này.
Vòng đời của Broadcast Receiver
●

●

BroadcastReciver chỉ có giá trị trong khi onReciver được gọi.
Khi phương thức này kết thúc thì receiver kết thúc và không còn
ở trạng thái active nữa.
Lưu ý:
●

●

●

Không thể gọi hàm bất đồng bộ bên trong onReceive vì hàm
này sẽ không có điểm quay về khi receiver không còn tồn tại.
Không nên show dialog mà nên dùng Notification bên trong
onReceive.
Không nên bind service mà nên dùng startService bên trong
onReceive.
Hạn chế của Broadcast Receiver
●

●

BroadcastReciver phải kết thúc việc thực thi trong 10 giây nếu
không thì nó sẽ trigger ANR exception.
Từ Android 3.1, mặc định hệ thống sẽ loại bỏ tất cả các receiver
từ các intent nếu như ứng dụng tương ứng với các receiver này
chưa được start bởi người dùng bao giờ hoặc các ứng dụng này
bị stop một cách tường minh bởi người dùng thông qua menu
(Manage Application).
Đăng ký Broadcast Receiver bằng code
●

Ngoài phương pháp đăng ký receiver trong
AndroidManifest.xml file chúng ta có thể đăng ký receiver bằng
code:
●

●

Trong onResume của Activity, chúng ta sử dụng
Contex#registerReceiver
(LocalBroadcastManager#registerReceiver).
Trong onPause của Activity, chúng ta sử dụng:
Context#unregisterReceiver
(LocalBroadcastManager#unregisterReceiver).
Disable receiver
●

Để disable một receiver đã đăng ký trong manifest file chúng ta
sử dụng PackageManger:

ComponentName mReceiver = new ComponentName(context, SampleReceiver.class);
PackageManager mManager = context.getPackageManager();
mManager.setComponentEnabledSetting(mReceiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Sticky Broadcast Intent
●

●

●

Broadcast intent thông thường thì sẽ bị mất sau khi hệ thống xử
lý xong.
Nếu chúng ta sử dụng Context#sendStickyBroadcastIntent để
gửi broadcast intent thì intent này nó không mất đi sau khi hệ
thống xử lý. Chúng ta có thể truy xuất đến intent này bằng
phương thức Context#registerReciver(BroadcastReceiver,
IntentFilter), trong đó nếu BroadcastReceiver = null thì phương
thức vẫn hoạt động.
Ví dụ Intent.ACTION_BATTERY_CHANGED là một sticky
broadcast intent. Chúng ta có thể truy xuất đến nó bất cứ lúc nào
sau khi nó được gửi.
Bài tập 06
●

Hiện thực chương trình mô tả như trong hình:
Nhập vào số giây
Nhấn nút “Start”
Xem thêm các class sau:
● PendingIntent
● AlarmManager
● Vibrator

10 giây sau, điện thoại rung
và 1 toast hiện ra thông điệp
Nguyen Huu Phuoc, MEng.
●

 Blog:http://folami.nghelong.com

●

 Website http://phuocnh.nghelong.com
Nguyen Huu Phuoc, MEng.
●

 nhphuoc@vn.isb.co.jp

●

 (84) 3.812.7145 Ext.118

●

 http://phuocnh.nghelong.com

More Related Content

Viewers also liked

Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development
Phuoc Nguyen
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
Phuoc Nguyen
 
Bài 1: Giới thiệu Android
Bài 1: Giới thiệu AndroidBài 1: Giới thiệu Android
Bài 1: Giới thiệu Android
hoccungdoanhnghiep
 
56123159 android
56123159 android56123159 android
56123159 android
Hieu Pham
 

Viewers also liked (18)

Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development Android Nâng cao-Bài 9-Debug in Android Application Development
Android Nâng cao-Bài 9-Debug in Android Application Development
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
 
IT120-1. Giới thiệu về Android SDK
IT120-1. Giới thiệu về Android SDKIT120-1. Giới thiệu về Android SDK
IT120-1. Giới thiệu về Android SDK
 
Android chapter03-life-cycle
Android chapter03-life-cycleAndroid chapter03-life-cycle
Android chapter03-life-cycle
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android ios wp7
Android ios wp7Android ios wp7
Android ios wp7
 
Google Android Security (Basic2Advanced)
Google Android Security (Basic2Advanced)Google Android Security (Basic2Advanced)
Google Android Security (Basic2Advanced)
 
Android chapter03-life-cycle
Android chapter03-life-cycleAndroid chapter03-life-cycle
Android chapter03-life-cycle
 
Basic Sqlite in Android
Basic Sqlite in AndroidBasic Sqlite in Android
Basic Sqlite in Android
 
Slide hội thảo Google Android BKHN 26-10
Slide hội thảo Google Android BKHN 26-10Slide hội thảo Google Android BKHN 26-10
Slide hội thảo Google Android BKHN 26-10
 
Android OS
Android OSAndroid OS
Android OS
 
Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...
Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...
Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...
 
Lap trinh android – kiem tien ngay trong khi hoc
Lap trinh android – kiem tien ngay trong khi hocLap trinh android – kiem tien ngay trong khi hoc
Lap trinh android – kiem tien ngay trong khi hoc
 
Tìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành androidTìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành android
 
Bài 1: Giới thiệu Android
Bài 1: Giới thiệu AndroidBài 1: Giới thiệu Android
Bài 1: Giới thiệu Android
 
56123159 android
56123159 android56123159 android
56123159 android
 
Kerudung syar’ie & trendy
Kerudung syar’ie & trendyKerudung syar’ie & trendy
Kerudung syar’ie & trendy
 
Demand-Driven Acquisitions, Part 1
Demand-Driven Acquisitions, Part 1Demand-Driven Acquisitions, Part 1
Demand-Driven Acquisitions, Part 1
 

Similar to Android Nâng cao-Bài 3: Broadcast Receiver (7)

Slide bài giảng lập trình Android DTU - Phần 5 (Broadcastreceiver)
Slide bài giảng lập trình Android DTU - Phần 5 (Broadcastreceiver)Slide bài giảng lập trình Android DTU - Phần 5 (Broadcastreceiver)
Slide bài giảng lập trình Android DTU - Phần 5 (Broadcastreceiver)
 
Hướng Dẫn Lập Trình Android: 5. BroadcastReceiver
Hướng Dẫn Lập Trình Android: 5. BroadcastReceiverHướng Dẫn Lập Trình Android: 5. BroadcastReceiver
Hướng Dẫn Lập Trình Android: 5. BroadcastReceiver
 
5. broadcast receiver
5. broadcast receiver5. broadcast receiver
5. broadcast receiver
 
Hướng Dẫn Lập Trình Android: 7. Xu ly bat dong bo
Hướng Dẫn Lập Trình Android: 7. Xu ly bat dong boHướng Dẫn Lập Trình Android: 7. Xu ly bat dong bo
Hướng Dẫn Lập Trình Android: 7. Xu ly bat dong bo
 
Bài 4: Event handle, Action & Intent
Bài 4: Event handle, Action & IntentBài 4: Event handle, Action & Intent
Bài 4: Event handle, Action & Intent
 
SMS-2 (1).pptx
SMS-2 (1).pptxSMS-2 (1).pptx
SMS-2 (1).pptx
 
Báo cáo tìm hiểu và xây dựng ứng dụng map trên android
Báo cáo tìm hiểu và xây dựng ứng dụng map trên androidBáo cáo tìm hiểu và xây dựng ứng dụng map trên android
Báo cáo tìm hiểu và xây dựng ứng dụng map trên android
 

More from Phuoc Nguyen (7)

Lanh dao va TPP
Lanh dao va TPPLanh dao va TPP
Lanh dao va TPP
 
Hiberbate Framework
Hiberbate FrameworkHiberbate Framework
Hiberbate Framework
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Webservice performance testing with SoapUI
Webservice performance testing with SoapUIWebservice performance testing with SoapUI
Webservice performance testing with SoapUI
 
Web application security test tools
Web application security test toolsWeb application security test tools
Web application security test tools
 
A successful project sharing
A successful project sharingA successful project sharing
A successful project sharing
 
Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)Buồn vui nghề IT (Pros & cons of IT Career)
Buồn vui nghề IT (Pros & cons of IT Career)
 

Android Nâng cao-Bài 3: Broadcast Receiver

  • 1. ANDROID NÂNG CAO Bài 3: Broadcast Receiver
  • 2. Nội dung bài học ● Send broadcast một Intent. ● System broadcast. ● Hiện thực Broadcast Receiver. ● Vòng đời của Broadcast Receiver. ● Hạn chế của Broadcast Receiver. ● Đăng ký broadcast receiver bằng code. ● Disable receiver đã đăng ký trong manifest. ● Sticky Broadcast Intent
  • 3. Send broadcast một Intent ● Send trong cùng một process. ● Send cho toàn hệ thống.
  • 4. Send broadcast một Intent ● Send trong cùng một process: ● Sử dụng các phương thức sau đây để send broadcast một Intent trong một process: – – LocalBroadcastManager#sendBroadcast → asynchronous LocalBroadcastManager#sendBroadcastSync → nếu có receiver cho Intent thì phương thức này sẽ block và ngay lập tức gọi receiver thực thi.
  • 5. Send broadcast một Intent ● Send cho toàn bộ hệ thống: ● Sử dụng các phương thức sau đây để send broadcast một Intent cho toàn bộ hệ thống: – – Context#sendBroadcast → asynchronous, unordered Context#sendOrderedBroadcast: ● ● ● ● One receiver at a time. The order is configured by android:priority. If the priorities are same, the order is undetermined. The result of the first receiver is passed to the next one. We can abort the broadcast to stop the result propogate.
  • 6. System Broadcast ● ● Trong Android nhiều system event được hệ thống gửi đến toàn bộ các ứng dụng trong hệ thống dưới dạng các broadcast intent. Các intent này có các action định nghĩa dưới dạng các biến final static trong lớp Intent cũng như các lớp khác như TelephonyManager. Một số event quan trọng: ● Intent.ACTION_BOOT_COMPLETED ● Intent.ACTION_BATTERY_LOW ● Intent.ACTION_BATTERY_OKAY
  • 7. Hiện thực Broadcast Receiver ● Kế thừa lớp BroadcastReceiver. ● Hiện thực phương thức onReceiver. ● Đăng ký receiver vào AndroidManifest.xml
  • 8. Hiện thực Broadcast Receiver ● Kế thừa lớp BroadcastReceiver. ● Hiện thực phương thức onReceiver. ● Đăng ký receiver vào AndroidManifest.xml
  • 9. Hiện thực Broadcast Receiver public class SampleReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //Nếu cần chúng ta cần kiểm tra action của intent chúng ta nhận // đúng là action mà chúng ta mong đợi rồi mới thực hiện // phần nghiệp vụ Intent service = new Intent(context, SampleService.class); context.startService(service); } } <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> ... <receiver android:name="SampleReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> ...
  • 10. Hiện thực Broadcast Receiver ● Lưu ý: ● ● ● Nếu chương trình cài đặt ở SD Card (thuộc tính location) thì chương trình không nhận được sự kiện ACTION_BOOT_COMPLETED vì sự kiện này xảy ra trước khi chương trình thực thi. Trong tình huống này chúng ta dùng sự kiện: ACTION_EXTERNAL_APPLICATIONS_AVAILABLE Trên các điện thoại HTC, sự kiện này cũng không nhận được khi chạy dưới chế độ “Fast Boot”. Từ Android 3.0, người dùng cần start ứng dụng ít nhất 1 lần thì ứng dụng mới nhận sự kiện này.
  • 11. Vòng đời của Broadcast Receiver ● ● BroadcastReciver chỉ có giá trị trong khi onReciver được gọi. Khi phương thức này kết thúc thì receiver kết thúc và không còn ở trạng thái active nữa. Lưu ý: ● ● ● Không thể gọi hàm bất đồng bộ bên trong onReceive vì hàm này sẽ không có điểm quay về khi receiver không còn tồn tại. Không nên show dialog mà nên dùng Notification bên trong onReceive. Không nên bind service mà nên dùng startService bên trong onReceive.
  • 12. Hạn chế của Broadcast Receiver ● ● BroadcastReciver phải kết thúc việc thực thi trong 10 giây nếu không thì nó sẽ trigger ANR exception. Từ Android 3.1, mặc định hệ thống sẽ loại bỏ tất cả các receiver từ các intent nếu như ứng dụng tương ứng với các receiver này chưa được start bởi người dùng bao giờ hoặc các ứng dụng này bị stop một cách tường minh bởi người dùng thông qua menu (Manage Application).
  • 13. Đăng ký Broadcast Receiver bằng code ● Ngoài phương pháp đăng ký receiver trong AndroidManifest.xml file chúng ta có thể đăng ký receiver bằng code: ● ● Trong onResume của Activity, chúng ta sử dụng Contex#registerReceiver (LocalBroadcastManager#registerReceiver). Trong onPause của Activity, chúng ta sử dụng: Context#unregisterReceiver (LocalBroadcastManager#unregisterReceiver).
  • 14. Disable receiver ● Để disable một receiver đã đăng ký trong manifest file chúng ta sử dụng PackageManger: ComponentName mReceiver = new ComponentName(context, SampleReceiver.class); PackageManager mManager = context.getPackageManager(); mManager.setComponentEnabledSetting(mReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
  • 15. Sticky Broadcast Intent ● ● ● Broadcast intent thông thường thì sẽ bị mất sau khi hệ thống xử lý xong. Nếu chúng ta sử dụng Context#sendStickyBroadcastIntent để gửi broadcast intent thì intent này nó không mất đi sau khi hệ thống xử lý. Chúng ta có thể truy xuất đến intent này bằng phương thức Context#registerReciver(BroadcastReceiver, IntentFilter), trong đó nếu BroadcastReceiver = null thì phương thức vẫn hoạt động. Ví dụ Intent.ACTION_BATTERY_CHANGED là một sticky broadcast intent. Chúng ta có thể truy xuất đến nó bất cứ lúc nào sau khi nó được gửi.
  • 16. Bài tập 06 ● Hiện thực chương trình mô tả như trong hình: Nhập vào số giây Nhấn nút “Start” Xem thêm các class sau: ● PendingIntent ● AlarmManager ● Vibrator 10 giây sau, điện thoại rung và 1 toast hiện ra thông điệp
  • 17. Nguyen Huu Phuoc, MEng. ●  Blog:http://folami.nghelong.com ●  Website http://phuocnh.nghelong.com
  • 18. Nguyen Huu Phuoc, MEng. ●  nhphuoc@vn.isb.co.jp ●  (84) 3.812.7145 Ext.118 ●  http://phuocnh.nghelong.com