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

Android BroadcastReceiver

时间:2015-07-26 17:10:09      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

 

1.BroadcastReceiver的作用

主要是用来监听系统或者应用发出的广播信息,然后根据广播信息做相应的逻辑处理。

2.BroadcastReceiver的用法

BroadcastReceiver在使用时,有两种注册方法:

(1)静态注册:在AndroidManifest.xml中通过<receiver>标签注册

(2)动态注册:通过Context.registerReceiver()方法注册

2.1小案例

在MainActivity中点击按钮发送带有特定内容的广播,当BroadcastReceiver接收到广播时将收到的内容显示出来。

2.2布局文件

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/sendBroadcast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送广播"/>

</LinearLayout>

BroadcastReceiver类

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String msg = intent.getStringExtra(Const.MESSAGE);
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }
}

Const.java

public class Const {
    public static final String MESSAGE = "message";
    public static final String ACTION = "com.study.broadcastreceiver";
}

2.2.1静态注册

1.AndroidManifest.xml中<application>标签下需添加如下内容:

<receiver
        android:name="receiver.MyReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.study.broadcastreceiver"/>        
        </intent-filter>
 </receiver>

其中"receiver"为MyReceiver所在的包,该Receiver只接收Intent Action为"com.study.broadcastreceiver"的广播。

2.MainActivity.java

public class MainActivity extends Activity {

    EditText message;
    Button sendBroadcast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        message = (EditText) findViewById(R.id.message);
        sendBroadcast = (Button) findViewById(R.id.sendBroadcast);

        sendBroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sendContent = message.getText().toString();
                Intent intent = new Intent();
                intent.putExtra(Const.MESSAGE,sendContent);
          intent.setAction(Const.ACTION); sendBroadcast(intent); } }); } }

点击"发送广播"按钮,MyReceiver收到广播后便以Toast方式显示收到的内容。

2.2.2动态注册

MainActivity.java

public class MainActivity extends Activity {

    EditText message;
    Button sendBroadcast;

    MyReceiver myReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        message = (EditText) findViewById(R.id.message);
        sendBroadcast = (Button) findViewById(R.id.sendBroadcast);

        //动态注册myReceiver
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(Const.ACTION);
        registerReceiver(myReceiver,intentFilter);

        sendBroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sendContent = message.getText().toString();
                Intent intent = new Intent();
                intent.putExtra(Const.MESSAGE,sendContent);
                intent.setAction(Const.ACTION);
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Activity销毁时,注销myReceiver
        unregisterReceiver(myReceiver);
    }
}

3.BroadcastReceiver类型

Broadcast的类型有两种:普通广播和有序广播。

(1)Normal broadcasts(普通广播):Normal broadcasts是完全异步的可以同一时间被所有的接收者接收到。消息的传递效率比较高。但缺点是接收者不能讲接收的消息的处理信息传递给下一个接收者也不能停止消息的传播。

(2)Ordered broadcasts(有序广播):Ordered broadcasts的接收者按照一定的优先级进行消息的接收。如:A,B,C的优先级依次降低,那么消息先传递给A,在传递给B,最后传递给C。优先级别声明在中,取值为[-1000,1000]数值越大优先级别越高。优先级也可通过filter.setPriority(10)方式设置。 另外Ordered broadcasts的接收者可以通过abortBroadcast()的方式取消广播的传播,也可以通过setResultData和setResultExtras方法将处理的结果存入到Broadcast中,传递给下一个接收者。然后,下一个接收者通过getResultData()和getResultExtras(true)接收高优先级的接收者存入的数据。

4.BroadcastReceiver接收机制及注意事项

当系统或应用发出广播时,将会扫描系统中的所有广播接收者,通过action匹配将广播发送给相应的接收者,接收者收到广播后将会产生一个广播接收者的实例,执行其中的onReceiver()这个方法。特别需要注意的是BroadcastReceiver的生命周期只有10秒左右,如果10秒内没执行结束onReceiver(),系统将会报错。

如果需要完成一项比较耗时的工作,应该通过发送 Intent 给 Service,由 Service 来完成(可以通过Intent启动Service来完成,但不能绑定Service)。这里不使用子线程来解决,因为 BroadcastReceiver 的生命周期很短,子线程可能还没有结束BroadcastReceiver就先结束了。BroadcastReceiver 一旦结束,此时 BroadcastReceiver 的所在进程很容易在系统需要内存时被优先杀死,因为它属于空进程 ( 没有任何活动组件的进程 )。如果它的宿主进程被杀死,那么正在工作的子线程也会被杀死。

http://developer.android.com/guide/components/processes-and-threads.html中有如下一段话:

Because a process running a service is ranked higher than a process with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply create a worker thread—particularly if the operation will likely outlast the activity. For example, an activity that‘s uploading a picture to a web site should start a service to perform the upload so that the upload can continue in the background even if the user leaves the activity. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. This is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread.

 

Android BroadcastReceiver

标签:

原文地址:http://www.cnblogs.com/ruyingxiangsui/p/4678025.html

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