Android广播的使用(一)
Android广播分为两个方面:广播发送者和广播接收者BroadcastReceiver。
BroadcastReceiver可以分为两种注册类型:静态注册和动态注册。
静态注册:直接在AndroidManifest.xml文件中进行注册。
动态注册:直接在代码中调用Context的registerReceiver函数。
动态注册:
Activity类代码:
public class MainActivity extends Activity { private static final String SERVICE_NAME = "com.seasy.android.MyRemoteService"; private static final String BROADCAST_ACTION = "com.seasy.android.MyBroadcastReceiver"; private MyBroadcastReceiver broadcastReceiver; private TextView txtMessage = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMessage = (TextView)findViewById(R.id.txtMessage); doRegisterReceiver(); //启动Service Intent serviceIntent = new Intent(MainActivity.this, MyRemoteService.class); startService(serviceIntent); } @Override protected void onDestroy() { super.onDestroy(); doUnregisterReceiver(); } /** * 注册广播接收者 */ private void doRegisterReceiver(){ broadcastReceiver = new MyBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(BROADCAST_ACTION); registerReceiver(broadcastReceiver, intentFilter); } /** * 注销广播接收者 */ private void doUnregisterReceiver(){ unregisterReceiver(broadcastReceiver); } public TextView getTxtMessage() { return txtMessage; } //广播接收器类:收到广播消息后,将消息显示在界面的文本框中 class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String messageData = intent.getStringExtra("messageData"); getTxtMessage().setText(messageData); } } }
Service类代码:
public class MyRemoteService extends Service { private static final String BROADCAST_ACTION = "com.seasy.android.MyBroadcastReceiver"; @Override public void onCreate() { super.onCreate(); sendBroadcastMessage("Start Thrift Server"); } @Override public IBinder onBind(Intent intent) { return null; } /** * 发送广播 */ private void sendBroadcastMessage(String messageData){ Intent intent = new Intent(); intent.setAction(BROADCAST_ACTION); intent.putExtra("messageData", messageData); sendBroadcast(intent); } }
在AndroidManifest.xml文件中添加如下配置信息:
<service android:name="com.seasy.android.MyRemoteService" android:exported="false"></service>
相关推荐
mingming 2015-01-13
chenjinlong 2020-04-06
xilove0 2020-01-14
magic00 2020-01-10
xilove0 2019-12-09
ThedakeLaugh 2010-08-23
fuzhangandroid 2011-04-07
老菜鸟自习室 2011-08-05
StarkHuang 2014-09-04
taiyuanwuyin 2015-03-31
易辰Android 2012-05-08
Alexlee 2018-04-20
OliverLau 2019-06-29
Alexlee 2018-04-20