1)创建发送广播Android Application Project “SendApp”修改MainActivity.java代码如下

package com.example.sendapp;import java.sql.Date;import java.text.SimpleDateFormat;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button button1=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button1=(Button)findViewById(R.id.button1);button1.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent();/*获取当前时间并设置样式*/              SimpleDateFormat formatter=new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");              Date currentDate=new Date(System.currentTimeMillis());              String currentDateString=formatter.format(currentDate);                          /*创建Bundle对象,并将要传递的数据传入*/Bundle bundle=new Bundle();bundle.putString("currentDate", currentDateString);intent.putExtras(bundle);intent.setAction("com.neter.broadcast.receiver.DEMO_ACTION");sendBroadcast(intent);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

2)创建接收广播Android Application Project "ReceiveApp"

1. 创建类文件DemoReceiver.java继承自BroadcastReceiver,聆听系统服务广播的信息,具体代码如下

package com.example.receiveapp;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.util.Log;public class DemoReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context,Intent intent){if(intent.getAction().equals("com.neter.broadcast.receiver.DEMO_ACTION")){/*获取Bundle对象*/          Bundle bundle=intent.getExtras();        if(bundle!=null){        /*获取Bundle对象中的数据*/              String currentDateString=bundle.getString("currentDate");             Log.i("BroadcastTest", currentDateString);        }}}}

2. 在AndroidManifest.xml中创建receiver聆听系统广播信息,具体代码如下

<receiver android:name=".DemoReceiver">            <intent-filter>                <action android:name="com.neter.broadcast.receiver.DEMO_ACTION"></action>            </intent-filter>        </receiver>


运行两个项目,单击发送广播项目的发送按钮,接收广播项目就能聆听到广播信息。

更多相关文章

  1. Android如何将第三方信息应用设置为默认信息应用?
  2. android 设置默认launcher 附上代码
  3. Android通过代码自动连接WiFi
  4. Android service: startService的代码实现
  5. Android 签名信息读取
  6. 【代码】利用Android的Log 演示一个activity的生命周期
  7. android studio使用.gitignore建立项目过滤规则
  8. Android Robotium的自动化代码
  9. Android代码实现飞行模式的打开

随机推荐

  1. Android 三大图片缓存原理、特性对比
  2. Android调用系统相机、自定义相机、处理
  3. Mika Mobile 谈论 Android 游戏开发:一个
  4. 一些优秀的 Android 开发专栏推荐
  5. Android SDK 2.3与Eclipse开发环境搭建
  6. 从零开始--系统深入学习android(实践-让我
  7. 内存泄漏,关于异步回调导致的内存泄漏,使用
  8. Android BroadcastReceiver(广播)实现消
  9. Android官方架构组件Paging:分页库的设计
  10. Android隐藏状态栏 全屏