Android开发BroadCastReceiver

释放双眼,带上耳机,听听看~!

静态注册广播

manifest

<!--自定义广播-->
<receiver
android:name=".BroadCastReceiver.MyCostomBroadRecyiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="mybroadcast" />
</intent-filter>
</receiver>

receiver

public class MyCostomBroadRecyiver extends BroadcastReceiver {
String TAG = MyCostomBroadRecyiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();
Log.e("DY" + TAG, "====收到自定义广播===");
}
}
    /**
* 发送自定义广播
*/
private void sendCostomBroadCast() {
Log.e(TAG, "===发送自定义广播===");
Intent intent = new Intent("mybroadcast");
//        8.0对广播做了限制  必须加下面一行代码  ComponentName ()第一参数为包名  第二为自定义广播的全路径
intent.setComponent(new ComponentName(getPackageName(),"com.first.code.BroadCastReceiver.MyCostomBroadRecyiver"));
sendBroadcast(intent);
}

本地广播(安全只有应用内可以使用)

implementation "com.android.support:support-v4"
private LocalBroadcastManager localBroadcastManager;
private IntentFilter localIntentFilter;
private LocalBroadcastReceive localBroadcastReceive;
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localIntentFilter = new IntentFilter();
localIntentFilter.addAction("local.broadcast");
localBroadcastReceive = new LocalBroadcastReceive();
localBroadcastManager.registerReceiver(localBroadcastReceive, localIntentFilter);//注册本地监听广播
/**
* LocalBroadcast
*/
private void sendLocalBroadcast() {
Intent intent = new Intent("local.broadcast");
localBroadcastManager.sendBroadcast(intent);
}

receiver

class LocalBroadcastReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到本地广播", Toast.LENGTH_SHORT).show();
}
}

人已赞赏
Android文章

Android 程序睡眠

2020-3-24 10:49:32

Android文章

Android开发service download manager

2020-3-24 11:22:23

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索