码迷,mamicode.com
首页 > 移动开发 > 详细

android开发 关于BroadCast Receiver

时间:2014-12-19 15:48:38      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:android   broadcastreceiver   broadcast   



BroadCast Receiver是android常用的技术之一

用于发送/广播Intent消息

下面就介绍两种简单的使用方法


一. 通过组合的方式

在类中定义一个BroadcastReceiver对象

重写onReceive 这样就能接收到广播

这个可以放到一般的Activity类中


首先注册IntentFilter 指定要接收的消息

 //注册一个IntentFilter
        IntentFilter intentFilter =  new IntentFilter( "PlayHandler.Broadcast" ); 
        registerReceiver( myBroadcastReceiver, intentFilter); 

然后定义BroadcastReceiver对象 接收消息

private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() { 

        @Override 
        public   void   onReceive(Context context, Intent intent) { 
        	//接收广播
    		// 注意 这里是主线程上 
    		System.out.println(" thread id :"+Thread.currentThread().getId());
        	System.out.println("PlayHandler.Broadcast onReceived!!" ); 
       } 

    }; 

这样一个接收消息处理的对象就完成了

下面来发送一条消息


//使用sendBroadcast 发送广播
    		Intent intent = new Intent( "PlayHandler.Broadcast" ); 
    		sendBroadcast(intent); 
    		System.out.println("PlayHandler.Broadcast" ); 

二. 注册XML

和前面一种方法不同的是 这里使用Manifest来注册了receiver

需要继承BroadcastReceiver类


首先在Manifest中注册

<receiver 
		    android:exported="false"
		    android:name="com.example.codetest_1.PlayBroadcastReceiver" >  
			<intent-filter>     
				<action android:name = "PlayBroadcastReceiver.Broadcast" />  
			</intent-filter> 
		</receiver>


声明一个BroadcastReceiver派生类

public class PlayBroadcastReceiver extends BroadcastReceiver {
	public static final String BROADCAST_ACTION  =  "PlayBroadcastReceiver.Broadcast" ; 
	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		System.out.println("PlayBroadcastReceiver.Broadcast onReceived!!" ); 
	}

}

消息的发送和第一种方法一样

intent = new Intent();
        	intent.setAction(PlayBroadcastReceiver.BROADCAST_ACTION);
    		sendBroadcast(intent); 
    		System.out.println("PlayBroadcastReceiver.Broadcast send");



android开发 关于BroadCast Receiver

标签:android   broadcastreceiver   broadcast   

原文地址:http://blog.csdn.net/zzzzyu/article/details/42028581

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!