很多时候我们有这样的需求,比如说,我在一个activity购买了某件商品,需要把另一个activity的余额进行更新,这时候我们就可以用到广播.
首先我们要使用Intent来发送一个广播
定义一个全局的广播名字
public static final String DOLOGOUTTRUE ="com.example.se7en.dreamcity.do_logout_true";
Intent intent = new Intent(); intent.setAction(DOLOGOUTTRUE); intent.putExtra("dolog_true", "dolog_true"); MainSettingsActivity.this.sendBroadcast(intent);
创建一个继承与BroadcastReceiver的类
实现继承的方法
在使用回调函数来实现 你想要发送的string字符串,然后在activity判断这个字符串是不是发送的这个,如果是,进行更新。
public class DologoutReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String isTrue = intent.getStringExtra("dolog_true"); if (onDologoutTrue != null) { onDologoutTrue.getIstrue(isTrue); } } public interface OnDologoutTrue { void getIstrue(String state); } public OnDologoutTrue onDologoutTrue; public void setOnDologoutTrue(OnDologoutTrue onDologoutTrue) { this.onDologoutTrue = onDologoutTrue; } }
在AndroidManifest中注册这个广播
切记 action里的name 和你定义的全局变量DOLOGOUTTRUE的内容一样
<receiver android:name=".receiver.DologoutReceiver"> <intent-filter> <action android:name="com.example.se7en.dreamcity.do_logout_true"></action> </intent-filter> </receiver>
在需要更新的页面 初始化,方法扔oncrete里面就可以。
/** * 广播接收者 */ private void initReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DOLOGOUTTRUE); DologoutReceiver receiver = new DologoutReceiver(); registerReceiver(receiver, intentFilter); receiver.setOnDologoutTrue(this); }
最后一步,在你的activity里implements 你的回调函数,完成未实现的方法。
public class MainActivity extends AppCompatActivity implements View.OnClickListener, DologoutReceiver.OnDologoutTrue
@Override public void getIstrue(String state) { if (state.equals("dolog_true")) { loginDialog.show(); } }
这样就好了。