一、参考方案
1.所有添加产品到购物车、修改购物车产品数量的操作,在操作完毕后发送广播。
2.静态注册一个广播接受者类,在广播接受者中对发送的广播进行判断,然后进行修改数量的操作。
清单文件
<!-- 购物车产品数量 -->
<receiver android:name="com.chinabuye.android.broadcast.NumberBroadcast" >
<intent-filter android:priority="1000" >
<action android:name="add.to.cart.params" />
<action android:name="add.to.cart.noparams" />
<action android:name="cart.reduce" />
<action android:name="cart.add" />
<action android:name="cart.remove" />
<action android:name="buy.success" />
</intent-filter>
</receiver>
广播接受者
package com.chinabuye.android.broadcast;
import com.chinabuye.android.bean.BroadAction;
import com.chinabuye.android.bean.NumberBean;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class NumberBroadcast extends BroadcastReceiver {
// 广播接受者,修改购物车产品数量
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
NumberBean bean = NumberBean.getInstance();
int number = bean.getNumber();
if (action.equals(BroadAction.ACTION3_REDUCE)) {// 数量减1
bean.setNumber(context,number - 1);
} else if (action.equals(BroadAction.REMOVE)) {// remove
int number2 = intent.getIntExtra("number", -1);
if (number2 != -1 && number2 <= number) {
bean.setNumber(context,number - number2);
}
} else if (action.equals(BroadAction.BUY_SUCCESS)) {// 下单购买成功
bean.setNumber(context,0);
} else {// 数量加1
bean.setNumber(context,number + 1);
}
Intent intent2 = new Intent();
intent2.setAction(BroadAction.CHANGE_NUMBER);
context.sendBroadcast(intent2);
}
}
3.在需要显示购物车产品数量的每个Activity中,动态注册一个广播接受者,接受静态注册的广播接受者发送的广播,在接收到广播后,修改显示的数量。
动态注册
//注册广播,用于跟新购物车产品数量
initBroadcast();
修改显示数量
/************* 广播 **************/
/**
* 注册广播
*/
private void initBroadcast() {
IntentFilter filter = new IntentFilter();
filter.addAction(BroadAction.CHANGE_NUMBER);
registerReceiver(myReceiver, filter);
}
/**
* 接受广播
*/
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NumberBean bean = NumberBean.getInstance();
cartnumber.setText(bean.getNumber() + "");
}
};
/**
* 解除广播
*/
protected void onDestroy() {
unregisterReceiver(myReceiver);
stopService(service);
super.onDestroy();
};