一陣子沒碰還是會忘記 BroadcastReceiver 怎麼做, 今天又重新整理了一下
首先在要接收封包事件的class新增一個class
在此範例中是寫在主程式(extends Activity)
public class BroadcastReceiver_customize extends BroadcastReceiver { //定義封包來源 static final String PieFee_ACTION = "com.tsots.PieFee"; @Override public void onReceive(Context context, Intent intent) { //若封包符合PieFee_ACTION內的值就接收下來 if (intent.getAction().equals(PieFee_ACTION)) { Bundle bundle_from = intent.getExtras(); if (bundle_from != null){ //解析封包內的"FROM"值 from = bundle_from.getString("FROM"); if(from.equals("prizeexchanged")){ //這裡是接收到Broadcast後要做的事 } } } } }
在主程式(extends Activity) 的onResume()中增加
@Override protected void onResume() { super.onResume(); //註冊一個Filter IntentFilter mFilter = new IntentFilter(BroadcastReceiver_customize.PieFee_ACTION); BroadcastReceiver_customize BRC = new BroadcastReceiver_customize(); registerReceiver(BRC, mFilter); }
再來決定發送端
在此範例中是寫在一個extends BaseAdapter的class裡
//會將封包以 "com.tsots.PieFee"的名義發送 Intent intent = new Intent("com.tsots.PieFee"); Bundle bundle_br_prize = new Bundle(); //在其內打包一個值作為識別 bundle_br_prize.putString("FROM", "prizeexchanged"); intent.putExtras(bundle_br_prize); //因為此class非extends Activity, 故加context(呼叫此class時會傳入context的值) context.sendBroadcast(intent);
沒有留言:
張貼留言