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

民主与科学

独立之人格,自由之思想

 
 
 

日志

 
 

BroadcastReceiver  

2010-06-13 17:52:40|  分类: Android基础 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
BroadcastReceiver
java.lang.Object
        android.content.BroadcastReceiver
Base class for code that will receive intents sent by sendBroadcast(). 
You can either dynamically register an instance of this class with Context.registerReceiver()  
or statically publish an implementation through the <receiver>  tag in your AndroidManifest.xml. 
Note: If registering a receiver in your Activity.onResume()  implementation, you should unregister it in Activity.onPause(). 
(You won't receive intents when paused, and this will cut down on unnecessary system overhead). 
Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack. 

该类主要用来接收sendBroadcast()发出的intent。
可以通过在代码中用
Context.registerReceiver()的形式动态注册BroadcastReceiver。
也可以在AndroidManifest.xml中通过<receiver>来注册BroadcastReceiver。
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 through Context.sendOrderedBroadcast.
final voidsetResultCode(int code)
Change the current result code of this broadcast; only works with broadcasts sent through Context.sendOrderedBroadcast.
final voidsetResultData(String data)
Change the current result data of this broadcast; only works with broadcasts sent through Context.sendOrderedBroadcast.
final voidsetResultExtras(Bundle extras)
Change the current result extras of this broadcast; only works with broadcasts sent through Context.sendOrderedBroadcast.
广播主要有两大类:
Normal broadcasts(普通广播:It (sent with Context.sendBroadcast) are completely asynchronous. 
                            All receivers of the broadcast are run in an undefined order, often at the same time.
                            This is more efficient, but means that receivers cannot use the result or abort APIs included here.
该广播通过Context.sendBroadcast这种发送发送。它是完全异步的。
所有的receivers接收器的执行顺序不确定。    因此,所有的receivers接收器接收broadcast的顺序不确定。
这种方式效率更高。但是receivers接收器无法使用the result or abort APIs
Ordered broadcasts(有序广播):It (sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. 
                            As each receiver executes in turn, it can propagate a result to the next receiver, 
                            or it can completely abort the broadcast so that it won't be passed to other receivers. 
                            The order receivers run in can be controlled with the android:priority attribute 
                            of the matching intent-filter; 
                            receivers with the same priority will be run in an arbitrary order. 
该广播是通过Context.sendOrderedBroadcast来发送。所有的receiver依次执行。
receiver接收器可以把结果传给下一个receiver接收器。
receiver接收器也可从丢掉广播,使该广播不在传送给别的接收器。
可以通过在intent-filter中设置
android:priority属性来设置receiver的优先级。
优先级相同的receiver其执行顺序不确定。
注意1:虽然发送广播和Context.startActivity()都使用了Intent。但是他们的机制是完全不一样的。
注意2:只有Ordered broadcasts(有序广播)才能把结果传给下一个receiver接收器。
        才能使用abortBroadcast()丢掉广播
Context

public abstract void sendStickyBroadcast (Intent intent)

Since: API Level 1

Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission, SecurityException will be thrown.

Parameters
intentThe Intent to broadcast; all receivers matching this Intent will receive the broadcast, and the Intent will be held to be re-broadcast to future receivers.

public abstract void sendStickyOrderedBroadcast (Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Since: API Level 5

Version of sendStickyBroadcast(Intent) that allows you to receive data back from the broadcast. This is accomplished by supplying your own BroadcastReceiver when calling, which will be treated as a final receiver at the end of the broadcast -- its onReceive(Context, Intent) method will be called with the result values collected from the other receivers. The broadcast will be serialized in the same way as calling sendOrderedBroadcast(Intent, String).

Like sendBroadcast(Intent), this method is asynchronous; it will return before resultReceiver.onReceive() is called. Note that the sticky data stored is only the data you initially supply to the broadcast, not the result of any changes made by the receivers.

See BroadcastReceiver for more information on Intent broadcasts.

Parameters
intentThe Intent to broadcast; all receivers matching this Intent will receive the broadcast.
resultReceiverYour own BroadcastReceiver to treat as the final receiver of the broadcast.
schedulerA custom Handler with which to schedule the resultReceiver callback; if null it will be scheduled in the Context's main thread.
initialCodeAn initial value for the result code. Often Activity.RESULT_OK.
initialDataAn initial value for the result data. Often null.
initialExtrasAn initial value for the result extras. Often null.
BroadcastReceiver的生命周期
    BroadcastReceiver的生命周期非常短暂的,而且是消息一到达则创建执行完毕就立刻销毁的.
    当函数onReceive(Context, Intent)返回后系统就认为该对象已经被完成,不会在使用它了,系统立刻销毁该对象。
    因此它的生命周期很短,不易做太多的事情,也不要做任何异步操作。
    对于耗时的事情通常放在Service来处理,在BroadcastReceiver调用Context.startService()启动一个服务来处理耗时的工作。
注意1:BroadcastReceiver是在intent匹配后再实例化,而且每次都是重新实例化的。
注意2:因为onReceive是运行在the main thread of its process,所有如果该函数的运行时间超过了10秒,
系统就会认为该程序没响应,会弹出杀死该程序的选择框。
注意3:程序中手动注册的BroadcastReceiver,并不会重新实例化的。具体见实例1
Permissions
如果在发送广播的时候权限项非null,那么接收接收广播的应用程序必须要有相对应的权限。
可以自定义Permissions,但是Permissions首先要在AndroidManifest.xml中进行申明

示例1:
    Intent intent=new Intent("com.teleca.action.HELLO");
    sendBroadcast(intent);

AndroidManifest.xml文件
    <receiver android:name="MyReceiver">
                <intent-filter>
                
<action android:name="com.teleca.action.HELLO"/>
            </intent-filter>
    </receiver>
BroadcastReceiver代码    
public class MyReceiver extends BroadcastReceiver {
    final static String ACTION_HELLO="com.teleca.action.HELLO";
    final static String tag="hubin";
    public void onReceive(Context context, Intent intent)
    {
        if(intent.getAction().equals(ACTION_HELLO))
        {
            Log.i(tag,"hello,robin");
        }
    }
}
示例2:
String action="com.teleca.action.HELLO";
String permission="com.teleca.permission.ACCESS";
Intent intent=new Intent(action);
sendBroadcast(intent,permission);

BroadcastReceiver代码和例1相同.
AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.teleca"
      android:versionCode="1"
      android:versionName="1.0">
        <permission android:name="com.teleca.permission.ACCESS"
        android:label="@string/MyPermission"
        android:description="@string/MyPermission"
        android:protectionLevel="dangerous" />

        <!--这里申明权限-->
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Hello"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Hello2"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="com.teleca.action.MAIN"/>
                <category android:name="com.teleca.category.DEFAULT" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.item/vnd.google.note" android:scheme="weather" android:host="com.msi.manning"/>
            </intent-filter>
        </activity>
    <receiver android:name="MyReceiver">
                <intent-filter>
                <action android:name="com.teleca.action.HELLO"/>
            </intent-filter>

    </receiver>
</application>
    <uses-sdk android:minSdkVersion="7" />

<uses-permission android:name="com.teleca.permission.ACCESS"></uses-permission>
<!--这里使用申明的权限-->
</manifest> 
实例1
package com.teleca;
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.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class Hello extends Activity {
 String tag="hubin";
    /** Called when the activity is first created. */
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.Button01);
        OnClickListener listener = new OnClickListener() {
         public void onClick(View v) {
          Intent intent =new Intent(Hello.this,Hello2.class);
         startActivity(intent);
         finish();//@2
         }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction("Hello");
        this.registerReceiver(receiver, filter);

        Log.i(tag,"create one1");
        ;
    }
    protected void onDestroy()
    {
     super.onDestroy();
     Log.i(tag,"one Destroy");
    }
    public BroadcastReceiver receiver = new BroadcastReceiver() {
 
 public void onReceive(Context context, Intent intent) {
   Log.i(tag,"receiver:"+this);//@1
   }
 };

}
文件2:Hello2.java
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Hello2 extends Activity {
 String tag="hubin";
    /** Called when the activity is first created. */
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        Button button = (Button) findViewById(R.id.Button01);
        OnClickListener listener = new OnClickListener() {
         public void onClick(View v) {
          Intent intent=new Intent("Hello");
          sendBroadcast(intent);

         }
        };
        button.setOnClickListener(listener);
    }
}
注意1:程序中手动注册的BroadcastReceiver,并不会重新实例化的。这点和AndroidManifest.xml不一样
注意2:它的存活时间是要一直到Activity死亡。如果调用了finish(),该Activity就死亡,receiver也同时死亡掉。
  评论这张
 
阅读(2818)| 评论(0)
推荐 转载

历史上的今天

评论

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

页脚

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