一.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

package com.amaker.ch08.app;
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 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

package com.amaker.ch08.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
*
* 显示系统启动完成广播接收器
*/
public class MyReceiver2 extends BroadcastReceiver{
@Override
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

<?xml version="1.0" encoding="utf-8"?>
<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">
<intent-filter>
<action android:name="com.amaker.ch08.action.MY_ACTION"/>
</intent-filter>
</receiver>
<receiver android:name="MyReceiver2">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</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.parse("file:///sdcard/sound.mp3");
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

package com.amaker.ch08.app;
import com.amaker.ch08.app.R;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
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 {
// 声明按钮
private Button sendBtn,cancelBtn;
// 声明Notification
private Notification n ;
// 声明NotificationManager
private NotificationManager nm;
// Notification标示ID
private static final int ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 实例化按钮
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() {
@Override
public void onClick(View v) {
// 取消通知
nm.cancel(ID);
}
};
}
/Chapter08_Notification1/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"
>
<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>
<Button
android:text="取消通知"
android:id="@+id/cancelButton02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
/Chapter08_Notification1/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<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>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
二、notification、notificationmanager和broadcast receiver的综合实例
/Chapter08_Notification2/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 {
// 声明Button
private Button btn;
// 定义Broadcast Receiver action
private static final String MY_ACTION = "com.amaker.ch08.app.MY_ACTION";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置当前布局视图
setContentView(R.layout.main);
// 实例化Button
btn = (Button)findViewById(R.id.Button01);
// 添加事件监听器
btn.setOnClickListener(listener);
}
// 创建事件监听器
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// 实例化Intent
Intent intent = new Intent();
// 设置Intent action属性
intent.setAction(MY_ACTION);
// 发起广播
sendBroadcast(intent);
}
};
}
/Chapter08_Notification2/src/com/amaker/ch08/app/DisplayActivity.java

package com.amaker.ch08.app;
import com.amaker.ch08.app.R;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DisplayActivity extends Activity {
// 声明按钮
private Button cancelBtn;
// 声明Notification
private Notification n ;
// 声明NotificationManager
private NotificationManager nm;
// Notification标示ID
private static final int ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
// 实例化按钮
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;
// 实例化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);
// 为按钮添加监听器
cancelBtn.setOnClickListener(cancelListener);
}
// 取消通知监听器
private OnClickListener cancelListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 取消通知
nm.cancel(ID);
}
};
}
/Chapter08_Notification2/src/com/amaker/ch08/app/MyReceiver.java

package com.amaker.ch08.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// 实例化Intent
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

<?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"></Button>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<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">
<intent-filter>
<action android:name="com.amaker.ch08.app.MY_ACTION"/>
</intent-filter>
</receiver>
<activity android:name="DisplayActivity"/>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>