注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

民主与科学

独立之人格,自由之思想

 
 
 

日志

 
 

BroadcastReceiver(有序广播篇)  

2011-10-29 14:31:37|  分类: Android基础 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
BroadcastReceiver所对应的广播分两类:普通广播有序广播
普通广播通过Context.sendBroadcast()方法来发送。它是完全异步的。
所有的receivers接收器的执行顺序不确定。    因此,所有的receivers接收器接收broadcast的顺序不确定。
这种方式效率更高。但是BroadcastReceiver无法使用setResult系列getResult系列abort系列API
有序广播是通过Context.sendOrderedBroadcast来发送。所有的receiver依次执行。
BroadcastReceiver可以使用setResult系列函数结果传给下一个BroadcastReceiver,通过getResult系列函数来取得上个BroadcastReceiver返回的结果,并可以abort系列函数来让系统丢弃该广播让,使用该广播不再传送到别的BroadcastReceiver
可以通过在intent-filter中设置android:priority属性来设置receiver的优先级。优先级相同的receiver其执行顺序不确定。
如果BroadcastReceiver是代码中注册的话,且其intent-filter拥有相同android:priority属性的话,先注册的将先收到广播。
主要函数
Public Methods
final voidabortBroadcast()
Sets the flag indicating that this receiver should abort the current broadcast; only works with broadcasts sent throughContext.sendOrderedBroadcast.
final voidclearAbortBroadcast()
Clears the flag indicating that this receiver should abort the current broadcast.
final booleangetAbortBroadcast()
Returns the flag indicating whether or not this receiver should abort the current broadcast.
final booleangetDebugUnregister()
Return the last value given to setDebugUnregister(boolean).
final intgetResultCode()
Retrieve the current result code, as set by the previous receiver.
final StringgetResultData()
Retrieve the current result data, as set by the previous receiver.
final BundlegetResultExtras(boolean makeMap)
Retrieve the current result extra data, as set by the previous receiver.
final BroadcastReceiver.PendingResultgoAsync()
This can be called by an application in onReceive(Context, Intent) to allow it to keep the broadcast active after returning from that function.
final booleanisInitialStickyBroadcast()
Returns true if the receiver is currently processing the initial value of a sticky broadcast -- that is, the value that was last broadcast and is currently held in the sticky cache, so this is not directly the result of a broadcast right now.
final booleanisOrderedBroadcast()
Returns true if the receiver is currently processing an ordered broadcast.
abstract voidonReceive(Context context, Intent intent)
This method is called when the BroadcastReceiver is receiving an Intent broadcast.
IBinderpeekService(Context myContext, Intent service)
Provide a binder to an already-running service.
final voidsetDebugUnregister(boolean debug)
Control inclusion of debugging help for mismatched calls to {@ Context#registerReceiver(BroadcastReceiver, IntentFilter) Context.registerReceiver()}.
final voidsetOrderedHint(boolean isOrdered)
For internal use, sets the hint about whether this BroadcastReceiver is running in ordered mode.
final voidsetResult(int code, String data, Bundle extras)
Change all of the result data returned from this broadcasts; only works with broadcasts sent throughContext.sendOrderedBroadcast.
final voidsetResultCode(int code)
Change the current result code of this broadcast; only works with broadcasts sent throughContext.sendOrderedBroadcast.
final voidsetResultData(String data)
Change the current result data of this broadcast; only works with broadcasts sent throughContext.sendOrderedBroadcast.
final voidsetResultExtras(Bundle extras)
Change the current result extras of this broadcast; only works with broadcasts sent throughContext.sendOrderedBroadcast.
以下是一个关于有序广播的实例。
实例1:
MainActivity.java文件
package com.teleca.robin.BroadcastReceiverExample;

import com.teleca.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView tv=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main0);
        tv=(TextView)findViewById(R.id.TextView1);
        Button button = (Button) findViewById(R.id.Button1);
        
        OnClickListener listener = new OnClickListener() {
         public void onClick(View v) {
        sendBroadcast();
         }
        };
        button.setOnClickListener(listener);
    }
    protected void onResume()
    {
    super.onResume();
    registerMyReceivers();
    }
    protected void onStop()
    {
    unRegisterMyReceivers();
    super.onStop();
    }
    final static String ACTION_HELLO="com.teleca.robin.action.HELLO";
    final static String KEY_ORDER_DETAIL="orderDetail";
    void sendBroadcast()
    {
        Intent intent=new Intent(ACTION_HELLO);
        String receiverPermission=null;
        Handler scheduler=null;
        int initialCode=0;
        String initialData=null;
        Bundle initialExtras=new Bundle();
        sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, 
        initialCode, initialData, initialExtras);
    }
    BroadcastReceiver receiverArray[]=new MyBroadcastReceiver[50];
    void registerMyReceivers()
    {
    int k=receiverArray.length;

    int priority=IntentFilter.SYSTEM_LOW_PRIORITY;
    for(int i=0;i<k;i++)
    {
    receiverArray[i]=new MyBroadcastReceiver();
        IntentFilter filter=new IntentFilter(ACTION_HELLO);
        filter.setPriority(priority);
    registerReceiver(receiverArray[i], filter);
    if((i+1)%5==0)
    priority++;
    }
   
    }
    void unRegisterMyReceivers()
    {
    int k=receiverArray.length;
    for(int i=0;i<k;i++)
    {
    if(receiverArray[i]!=null)
    {
    unregisterReceiver(receiverArray[i]);
    receiverArray[i]=null;
    }
    }
    }
    final static String tag="robin";
    BroadcastReceiver resultReceiver=new BroadcastReceiver() {
    @Override
    public void onReceive(Context arg0, Intent intent) {
    // TODO Auto-generated method stub
    StringBuffer strBuffer=new StringBuffer();
    int count=getResultCode();
    strBuffer.append("there are "+count+" student\n");
    strBuffer.append("the older are :"+getResultData()+"\n");
    strBuffer.append("the detail older are :"+getResultExtras(true).getString(KEY_ORDER_DETAIL));
    tv.setText(strBuffer.toString());
    }

    };
}
MyBroadcastReceiver.java文件
package com.teleca.robin.BroadcastReceiverExample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

class MyBroadcastReceiver extends BroadcastReceiver {
static int SN=0;
int id=SN++;
final static String tag="robin";
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(MainActivity.ACTION_HELLO))
{
int count=getResultCode()+1;
setResultCode(count);
Log.i(tag,"this is student"+id);
String str=getResultData();
if(str==null)
str=""+id;
else
str=str+" "+id;
setResultData(str);
Bundle b=getResultExtras(true);
str=b.getString(MainActivity.KEY_ORDER_DETAIL);
if(str==null)
str=""+id;
else
str=str+"->"+id;
b.putString(MainActivity.KEY_ORDER_DETAIL, str);
Log.i(tag,"str:"+str);
setResultExtras(b);
}
}

}
main0.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"
    android:id="@+id/root"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="#FF0000FF"
    android:minHeight="50dip"
    android:text="@string/BroadcastReceiverExample"
    android:id="@+id/TextView1"
    />
<Button android:text="@string/pressme" 
android:id="@+id/Button1" 
android:layout_width="wrap_content" android:layout_height="wrap_content"
></Button>
</LinearLayout>
AndroidManifest.xml中
<activity android:name="com.teleca.robin.BroadcastReceiverExample.MainActivity"
  android:label="@string/app_name"
          >
             <intent-filter>
                <action android:name="com.teleca.robin.Hello" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
  评论这张
 
阅读(1602)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017