第八章:Android广播事件处理 Broadcast Receiver

Broadcast Receiver广播接收器。事件的广播比较简单,同样还是构建Intent对象,然后调用sendBroadcast()方法将广播发出。事件的接收是通过定义一个继承BroadcastReceiver的类来实现的,继承该类后覆盖其onReceive()方法,在该方法中响应事件。

一、自己定义Broadcast Receiver来处理广播事件

首先在你的程序组件里构建你要广播的Intent,使用sendBroadcast()方法发送出去,其次定义一个广播接收器,最后注册该广播接收器。我们可以在代码中注册,也可以在配置文件中注册。

/**
 * 发出广播
 */
public class CustomBroadcastActivity extends Activity {
	//定义一个Action常量
	private static final String MY_ACTION = "mx.android.ch08.MY_ACTION";
	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 arg0) {
				System.out.println("onClick...");
				//实例化Intent对象
				Intent intent = new Intent();
				//设置Intent action属性
				intent.setAction(MY_ACTION);
				//为Intent添加附加信息
				intent.putExtra("msg", "地瓜地瓜,我是土豆,收到请回复,收到请回复!");
				//发出广播
				sendBroadcast(intent);
			}
		});
    }
}
/**
 * 接收广播
 */
public class CustomBroadcast_ReceiverActivity extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		System.out.println("onReceive...");
		//从Intent中获取信息
		String msg = intent.getStringExtra("msg");
		//使用Toast显示
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}
}

在AndroidManifest.xml配置文件中声明广播接收器组件

<receiver android:name="CustomBroadcast_ReceiverActivity">
        <intent-filter>
            <action android:name="mx.android.ch08.MY_ACTION" />
        </intent-filter>
</receiver>

二、系统广播事件的使用

标准广播Actino常量

常量名称常量值意义
ACTION_BOOT_COMPLETEDandroid.intent.action.BOOT_COMPLETED系统自动完成
ACTION_TIME_CHANGEDandroid.intent.action.ACTION_TIME_CHANGED时间改变
ACTION_DATE_CHANGEDandroid.intent.action.ACTION_DATE_CHANGED日期改变
ACTION_TIMEZONE_CHANGEDandroid.intent.action.ACTION_TIMEZONE_CHANGED时区改变
ACTION_BATTERY_LOWandroid.intent.action.ACTION_BATTERY_LOW电量低
ACTINO_MEDIA_EJECTandroid.intent.action.ACTINO_MEDIA_EJECT插入或拔出外部媒体
ACTION_MEDIA_BUTTONandroid.intent.action.ACTION_MEDIA_BUTTON按下媒体按钮
ACTION_PACKAGE_ADDEDandroid.intent.action.ACTION_PACKAGE_ADDED添加包
ACTION_PACKAGE_REMOVEDandroid.intent.action.ACTION_PACKAGE_REMOVED删除包


下面实例我们通过接收系统启动完成广播来测试系统广播事件。这样我们不需要自己再定义发出广播的Intent,只需要定义接收器就可以了。

/**
 * 显示系统启动完成广播接收器
 */
public class SystemBroadcast extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		//显示广播信息
		Log.i("my_tag","BOOT_COMPLETED~~~~~~~~~");
		
		//实例化IntentFilter
		IntentFilter filter = new IntentFilter();
		SystemBroadcast r = new SystemBroadcast();
		//注册Receiver
		//registerReceiver(r,filter);
		//注销Receiver
		//unregisterReceiver(r);
	}
}

在AndroidManifest.xml配置文件中注册该接收器

<receiver android:name="SystemBroadcast">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

也可以通过代码的方式注册接收器。一般是在Activity.onResume()方法中使用Context.registerReceiver()方法来注册一个接收器,在Activity.onPause()方法中使用unregisterReceiver(r)方法来注销一个广播接收器。代码在上面类中注释掉的部分。

三、Notification和NotificationManager的使用

实现可视化的信息显示,通过它们可以显示广播信息的内容、图标以及震动等信息

1、简介

使用Notification和NotificationManager比较简单,一般获得系统级的服务NotificationManager,然后实例化Notification,设置其属性,通过NotificationManager发出通知就可以了。基本步骤说明如下:

