音乐播放器widget 补充
音乐播放器widget 补充
?
[功能]
在 音乐播放器widget 前传 后传 有一些没讲清楚 所以打算再开辟 专门说一下
?
?
1. Bundle 复用
?
2. BroadcastReceiver 复用
?
?
[前提]
1. 现有一BroadcastReceiver:class MessageListenerHelper extends BroadcastReceiver 实现如下:
public class MessageListenerHelper extends BroadcastReceiver {Context context;MessageListenerHelper listener;//construct public MessageListenerHelper(Context c){context = c;//to instance itlistener = this;}public void registerAction(String action){IntentFilter filter = new IntentFilter();filter.addAction(action);context.registerReceiver(listener,filter);}@Overridepublic void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stub}}
?
MessageListenerHelper listener = new MessageListenerHelper(this);listener.registerAction("Broadcast_MessageListwener");?
?
2. 发生某Broadcast
public void sendMessageText(String s){ Intent i = new Intent(BroadcastColumn.BROADCAST_TaskB); Bundle b = new Bundle(); b.putString("Message_Text", s); i.putExtras(b); sendBroadcast(i); }
?
?
3. 实现onReceive() 并对具体消息做判断
public void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubBundle b = arg1.getExtras();if(b.containsKey("Message_Text")){String string = b.getString("Message_Text");Log.d("TAG",string);}}
?
?
?
4. 如此就实现了Bundle 复用
?
?
?
?
[Broadcast 复用]
1. 注册MessageListenerHelper
MessageListenerHelper listener = new MessageListenerHelper(this);listener.registerAction("Broadcast_MessageListener_1");MessageListenerHelper listener2 = new MessageListenerHelper(this);listener2.registerAction(Broadcast_MessageListener_2);
?
?
2.? 发生某Broadca
public void sendMessage1(String b,String key, String value){ Intent i = new Intent(b); Bundle b = new Bundle(); b.putString(key, value); i.putExtras(b); sendBroadcast(i); }
?
?
3. 实现onReceive() 并对具体Broadcast 做判断
public void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubif(arg1.getAction().endsWith("Broadcast_MessageListener_1")){Bundle b = arg1.getExtras();if(b.containsKey("Message_Text_1")){String string = b.getString("Message_Text_1");Log.d("TAG",string);}}else if(arg1.getAction().endsWith("Broadcast_MessageListener_2")){Bundle b = arg1.getExtras();if(b.containsKey("Message_Text_2")){String string = b.getString("Message_Text_2");Log.d("TAG",string);}}}
?
?
?
4. 此为Broadcast 复用
?
?
补充:
1. 其实除了在widget中 必须用 Broadcast复用外 二者都可以使用 具体用那个 视情况而定
2. 因为Broadcast复用中 需要new 2 次 所以推荐 尽量用 Bundle 复用 仅限个人意见
?
?