1. SendBroadcastActivity:

 1 package com.example.broadcastdemo;
 2 
 3 import android.app.Activity;
 4 import android.content.Intent;
 5 import android.content.IntentFilter;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.widget.EditText;
 9 
10 import androidx.annotation.Nullable;
11 
12 public class SendBroadcastActivity extends Activity{
13 
14     private EditText mEditSendInput;
15     private MessageReceiver mMessageReceiver;
16 
17     @Override
18     protected void onCreate(@Nullable Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_send);
21         initView();
22         registerBroadcastReceiver();
23     }
24 
25     private void initView() {
26         mEditSendInput = (EditText) this.findViewById(R.id.be_send_input_edit);
27     }
28 
29     /**
30      * 点击后发送广播,这个方法就会被调用
31      * @param view
32      */
33     public void sendBroadcastMessage(View view){
34         String content = mEditSendInput.getText().toString();
35         Intent intent = new Intent();
36         // 添加Action(只有一个
37         intent.setAction(Constants.ACTION_SEND_MSG);
38         // 通过键值对传值
39         intent.putExtra(Constants.KEY_CONTENT, content);
40         // 给特定的intent发送广播
41         sendBroadcast(intent);
42     }
43 
44     /**
45      * 注册动态广播
46      */
47     public void registerBroadcastReceiver(){
48         IntentFilter intentFilter = new IntentFilter();
49         intentFilter.addAction(Constants.ACTION_SEND_MSG);
50         mMessageReceiver = new MessageReceiver();
51         this.registerReceiver(mMessageReceiver, intentFilter);
52     }
53 
54     @Override
55     protected void onDestroy() {
56         super.onDestroy();
57         // 动态广播注册时要取消广播注册,否则会导致内存泄露
58         if (mMessageReceiver != null) {
59             this.unregisterReceiver(mMessageReceiver);
60         }
61     }
62 }

 

2. MessageReceiver:

 1 package com.example.broadcastdemo;
 2 
 3 import android.content.BroadcastReceiver;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 import android.util.Log;
 7 
 8 import java.security.acl.LastOwnerException;
 9 
10 public class MessageReceiver extends BroadcastReceiver {
11     private static final String TAG = "MessageReceiver";
12 
13     @Override
14     public void onReceive(Context context, Intent intent) {
15         String action = intent.getAction();
16         Log.d(TAG, "action is --" + action);
17         String content = intent.getStringExtra(Constants.KEY_CONTENT);
18         Log.d(TAG, "content is --" + content);
19     }
20 }

 

3. Constants:

1 package com.example.broadcastdemo;
2 
3 public class Constants {
4     // 定义action的名字
5     public static final String ACTION_SEND_MSG = "com.example.broadcastdemo.SEND_MSG";
6     public static final String KEY_CONTENT = "content";
7 }

 

posted on 2021-10-08 17:58  EndlessShw  阅读(233)  评论(0编辑  收藏  举报