1)、获得系统级的服务NotificationManager

2)、实例化Notification对象,并设置其属性

3)、调用setLatestEventInfo()方法在视图中设置图标和时间

4)、发出通知

public class NitificationActivity extends Activity {
	// 声明Button
	private Button sendBtn,calcelBtn;
	//声明Notification
	private Notification n;
	//声明NotificationManager
	private NotificationManager nm;
	//Notification坐标ID
	private static final int ID = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//实例化按钮
		sendBtn = (Button) findViewById(R.id.sendButton01);
		calcelBtn = (Button) findViewById(R.id.cancelButton02);
		//获得NotificationManager实例
		String service = NOTIFICATION_SERVICE;
		nm = (NotificationManager) getSystemService(service);
		//实例化Notification
		n = new Notification();
		//设置显示图标,该图标会在状态栏显示
		int icon = n.icon = R.drawable.ic_launcher;
		//设置提示信息,该信息也会在状态栏显示
		String tickerText = "Test Notification";
		//显示时间
		long when = System.currentTimeMillis();
		n.icon = icon;
		n.tickerText = tickerText;
		n.when = when;
		//为按钮添加监听器
		sendBtn.setOnClickListener(sendListener);
		calcelBtn.setOnClickListener(calcelListener);
	}
	
	//发送通知监听器
	private OnClickListener sendListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			//实例化Intent
			Intent intent = new Intent(NitificationActivity.this,NitificationActivity.class);
			//获得PendingIntent
			PendingIntent pi = PendingIntent.getActivity(NitificationActivity.this, 0, intent, 0);
			//设置事件信息
			n.setLatestEventInfo(NitificationActivity.this, "My Title", "My Content", pi);
			//发出通知
			nm.notify(ID, n);
		}
	};
	
	//取消通知监听器
	private OnClickListener calcelListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			nm.cancel(ID);
		}
	};
}

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:text="测试Notification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
    <Button 
        android:text="发出通知"
        android:id="@+id/sendButton01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button 
        android:text="取消通知"
        android:id="@+id/cancelButton02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

在上面的这个实例中,我们只使用Notification和MotificationManager来显示通知,下面我们写的另外一个实例是Notification、MotificationManager、Broadcast Receiver的一个综合实例。分别定义一个发出广播和接收广播的Activity,当接收到广播后,启动另一个DisplayActivity,在该类中通过Notification和MotificationManager来可视化显示广播通知。

/**
 * 测试广播和通知
 */
public class MainActivity extends Activity {
	private Button btn;
	//定义Broadcast Receiver action
	private static final String RECEIVER_ACTION = "mx.android.ch08.RECEIVER_ACTION";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btn = (Button) findViewById(R.id.zhButton01);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction(RECEIVER_ACTION);
				//发起广播
				sendBroadcast(intent);
			}
		});
	}
}

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >    
    <Button 
        android:id="@+id/zhButton01"
        android:text="发出广播"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
/**
 * 接收广播类
 */
public class MyReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Intent i = new Intent();
		//在新的任务中启动Activity
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//设置Intent启动的组件名称
		i.setClass(context, DisplayActivity.class);
		//启动Activity显示通知
		context.startActivity(i);
	}
}
/**
 * 显示通知
 */
public class DisplayActivity extends Activity {
	//实例化Button
	private Button myBtn;
	//声明Notification
	private Notification n;
	//声明NotificationManager
	private NotificationManager nm;
	//Notification标识ID
	private static final int ID = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display);
		myBtn = (Button) findViewById(R.id.zhCancelButton01);
		String service = NOTIFICATION_SERVICE;
		nm = (NotificationManager) getSystemService(service);
		n = new Notification();
		//设置显示图标
		int icon = n.icon = R.drawable.ic_launcher;
		//设置显示提示信息
		String tickerText = "Test Notification";
		//显示时间
		long when = System.currentTimeMillis();
		n.icon = icon;
		n.tickerText = tickerText;
		n.when = when;
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
		//设置事件信息
		n.setLatestEventInfo(this, "My Title", "My Content", pi);
		//发出通知
		nm.notify(ID, n);
		//取消通知监听器
		myBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				nm.cancel(ID);
			}
		});
	}
}

