其他分享
首页 > 其他分享> > 广播

广播

作者:互联网

广播类型:

广播机制:


一、本地广播:

广播定义:

public class Broadcaster {
private static Broadcaster sInstance;
private Context mContext;

private LocalBroadcastManager localBroadcastManager;

public static Broadcaster getInstance(Context context, BroadcastReceiver receiver) {
if (sInstance == null) {
sInstance = new Broadcaster(context.getApplicationContext(),receiver);
}
return sInstance;
}

private Broadcaster(Context context, BroadcastReceiver receiver) {
mContext = context;
setReceiver(receiver);
}

public void setReceiver(BroadcastReceiver receiver) {

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.bug01.Broadcast.AAA");
intentFilter.addAction("com.bug01.Broadcast.BBB");

//注册本地接收器
localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
localBroadcastManager.registerReceiver(receiver, intentFilter);
}

public void DoSomething() {
// 定义一个线程,模拟从其它地方发生了一个广告。
new Thread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent("com.bug01.Broadcast.AAA");
//发送本地广播
localBroadcastManager.sendBroadcast(intent);//发送无序广播
//localBroadcastManager.sendBroadcastSync(intent);//发送有序广播
}
}).start();
}

/**
* 注销时要同时注销接收器
*/
protected void onDestroy(BroadcastReceiver receiver) {
localBroadcastManager.unregisterReceiver(receiver);
}
}

接收器定义:

public class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到本地广播" + intent.getAction(), Toast.LENGTH_SHORT).show();
//abortBroadcast(); 取消广播向下传递
}
}

使用:



public class MainActivity extends AppCompatActivity {

Broadcaster mBroadcaster;
LocalReceiver mLocalReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mLocalReceiver = new LocalReceiver();

mBroadcaster = Broadcaster.getInstance(this, mLocalReceiver);
mBroadcaster.DoSomething();
}


@Override
protected void onDestroy() {
mBroadcaster.onDestroy(mLocalReceiver);
super.onDestroy();
}
}



二、全局广播

 

标签:void,广播,Broadcaster,receiver,new,public
来源: https://www.cnblogs.com/bug01/p/11246573.html