2012-12-14 160 views
2

嗨夥計我怎樣才能實現一個廣播接收器在一個活動,從一個服務接收意圖連同一些參數的int和字符串類型?廣播內部活動接收器

UPDATE:

我有這樣的活動下:

private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){ 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     Toast.makeText(context, "IN DA BroadCASTER", 
       Toast.LENGTH_LONG).show(); 

    } 

    }; 

,我有這個服務中的功能是從另一個活動的事件調用時選中的按鈕是下檢查:

public void switchSpeaker(int hr, int min){ 

     Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show(); 

     Intent intent = new Intent(this, andRHOME.class); 
     //intent.putExtra("sendMessage","1"); 
     startActivity(intent); 
     /*PendingIntent pi = PendingIntent.getService(Server.this, 0, myIntent, 0); 
     AlarmManager almmgr = (AlarmManager) getSystemService(ALARM_SERVICE); 
     Calendar cldr = Calendar.getInstance(); 
     int min1 = cldr.get(Calendar.MINUTE); 
     cldr.setTimeInMillis(System.currentTimeMillis()); 
     cldr.add(Calendar.SECOND, 30); 
     almmgr.set(AlarmManager.RTC_WAKEUP, cldr.getTimeInMillis(), pi);*/ 
    } 

但它的崩潰? ,該怎麼辦?

+0

基本上,您粘貼的兩段代碼彼此不相關,也不構成邏輯通信。您需要決定是否要製作intent和startActivity(intent),在這種情況下,您需要在活動中實現onCreate和onNewIntent以處理意圖信息。 或者你想使用廣播系統,然後用sendBroadcast發送意圖(intent); – Raanan

+0

看看他如何發送廣播意圖鏈接: http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/ 如果它是崩潰,請至少添加例外。 – Raanan

+0

我用sendBroadcast代替了錯誤的startActivity()現在沒有異常沒有崩潰但現在我會檢查這個東西是否按照想要的那樣工作!實際上我想傳遞一個變量,然後使用嵌入在Activity下的函數! **廣播員接收器中的更新** Toast未運行,因此意味着沒有收到廣播,我是否正確? – Naaz

回答

9
BroadcastReceiver receiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) {   
     // DO YOUR STUFF 
    } 
} 

IntentFilter filter = new IntentFilter(); 

中的onResume:(所以你只接收而在前臺)

filter.addAction(/* the action you want to receive */); 
registerReceiver(receiver, filter); 
中的onPause

:(在嘗試捕捉是修復在註銷錯誤的情況下,它被稱爲兩次)

try { 
    unregisterReceiver(receiver); 
} catch (IllegalArgumentException e) { 
    if (e.getMessage().contains("Receiver not registered")) { 
     // Ignore this exception. This is exactly what is desired 
     Log.w(TAG,"Tried to unregister the reciver when it's not registered"); 
    } else { 
     // unexpected, re-throw 
     throw e; 
    } 
} 
+0

如果服務是您的,並且您還希望確保活動實際上處於活動狀態,那麼最好從服務開始您的活動,並在活動中處理onNewIntent事件,以處理活動的情況已經有效。 – Raanan

+0

其實我不會有活動活動,但仍然想使用它的功能?這是可能的,如果我只有onReceive()? – Naaz

+0

所以你的問題是在錯誤的方向,你應該做的就是編寫一個擴展BradcastReciver的類並將它註冊到你的應用清單中。所以它處理這個動作。 – Raanan

0
public class myActivity extends Activity { 

    private BroadcastReceiver receiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      // TODO Auto-generated method stub 
      Toast.makeText(getApplicationContext(), "Message", Toast.LENGTH_SHORT); 

     } 
    }; 
protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
} 


}