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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new Button.OnClickListener() {
@Override
public 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);
}
});
}
@Override
public 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 {
@Override
public 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>