静态注册广播:在清单文件里注册(不好用,接收方没有打印出LOG → 清单文件中的代码不好用)
*动态注册广播:在java里注册
step1 工具类,定义flag
step2 创建一个接收者
CustomReceiver 继承 BroadcastReceiver,重写onReceive方法
step3 xml 定义点击事件
step4 MainActivity里
1 动态注册
//java代码来注册动态接收者
//new一个自定义的接收者
CustomReceiver customReceiver = new CustomReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ActionUtils.DONG_ACTION_FLAG);
registerReceiver(customReceiver,filter);
2 点击事件:
Intent intent = new Intent();
// 参数是静态的flag (注册清单文件里的 action的name)
intent.setAction(ActionUtils.JING_ACTION_FLAG);
//发送广播
sendBroadcast(intent);
step1 工具类,定义flag
//动态接收者flag
String DONG_ACTION_FLAG ="com.cs.dong";
step2 创建一个接收者
CustomReceiver.java
package com.example.myactivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
//接收者
public class CustomReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("cs","动态接收到了");
}
}
step3 xml 定义点击事件
android:onClick="sendDongAction"
step4 MainActivity里
package com.example.myactivity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
public class MainActivity4 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//java代码来注册动态接收者
//new一个自定义的接收者
CustomReceiver customReceiver = new CustomReceiver();
IntentFilter filter = new IntentFilter();
//参数是动态的flag
filter.addAction(ActionUtils.DONG_ACTION_FLAG);
registerReceiver(customReceiver,filter);
}
//点击事件,动态发送广播 给接收者
public void sendDongAction(View view) {
Intent intent = new Intent();
// 参数是动态的flag
intent.setAction(ActionUtils.DONG_ACTION_FLAG);
//发送广播
sendBroadcast(intent);
}
}
效果
注意log打不出来的时候改下这里
静态注册步骤:(虽然不好用也记录一下)
1 工具类,定义flag
1 创建一个接收者
CustomReceiver 继承 BroadcastReceiver,重写onReceive方法
2 在清单文件中注册静态接收者(action的name 是 静态接收者的flag)
3 xml
4 MainActivity里点击事件:
Intent intent = new Intent();
// 参数是静态的flag (注册清单文件里的 action的name)
intent.setAction(ActionUtils.JING_ACTION_FLAG);
//发送广播
sendBroadcast(intent);



