sendStickyBroadcast函数的使用
比如有这种情况,ActivityA发送广播到ActivityB,但BroadcastReceiver是在ActivityB中用代码进行注册的,ActivityA发送出去的广播ActivityB是接收不到的,如果遇到这种情况该怎么办呢?使用sendStickyBroadcast方法就解决了。
新建名称为test的Android项目,Main.java的核心代码如下:
- public class Main extends Activity {
- private Button button1;
- private Button button2;
- private int count = 0;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 添加android.permission.BROADCAST_STICKY权限
- button1 = (Button) this.findViewById(R.id.button1);
- button1.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- count++;
- Intent intent = new Intent("sendMyBroadcastReceiver");
- intent.putExtra("username", "username" + count);
- Main.this.sendStickyBroadcast(intent);
- }
- });
- button2 = (Button) this.findViewById(R.id.button2);
- button2.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- Intent intent = new Intent(Main.this, Second.class);
- Main.this.startActivity(intent);
- }
- });
- }
- }
文件Second.java的核心代码如下:
- class MyBroadcastReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context arg0, Intent arg1) {
- Log.v("!", "usernameusername=" + arg1.getStringExtra("username"));
- }
- }
- public class Second extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- IntentFilter filter = new IntentFilter();
- filter.addAction("sendMyBroadcastReceiver");
- MyBroadcastReceiver myBroadcastReceiverRef = new MyBroadcastReceiver();
- this.registerReceiver(myBroadcastReceiverRef, filter);
- }
- }
在AndroidManifest.xml文件中添加权限代码:
- <uses-permission android:name="android.permission.BROADCAST_STICKY"></uses-permission>
程序运行后单击两次"单击我2次发送2次sendStickyBroadcast广播"按钮。
这时再单击"到Second.java"按钮,在LogCat控制台打印出最后一次Intent中的数据。
![]() |
图6.2 单击2次上面的按钮 |
![]() |
图6.3 打印最后1次Intent中的数据 |
转载于:https://blog.51cto.com/whatandroid/1092851