一.Broadcast Receive為廣播接收器,它和事件處理機制類似,隻不過事件的處理機制是程式元件級别的,而廣播處理機制是系統級别的。
Broadcast Receiver用于接收并處理廣播通知(broadcast announcements)。多數的廣播是系統發起的,如地域變換、電量不足、來電來信等。程式也可以播放一個廣播。程式可以有任意數量的 broadcast receivers來響應它覺得重要的通知。broadcast receiver可以通過多種方式通知使用者:啟動activity、使用NotificationManager、開啟背景燈、振動裝置、播放聲音等,最典型的是在狀态欄顯示一個圖示,這樣使用者就可以點它打開看通知内容。
通常我們的某個應用或系統本身在某些事件(電池電量不足、來電來短信)來臨時會廣播一個Intent出去,我們可以利用注冊一個Broadcast Receiver來監聽到這些Intent并擷取Intent中的資料。
二.事件的廣播比價簡單,建構Intent對象,調用sendBroadcast()方法将廣播發出。事件的接收是通過定義一個繼承BroadcastReceiver類來實作,繼承該類後覆寫其onReceiver方法,并在該方法中相應事件。
MainActivity:
Intent intent=new Intent();
intent.setAction(MY_ACTION);
intent.putExtra("msg","請回複");
sendBroadcast(intent);
MyReceiver:
public calss MyReceiver extends BroadcastReceiver{
public void onReceiver(Context ctx,intent intent){
//從Intent中獲得資訊
String msg=intent.getString("msg");
Toast.makeText(ctx,msg,Toast.LENGTH_LONG).show()
}
三.系統廣播事件的使用
1. 這些廣播是系統自動發出,我們直接定義事件接收器進行接收。
通過配置檔案注冊
MyReceiver2:
public class MyReceiver2 extends BroadcastReceiver{
public void onReceiver( Context context,Intent intent){
Log.i("my_tag","BOOT_COMPLETED")
AndroidMainifest.xml:
<receiver android:name="MyReceiver2">
<intent-filter>
<android android:name="android.intent.android.BOOT_COMPLETED">
</intent-filter>
</receiver>
通過代碼注冊:
IntentFilter filter=new IntentFilter();//執行個體化
//執行個體化Receiver
MyReceiver2=new MyReceiver2();
//注冊Receiver
registerReceiver(r,filter);
//登出Receiver
unregisterReceiver(r);
四.Notification和NotificationManager的使用
Broadcast Receiver元件并沒有提供可視化的界面來顯示廣播資訊。這裡我們可以使用Notification和Notification Manager來實作可視化的資訊的界面,通過使用它們 ,我們可以顯示廣播資訊的内容,圖示及震動資訊。
五.AlarmManager的使用
現在的手機普遍都會有一個鬧鐘功能,如果使用Android來實作一個鬧鐘,可以使用AlarmManager來實作。AndroidManager提供了一種系統級的提示服務,允許你安排在将來的某個時間執行一個任務,AlarmManager對象一般不直接執行個體化,而是通過Context.getSystemService(Context.ALARM_SERVICE)方法獲得。
執行個體一、自定義broadcast receive來處理廣播事件
/Chapter08_Broadcast_Receiver1/src/com/amaker/ch08/app/MainActivity.java
代碼
package com.amaker.ch08.app;
import com.amaker.ch08.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
*
* 發出廣播
*/
public class MainActivity extends Activity {
// 定義一個Action常量
private static final String MY_ACTION = "com.amaker.ch08.action.MY_ACTION";
// 定義一個Button對象
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 設定目前布局視圖
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.Button01);
// 為按鈕設定單擊監聽器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 執行個體化Intent對象
Intent intent = new Intent();
// 設定Intent action屬性
intent.setAction(MY_ACTION);
// 為Intent添加附加資訊
intent.putExtra("msg", "地瓜地瓜,我是洋芋,收到請回複,收到請回複!");
// 發出廣播
sendBroadcast(intent);
}
});
}
自定義廣播事件的使用
/Chapter08_Broadcast_Receiver1/src/com/amaker/ch08/app/MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.widget.Toast;
* 接收廣播
public class MyReceiver extends BroadcastReceiver{
public void onReceive(Context cxt, Intent intent) {
// 從Intent中獲得資訊
String msg = intent.getStringExtra("msg");
// 使用Toast顯示
Toast.makeText(cxt, msg, Toast.LENGTH_LONG).show();
/Chapter08_Broadcast_Receiver1/src/com/amaker/ch08/app/MyReceiver2.java
import android.util.Log;
* 顯示系統啟動完成廣播接收器
public class MyReceiver2 extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
// 顯示廣播資訊
Log.i("my_tag", "BOOT_COMPLETED~~~~~~~~~~~~~~~~");
系統廣播事件的使用
/Chapter08_Broadcast_Receiver1/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:text="發出廣播..."
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
/Chapter08_Broadcast_Receiver1/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.amaker.ch08.app"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyReceiver">
<action android:name="com.amaker.ch08.action.MY_ACTION"/>
</receiver>
<receiver android:name="MyReceiver2">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
二、notification和notificationmanager的使用
1、擷取系統級的服務notificationmanager
String service = NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager)getSystemService(service);
2、執行個體化Notification
Notification n = new Notification();
// 設定顯示圖示,該圖示會在狀态欄顯示
int icon = n.icon = R.drawable.icon;
// 設定顯示提示資訊,該資訊也會在狀态欄顯示
String tickerText = "Test Notification";
// 顯示時間
long when = System.currentTimeMillis();
n.icon = icon;
n.tickerText = tickerText;
n.when = when;
// 也可以通過這種構造方法來設定
Notification n1 = new Notification(icon, tickerText, when);
3、執行個體化Intent
Intent intent = new Intent(this, MainActivity_Temp.class);
// 獲得PendingIntent
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
// 設定事件資訊
n.setLatestEventInfo(this, "My Title", "My Content", pi);
n.defaults |= Notification.DEFAULT_SOUND;
n.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
n.defaults |= Notification.DEFAULT_VIBRATE;
long[] vibrate = {0,50,100,150};
n.vibrate = vibrate;
n.defaults |= Notification.DEFAULT_LIGHTS;
n.ledARGB = 0xff00ff00;
n.ledOnMS = 300;
n.ledOffMS = 1000;
n.flags |= Notification.FLAG_SHOW_LIGHTS;
4、發通知
// 标示該通知的ID
int ID = 1;
// 發出通知
nm.notify(ID, n);
利用notification和notificationmanager來實作可視化的消息顯示。
/Chapter08_Notification1/src/com/amaker/ch08/app/MainActivity.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
* 測試通知
// 聲明按鈕
private Button sendBtn,cancelBtn;
// 聲明Notification
private Notification n ;
// 聲明NotificationManager
private NotificationManager nm;
// Notification标示ID
private static final int ID = 1;
// 執行個體化按鈕
sendBtn = (Button)findViewById(R.id.sendButton01);
cancelBtn = (Button)findViewById(R.id.cancelButton02);
// 獲得NotificationManager執行個體
String service = NOTIFICATION_SERVICE;
nm = (NotificationManager)getSystemService(service);
// 執行個體化Notification
n = new Notification();
// 設定顯示圖示,該圖示會在狀态欄顯示
int icon = n.icon = R.drawable.happy;
// 設定顯示提示資訊,該資訊也會在狀态欄顯示
String tickerText = "Test Notification";
// 顯示時間
long when = System.currentTimeMillis();
n.icon = icon;
n.tickerText = tickerText;
n.when = when;
// 為按鈕添加監聽器
sendBtn.setOnClickListener(sendListener);
cancelBtn.setOnClickListener(cancelListener);
// 發送通知監聽器
private OnClickListener sendListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 執行個體化Intent
Intent intent = new Intent(MainActivity.this, MainActivity.class);
// 獲得PendingIntent
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
// 設定事件資訊
n.setLatestEventInfo(MainActivity.this, "My Title", "My Content", pi);
// 發出通知
nm.notify(ID, n);
}
};
// 取消通知監聽器
private OnClickListener cancelListener = new OnClickListener() {
// 取消通知
nm.cancel(ID);
/Chapter08_Notification1/res/layout/main.xml
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="測試Notification"
/>
<Button
android:text="發出通知"
android:id="@+id/sendButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
android:text="取消通知"
android:id="@+id/cancelButton02"
/Chapter08_Notification1/AndroidManifest.xml
二、notification、notificationmanager和broadcast receiver的綜合執行個體
/Chapter08_Notification2/src/com/amaker/ch08/app/MainActivity.java
* 測試廣播和通知
// 聲明Button
// 定義Broadcast Receiver action
private static final String MY_ACTION = "com.amaker.ch08.app.MY_ACTION";
// 執行個體化Button
// 添加事件監聽器
btn.setOnClickListener(listener);
// 建立事件監聽器
private OnClickListener listener = new OnClickListener() {
Intent intent = new Intent();
// 設定Intent action屬性
intent.setAction(MY_ACTION);
// 發起廣播
sendBroadcast(intent);
/Chapter08_Notification2/src/com/amaker/ch08/app/DisplayActivity.java
public class DisplayActivity extends Activity {
private Button cancelBtn;
@Override
setContentView(R.layout.main2);
// 執行個體化Intent
Intent intent = new Intent(this, MainActivity.class);
// 獲得PendingIntent
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
// 設定事件資訊
n.setLatestEventInfo(this, "My Title", "My Content", pi);
// 發出通知
nm.notify(ID, n);
@Override
/Chapter08_Notification2/src/com/amaker/ch08/app/MyReceiver.java
Intent i = new Intent();
// 在新的任務中啟動Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 設定Intent啟動的元件名稱
i.setClass(context, DisplayActivity.class);
// 啟動Activity顯示通知
context.startActivity(i);
/Chapter08_Notification2/res/layout/main.xml
android:text="發出廣播"
android:layout_height="wrap_content"></Button>
<action android:name="com.amaker.ch08.app.MY_ACTION"/>
<activity android:name="DisplayActivity"/>
本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1079393