Android-广播的两种注册方式
概述本文介绍两种注册方式的广播:动态注册( JAVA代码)、静态( 在清单文件AndroidManifest.xml 中注册) 动态注册广播接收器达到的效果:在 app 的 MainActivity 中发送广播消息的按钮点击后给出下面几个反馈: 向 MainActivity 中的 EditText 中写入文字弹出 Toast打印 Logcat创建项目的操作就略过了,下面开始每个模块的制作以及代码: 制作 MainActivity 的布局文件 acitvity_main,其完整代码如下: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_gravity="center_horizontal" android:text="Received Broadcasts" /> <Button android:id="@+id/btnSendBroadcast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_gravity="center_horizontal" android:text="Send Broadcast"/> <EditText android:id="@+id/etReceivedBroadcast" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>制作 MainActivity ,其完整代码如下: package com.ccsoft.broadcastdemo;import android.app.Activity;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;public class MainActivity extends Activity implements View.OnClickListener { MyReceiver myReceiver; IntentFilter intentFilter; EditText etReceivedBroadcast; Button btnSendBroadcast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activit_main); etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast); btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast); //keep reference to Activity context MyApplication myApplication = (MyApplication) this.getApplicationContext(); myApplication.mainActivity = this; btnSendBroadcast.setOnClickListener(this); myReceiver = new MyReceiver(); intentFilter = new IntentFilter("chanchawReceiver"); } @Override protected void onResume() { super.onResume(); registerReceiver(myReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(myReceiver); } @Override public void onClick(View view) { Intent intent = new Intent("chanchawReceiver"); sendBroadcast(intent); }}上面步骤贴到项目中后会有些类、对象不存在造成报错,先别着急,布置完全部代码后即可正常运行。步骤2中用到的 MyApplication 的完整代码如下 ...