Android开发学习之路--Broadcast Receiver初体验

Posted 东月之神

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发学习之路--Broadcast Receiver初体验相关的知识,希望对你有一定的参考价值。

    学习了Activity组件后,这里再学习下另一个组件Broadcast Receiver组件。这里学习下自定义的Broadcast Receiver。通过按键自己发送广播,然后自己接收广播。新建MyBroadcastReceiver,代码如下:

package com.example.jared.broadcasttest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by jared on 16/2/12.
 */
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Received from MyBroadcastReceiver",
                Toast.LENGTH_LONG).show();
    }
}

    然后在AndroidManifest中添加receiver标签:

 <receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>
     这里定义了消息为com.example.broadcasttest.MY_BROADCAST的广播。

     修改activity_main.xml如下,添加一个button控件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.jared.broadcasttest.MainActivity">

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send myBroadcast"
        android:textAllCaps="false"/>

</RelativeLayout>

    然后修改MainActivity,添加如下:

        send = (Button)findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
    这里用到了Intent,当按下按钮的时候,就会sendBroadcast一条名为com.example.broadcasttest.MY_BROADCAST的广播。

    接着运行看下效果:

技术分享

    其实广播是跨进程的,不同进程间也就是不同的app之间是可以互相传递的。这里我们已经安装好了这个Broadcasttest的app,下面再新建一个app,用来接收这条消息。新建BroadcastTest2。

       然后添加OtherBroadcastReceiver,代码如下:

package com.example.jared.broadcasttest2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by jared on 16/2/12.
 */
public class OtherBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "receive by OtherBroadcastReceiver!",
                Toast.LENGTH_LONG).show();
    }
}
    添加AndroidManifest代码如下:

  <receiver android:name=".OtherBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>

    然后运行代码,按home键退到后台,接着运行上面已经安装好的app,然后运行,效果如下:

技术分享      技术分享

    可以看到两条广播都收到了。而发送的就一次。接着我们来学习下广播接收的优先级,这里只需要修改两个地方,一个是发送的函数,sendBroadcast函数替换成sendOrderedBroadcast,然后在AndroidManifest中添加android:priority属性。然后可以通过abortBroadcast方法将广播截断。还是看下例子吧。

    修改BroadcastTest工程的代码,如下:

send = (Button)findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendOrderedBroadcast(intent, null);
            }
        });

    修改接收到的广播后截断广播,代码如下:

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Received from MyBroadcastReceiver",
                Toast.LENGTH_LONG).show();
        abortBroadcast();
    }
}

修改AndroidManifest添加优先级:

        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter android:priority="100">
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>

    然后运行查看效果,只有当前的这个app收到广播,而另一个app没有收到任何广播。也达到了我们的期望。

    接下去学习下本地的广播,所谓本地,就是只有当前的app可以收到广播,其他的app是收不到这个广播的。 新建LocalBroadcast工程,编写代码如下:

package com.example.jared.localbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private Button send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.localbroadcast.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager = localBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);

        send = (Button)findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.localbroadcast.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "LocalReciver received ", Toast.LENGTH_LONG).show();
        }
    }
}

    这里注册了一个LocalBroadcastManager,名字为com.example.localbroadcast.LOCAL_BROADCAST。通过intentfilter动态注册。内部类LocalReceiver继承BroadcastReceiver,并重写了onReceive方法,在该方法中通过Toast消息反馈下收到广播的提醒。

    运行效果如下:

技术分享

    关于Broadcast Receiver就基本学习到这里了,先学习基础,以后再深入学习。

    明天就上班了,还好过年也学习了一些知识,得加快学完第一行代码,然后继续深入学习,早日可以胜任android开发的工作,早日去做自己想做的事情。


附:参考《第一行代码》













以上是关于Android开发学习之路--Broadcast Receiver初体验的主要内容,如果未能解决你的问题,请参考以下文章

android framework开发之广播broadcast源码分析-千里马

Spark学习之路 SparkCore的调优之开发调优

Android学习总结——Broadcast

Android开发学习之路--UI之基本布局

Android开发学习之路--RxAndroid之初体验

Android开发学习之路--UI之ListView