2015-02-11 32 views
-1

我的接收器不工作。問題在於課堂和活動之間。即時通訊從類發送消息到活動,但不工作... 該班將與兩個活動,一次一個通...Android和課間活動

我的廣播代碼(活動內):

public class MainActivity extends Activity{ 

BroadcastReceiver receiver; 
IntentFilter filter; 

private void init() { 
     try { 

      ... 

      receiver = new BroadcastReceiver() { 

       @Override 
       public void onReceive(Context context, Intent intent) { 
        String action = intent.getAction(); 

        if(action.equals("HAS_CONECT")){ 
         progressBar.setVisibility(View.GONE); 
         Toast.makeText(getApplicationContext(), "IS CONECTED!", Toast.LENGTH_LONG).show(); 
        } 
        else if(action.equals("ARRIVES")){ 
         Toast.makeText(getApplicationContext(), "HAS ARRIVE!!!", Toast.LENGTH_LONG).show(); 
        } 
       } 

      }; 

      filter = new IntentFilter("HAS_CONECT"); 
      registerReceiver(receiver, filter); 
      filter = new IntentFilter("ARRIVES"); 
      registerReceiver(receiver, filter); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

... 
} 

而且我的代碼類:

public void adviseActivity(){ 
    try { 
     Intent i = new Intent("MESSAGE"); 
     i.putExtra("msg", "DATA ARRIVE"); 
     i.setAction("ARRIVES"); 
     context.sendBroadcast(i); 

    } catch (Exception e) { 
     System.out.print(e); 
    } 
} 

回答

0

的問題是在你的onReceive方法,你找錯了行動。您設置的操作是MESSAGE,但您正在查找的操作onReceiveHAS_CONECTARRIVES。 更正代碼如下:

  @Override 
      public void onReceive(Context context, Intent intent) { 
       String action = intent.getAction(); 

       if(action.equals("MESSAGE")){ 
        progressBar.setVisibility(View.GONE); 
        Toast.makeText(getApplicationContext(), "IS CONECTED!", Toast.LENGTH_LONG).show(); 
       } 
      } 
+0

謝謝!我認爲這是setAction(「ARRIVE」); setAction什麼是功能? 我如何得到i.putExtrA(「msg」,「A」)? – user3240604 2015-02-11 18:25:05

+0

'Bundle bundle = intent.getExtras(); bundle.getString(「msg」);' – Psypher 2015-02-11 19:21:35

+0

謝謝,現在我有最後一個問題。我有5個活動,我必須在每個活動中複製廣播......我不知道這是否是交流班和活動的最佳解決方案 – user3240604 2015-02-12 17:02:55