1、使用标准广播
1.1 定义广播接收器
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String string=arg1.getStringExtra("data");
Toast.makeText(arg0, "received:"+string, Toast.LENGTH_SHORT).show();
}
}
1.2 修改AndriodManifest.xml,注册广播接收器
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcastreceiverdemo.BROADCAST"></action>
</intent-filter>
</receiver>
1.3 补充MainActivity代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.broadcastreceiverdemo.BROADCAST");
intent.putExtra("data", "hello");
sendBroadcast(intent);
}
});
}
}
2、使用本地广播
本地广播只能够在应用程序的内部进行传递,并且广播接收器也只能接收来自本应用程序发出的广播,这样就提高了数据传播的安全性。但本地广播无法通过静态注册的方式来接收。本地广播使用LocalBroadcastManager来对广播进行管理,并提供了发送广播及注册广播接收器的方法。
//定义广播接收器
public class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String string=arg1.getStringExtra("data");
Toast.makeText(arg0, "received:"+string, Toast.LENGTH_SHORT).show();
}
}
//MainActivity
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter=new IntentFilter("com.example.localbroadcastdemo.LOCALBROADCAST");
localReceiver=new LocalReceiver();
//获取实例
localBroadcastManager=LocalBroadcastManager.getInstance(this);
//注册本地广播监听器
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
Button button=(Button)findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.localbroadcastdemo.LOCALBROADCAST");
intent.putExtra("data", "hello");
//发送本地广播
localBroadcastManager.sendBroadcast(intent);
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
@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;
}
}