粘性广播接收器 - 它们是如何工作的?
广播接收器是否粘性或意图粘性? 据我所知 - “粘性意图是那些广播后坚持的意图,没有粘性广播接收器这样的东西,只有接收者可以听粘性意图。”粘性广播接收器 - 它们是如何工作的?
但是,我们如何让意图变得粘稠? 是sendStickyBroadcast(intentA)是使intentA粘性的唯一方法吗?如果是,如果我同时拨打sendStickyBroadcast(intentA)和sendBroadcast(intentA)会发生什么?意向A是否可用于未来的接收者?
我想测试此方案与logcat的,但我已经收到意想不到的日志:
public class MainActivity extends Activity {
private static final String CUSTOM_INTENT = "com.ashok.abacussb.my_intent";
Button button;
Receiver1 receiver1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBroadcast(new Intent(CUSTOM_INTENT));
Log.d("abd", "after sendBroadcast() "+ Thread.currentThread().getName());
receiver1 = new Receiver1();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("abd", "inside onClick()");
Intent intent = registerReceiver(receiver1, new IntentFilter(CUSTOM_INTENT));
Log.d("abd", (intent == null ? "null": ""+intent));
}
});
}
}
public class Receiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("abd", "inside Receiver1 onReceive() "+ Thread.currentThread().getName());
}
}
和日志:
09-21 16:26:43.845: D/abd(26620): after sendBroadcast() main
09-21 16:26:49.665: D/abd(26620): inside onClick()
09-21 16:26:49.685: D/abd(26620): Intent { act=com.ashok.abacussb.my_intent flg=0x10 }
09-21 16:26:49.770: D/abd(26620): inside Receiver1 onReceive() main
Receiver1注册按钮点击,这之后是明确sendBroadcast()被执行。为什么的onReceive()方法执行&通过registerReceiver()不返回NULL的意图,因为它不是一个sendStickyBroadcast()?
广播接收器是粘性还是意图粘性?
广播Intent
s可通过sendStickyBroadcast()
发送具有粘性,如果你持有发送这种广播适当的权限。
sendStickyBroadcast(intentA)是让intentA粘性的唯一方法吗?
是的。
如果是,如果我同时调用sendStickyBroadcast(intentA)和sendBroadcast(intentA)会发生什么?意向A是否可用于未来的接收者?
AFAIK,行为是无证的。我不会推荐使用这种模式。
为什么的onReceive()方法执行&通过registerReceiver()不返回NULL的意图,因为它不是一个sendStickyBroadcast()?
也许你以前发送过同样的动作字符串粘滞广播。重新启动您的设备或模拟器并再次尝试您的测试。