2016-07-20 47 views
1

我該如何實現廣播接收機&過濾器,以便它可以響應多個intents有多種動作的Android廣播接收機

private BroadcastReceiver myReceiver; 
IntentFilter myFilter = new IntentFilter(); 

的onCreate():

myFilter.addAction("first"); 
    myFilter.addAction("second"); 

    myReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
       // do different actions according to the intent 
      } 
     }; 

    registerReceiver(myReceiver, myFilter); 

從我的片段:

Intent i = new Intent("first"); sendBroadcast(i); 

Intent i = new Intent("second"); sendBroadcast(i); 

感謝

+0

只是看在意向'intent.getAction行動() ' – tyczj

回答

4
@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    if(action != null) { 
     if(action.equals("action1") { 
      // CODE 
     } else if (action.equals("action2") { 
      // CODE 
     } 
    } 
}