BroadcastReceiver

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 void abortBroadcast()
Sets the flag indicating that this receiver should abort the current broadcast; only works with broadcasts sent through Context.sendOrderedBroadcast.
final void clearAbortBroadcast()
Clears the flag indicating that this receiver should abort the current broadcast.
final boolean getAbortBroadcast()
Returns the flag indicating whether or not this receiver should abort the current broadcast.
final boolean getDebugUnregister()
Return the last value given to  setDebugUnregister(boolean).
final int getResultCode()
Retrieve the current result code, as set by the previous receiver.
final  String getResultData()
Retrieve the current result data, as set by the previous receiver.
final  Bundle getResultExtras(boolean makeMap)
Retrieve the current result extra data, as set by the previous receiver.
final  BroadcastReceiver.PendingResult goAsync()
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 boolean isInitialStickyBroadcast()
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 boolean isOrderedBroadcast()
Returns true if the receiver is currently processing an ordered broadcast.
abstract void onReceive( Context context,  Intent intent)
This method is called when the BroadcastReceiver is receiving an Intent broadcast.
IBinder peekService( Context myContext,  Intent service)
Provide a binder to an already-running service.
final void setDebugUnregister(boolean debug)
Control inclusion of debugging help for mismatched calls to {@ Context#registerReceiver(BroadcastReceiver, IntentFilter) Context.registerReceiver()}.
final void setOrderedHint(boolean isOrdered)
For internal use, sets the hint about whether this BroadcastReceiver is running in ordered mode.
final void setResult(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 void setResultCode(int code)
Change the current result code of this broadcast; only works with broadcasts sent through  Context.sendOrderedBroadcast.
final void setResultData( String data)
Change the current result data of this broadcast; only works with broadcasts sent through  Context.sendOrderedBroadcast.
final void setResultExtras( Bundle extras)
Change the current result extras of this broadcast; only works with broadcasts sent through  Context.sendOrderedBroadcast.
BroadcastReceiver主要有两大类:
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()丢掉广播
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也同时死亡掉。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值