Android四大组件之BroadCastReceiver

来源:互联网 发布:手机连接电脑网络共享 编辑:程序博客网 时间:2024/05/18 01:54

1.MainActivity:主界面-发送广播

//广播就是一个观察者模式  你不知道发送完广播之后对方会有什么样的操作public class MainActivity extends AppCompatActivity implements View.OnClickListener {    public static final String TAG = "info";    //UI控件    private Button btn_common;    private Button btn_orderedBC;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        initEvent();        initReceiver();    }    /**     * 初始化广播之本地广播     */    private void initReceiver() {        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);        manager.registerReceiver(new MyBroadCastReceiver(), new IntentFilter("com.ruru.aaa"));        Intent intent = new Intent();        intent.setAction("com.ruru.aaa");        manager.sendBroadcast(intent);    }    /**     * 点击事件     */    private void initEvent() {        btn_common.setOnClickListener(this);        btn_orderedBC.setOnClickListener(this);    }    /**     * 初始化控件     */    private void initView() {        btn_common = (Button) findViewById(R.id.btn_common);        btn_orderedBC = (Button) findViewById(R.id.btn_orderedBC);    }    /**     * 控件的点击事件     */    @Override    public void onClick(View view) {        switch (view.getId()) {            case R.id.btn_common:                sendCommonBC();                break;            case R.id.btn_orderedBC:                sendOrderedBC();                break;            default:                break;        }    }    /**     * 发送有序广播     */    private void sendOrderedBC() {        //静态注册        Intent intent = new Intent();        intent.setAction("com.ruru.bbb");//        sendOrderedBroadcast(intent,null);        //终结广播  不管广播会不会被拦截都要执行        sendOrderedBroadcast(intent, null, new PiorityBroadCastReceiver.LowReceiver(), new Handler(), 0, null, null);    }    /**     * 发送普通广播     */    private void sendCommonBC() {        //动态注册广播 对应反注册广播//        registerReceiver(new MyBroadCastReceiver(), new IntentFilter("com.ruru.aaa"));//接收广播要判断发送的广播和接收的广播是否一致        //发送广播        Intent intent = new Intent();        intent.setAction("com.ruru.aaa");        sendBroadcast(intent);    }    /**     * 接收广播 实现onReceive方法  要写成公共的方法  否则静态注册会报红线     * 要写成静态的  否则会报没有MyBroadCaseReceiver     * 静态内部类     */    public static class MyBroadCastReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Log.i(TAG, "onReceive: 接收到广播啦");            Toast.makeText(context, "接收到广播啦", Toast.LENGTH_SHORT).show();        }    }    /**     * 反注册广播     *///    @Override//    public void unregisterReceiver(BroadcastReceiver receiver) {//        super.unregisterReceiver(receiver);//    }}
2.PiorityBroadCastReceiver:有序广播接收者

public class PiorityBroadCastReceiver {    private static final String TAG = "info";    public static class HighReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Log.i(TAG, "onReceive: high");            abortBroadcast();//有序广播可以用来拦截广播            //传递结果到下一个广播接收器            int code = 0;            String data = "hello";            Bundle bundle = null;            setResult(code, data, bundle);        }    }    public static class MidReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Log.i(TAG, "onReceive: mid");            //获取上一个广播接收器结果            int resultCode = getResultCode();            String resultData = getResultData();            Log.i(TAG, "onReceive: 获取到上一个广播接收器结果===" + resultCode + "  " + resultData);            Bundle bundle = null;            setResult(resultCode, resultData, bundle);        }    }    public static class LowReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Log.i(TAG, "onReceive: low");            int resultCode = getResultCode();            String resultData = getResultData();            Log.i(TAG, "onReceive: 从第二个广播接收到的结果===" + resultCode + "  " + resultData);        }    }}
3.LaunchReceiver:开机自启动广播

/** * 开机的时候收到的广播 * 静态注册此广播 */public class LaunchReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        //启动指定service        Intent intent1 = new Intent(context, LaunchService.class);        context.startService(intent1);    }}
4.LaunchService:开机自启动开启的服务

/** * 开启服务:让LaunchReceiver监听系统开机发出的广播 */public class LaunchService extends Service {    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    /**     * 开机时就会启动这个服务,其间隔1秒就会打印一行日志     */    @Override    public void onCreate() {        super.onCreate();        Timer timer = new Timer();        timer.schedule(new TimerTask() {            @Override            public void run() {                Log.i(TAG, "run: " + new Date());            }        }, 0, 1000);    }}
5.AndroidMenifest.xml:系统开机事件的权限和四大组件的注册

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.ruru.broadcastreceiver">    <!--系统开机事件的权限-->    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name=".MainActivity$MyBroadCastReceiver">            <intent-filter>                <action android:name="com.ruru.aaa"></action>            </intent-filter>        </receiver>        <receiver android:name=".PiorityBroadCastReceiver$HighReceiver">            <intent-filter android:priority="3000">                <action android:name="com.ruru.bbb"></action>            </intent-filter>        </receiver>        <receiver android:name=".PiorityBroadCastReceiver$MidReceiver">            <intent-filter android:priority="2000">                <action android:name="com.ruru.bbb"></action>            </intent-filter>        </receiver>        <receiver android:name=".PiorityBroadCastReceiver$LowReceiver">            <intent-filter android:priority="1000">                <action android:name="com.ruru.bbb"></action>            </intent-filter>        </receiver>        <receiver android:name=".LaunchReceiver">            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED"></action>            </intent-filter>        </receiver>    </application></manifest>
6.布局:activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.ruru.broadcastreceiver.MainActivity">    <Button        android:id="@+id/btn_common"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="普通广播" />    <Button        android:id="@+id/btn_orderedBC"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="有序广播" /></LinearLayout>
7.精彩链接:鸿洋大神总结的:

 Android 广播相关的都在这儿

8.知识点总结:

  广播分为六大类:普通广播    有序广播(优先级)    拦截广播(有序广播里可以拦截 还有终结广播)

                             本地广播(非全局的,保证应用安全和系统开销,和生命周期保持一致,只有该应用程序可以收到广播)

                             系统广播:结合service使用

                             sticky广播:淘汰

9.系统广播和service的结合使用:开机自启动例子

BootBroadCastReceiver:

public class BootBroadCastReceiver extends BroadcastReceiver {    static final String ACTION = "android.intent.action.BOOT_COMPLETED";    @Override    public void onReceive(Context context, Intent intent) {        // 当收听到的事件是“BOOT_COMPLETED”时,就创建并启动相应的Activity和Service        if (intent.getAction().equals(ACTION)) {            // 开机启动的Activity            Intent activityIntent = new Intent(context, BootActivity.class);            activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            // 启动Activity            context.startActivity(activityIntent);            // 开机启动的Service            Intent serviceIntent = new Intent(context, BootService.class);            // 启动Service            context.startService(serviceIntent);        }    }}
BootActivity:

public class BootActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_boot);        // 设置Activity的显示内容为一个文本域        TextView aTextView = new TextView(this);        aTextView.setText("Wow!I started after cellphone boot.");        setContentView(aTextView);    }}
BootService:

public class BootService extends Service{    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();        // Service被启动时,将会有弹出消息提示[MyService onStart]        Toast.makeText(this, "[MyService onStart]", Toast.LENGTH_LONG).show();    }}
安装程序,重启app会打印activity和service当中的内容。



  






0 0