display.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >    
	<Button 
	    android:text="取消通知"
	    android:id="@+id/zhCancelButton01"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content" />    
</LinearLayout>

AndroidManifest.xml

添加:

	<activity android:name=".DisplayActivity" />
	<receiver android:name="MyReceiver">
	        <intent-filter>
	            <action android:name="mx.android.ch08.RECEIVER_ACTION" />
	        </intent-filter>
	</receiver>

正如我们上面看到的那样,可以为Notification对象设置图标、显示文字等信息。除了这些Notification,还有很多其他属性可以用来进行提示。例如,设置声音、震动和闪光灯等。设置方式如下:

提示音:

	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;

四、AlarmManager的使用

现在的手机普遍都会有一个闹钟的功能,如果使用Android实现一个脑子,可以使用AlarmManager来实现。AlarmManager提供了一种系统级的提示服务,允许你安排在未来的某个时间执行一个服务。AlarmManager对象一般不直接实例化,而是通过Context.getSystemService(Context.ALARM_SERVICE)方法获得。

AlarmManager常用属性和方法

属性或方法名称说明
ELAPSED_REALTIME设置闹钟时间,从系统启动开始
ELAPSED_REALTIME_WAKEUP设置闹钟时间,从系统启动开始,如果设备休眠则唤醒
INTERVAL_DAY设置闹钟时间,每隔一天
INTERVAL_FIFTEEN_MINUTES间隔15分钟
INTERVAL_HALF_DAY间隔半天
INTERVAL_HALF_HOUR间隔半小时
INTERVAL_HOUR间隔1小时
RTC设置闹钟时间,从系统当前时间开始(System.currentTimeMillis())
RTC_WAKEUP设置闹钟时间,从系统当前时间开始,设备休眠则唤醒
set(int type,long triggerAtTime,PendingIntent operation)设置在某个时间执行闹钟
setRepeating(int type,long triggerAtTime,long interval,PendingIntent operation)设置在某个时间重复执行闹钟
setInexactRepating(int type,long triggerAtTime,long interval,PendingIntent operation)设置在某个时间重复执行闹钟,但不是间隔固定时间


AlarmManager的使用步骤如下:

1)、获得AlarmManager实例

2)、闹钟一般是通过发出一个广播来实现的,所以要定义一个PendingIntent发出广播。

3)、调用AlarmManager的方法,设置定时或重复提醒。

下面实例中定义了一个Button,单击Button设置闹钟。定义一个Broadcast Receiver接收广播,并显示信息。

public class MainActivity2 extends Activity {
	private Button setBtn,calcelBtn;
	//定义广播ACtion
	private static final String BC_ACTION = "mx.android.ch08.BC_ACTION";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);
		setBtn = (Button) findViewById(R.id.setTimeButton01);
		calcelBtn = (Button) findViewById(R.id.calcelTimeButton02);
		//获得AlarmManager实例
		final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent();
		intent.setAction(BC_ACTION);
		intent.putExtra("msg","该开会啦~");
		//实例化PendingIntent
		final PendingIntent pi = PendingIntent.getBroadcast(MainActivity2.this, 0, intent, 0);
		//获得系统时间
		final long time = System.currentTimeMillis();
		//设置按钮单击事件
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//重复提示,从当前时间开始,间隔5秒
				am.setRepeating(AlarmManager.RTC_WAKEUP, time, 8*1000, pi);
			}
		});
		calcelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				am.cancel(pi);
			}
		});
	}
}

main2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >    
    <Button 
        android:id="@+id/setTimeButton01"
        android:text="设置闹钟"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />    
    <Button 
        android:id="@+id/calcelTimeButton02"
        android:text="取消闹钟"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
public class MyReceiver2 extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		//获得提示信息
		String msg = intent.getStringExtra("msg");
		//显示提示信息
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}
}

AndroidManifest.xml

添加:

	<receiver android:name="MyReceiver2">
	        <intent-filter>
	            <action android:name="mx.android.ch08.BC_ACTION" />
	        </intent-filter>
	</receiver>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值