• android简单的广播发送与接收


    发送端:

     public class MainActivity extends Activity { //先在布局文件main.xml中定义一个Button
    /*
      *
      * <Button
      *  android:layout_width="fill_parent"
      *  android:layout_height="wrap_content"
      *  android:text="@string/button_send"
      *  android:id="@+id/send_broadcast_button"
      *  />
      *
      */


    private Button send_broadcast_button; @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            send_broadcast_button = (Button) this.findViewById(R.id.send_broadcast_button);
            send_broadcast_button.setOnClickListener(new SendBroadcast());
        }
    private class SendBroadcast implements View.OnClickListener {  @Override
      public void onClick(View v) {
       
       Intent intent = new Intent();
       intent.setAction("cn.abel.action.broadcast");
       
       //要发送的内容
       intent.putExtra("author", "Abel");
       
       //发送 一个无序广播
       MainActivity.this.sendBroadcast(intent);
      }
      
    }
    }

    接收端:

    public class MainActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("cn.abel.action.broadcast");
            this.registerReceiver(new MyBroadcastReciver(), intentFilter);
        }
        private class MyBroadcastReciver extends BroadcastReceiver {  @Override
      public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();
       if(action.equals("cn.abel.action.broadcast")) {
        String author = intent.getStringExtra("author");
       
        //在控制台显示接收到的广播内容
        System.out.println("author==>"+author);
       
        //在android端显示接收到的广播内容
        Toast.makeText(MainActivity.this, author, 1).show();
       
        //在结束时可取消广播
        //MainActivity.this.unregisterReceiver(this);
       }
      }
         
        }
    }

    原文转载自:android简单的广播发送与接收

    谢谢支持我的网站:鼓浪屿住宿

  • 相关阅读:
    MSDTC服务出错
    jquery.lazyload.js实现图片延迟加载——wordpress图片随滚动条渐显效果
    js:警惕firstChild
    基于jquery的表格排序
    jquery JSON的解析方式
    用JS jquery取float型小数点后两位
    JQuery之append和appendTo的区别,还有js中的appendChild用法
    js笔记之Math random()、ceil()、floor()、round()
    Oracle笔记
    STL: equal
  • 原文地址:https://www.cnblogs.com/clarence/p/3386202.html
Copyright © 2020-2023  润新知