2012-01-02 8 views
0

서비스에서 브로드 캐스트되는 활동의 메시지를 수신하기 위해 BroadcastReceiver를 사용하여 많은 게시물을 볼 수 있습니다. 나는 수십을 겪어 왔지만 그것을 하나로 모으는 사람을 찾지 못했습니다. 결론은 방송 수신을위한 활동을 가져올 수 없다는 것입니다.End to end BroadcastReceiver 연결

서비스 클래스 방송 :

Context context = this.getApplicationContext(); 
Intent intentB2 = new Intent(context, StationActivity.AudioReceiver.class); 
intentB2.putExtra("Track", mSongTitle); 
this.sendBroadcast(intentB2); 
Log.i(TAG, "Broadcast2: " + mSongTitle); 

활동 클래스 선언 :

public String INCOMING_CALL_ACTION = "com.example.android.musicplayer.action.BROADCAST"; 

활동 수준의 인라인 브로드 캐스트 리시버 :

public class AudioReceiver extends BroadcastReceiver  
{ 
    @Override 
    public void onReceive(Context context, Intent intent) { 
    // Handle receiver 
    Log.i(TAG, "Inner BroadcastReceiver onReceive()"); 
    String mAction = intent.getAction(); 

    if(mAction.equals(INCOMING_CALL_ACTION)) { 
     Log.i(TAG, "Inner BroadcastReceiver onReceive() INCOMING_CALL_ACTION"); 
    } 
    } 
}; 

안드로이드 매니페스트 수신기 여기에 내가 지금까지 한 일이다 선언 :

<receiver android:name=".StationActivity.AudioReceiver"> 
     <intent-filter> 
      <action android:name="com.example.android.musicplayer.action.BROADCAST" /> 
     </intent-filter>    
    </receiver> 

무엇이 누락 되었습니까? 미리 감사드립니다.

답변

0

서비스 코드를 아래 코드로 바꾸고 서비스에 문자열 INCOMING_CALL_ACTION을 추가하거나 활동 클래스에서 직접 사용하십시오. 서비스에서

Context context = this.getApplicationContext(); 
Intent intentB2 = new Intent(); 
intentB2.setAction(INCOMING_CALL_ACTION); 
intentB2.putExtra("Track", mSongTitle); 
this.sendBroadcast(intentB2); 
Log.i(TAG, "Broadcast2: " + mSongTitle); 
1

: 활동에서 그런

Intent intentB2 = new Intent("some_action_string_id"); 
intentB2.putExtra("Track", mSongTitle); 
sendBroadcast(intentB2); 

:

public class MyActivity extends Activity { 

    private BroadcastReceiver myReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Toast.makeText(getApplicationContext(), "Woot! Broadcast received!", Toast.LENGTH_SHORT); 
     } 
    }; 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     IntentFilter filter = new IntentFilter("some_action_string_id"); // NOTE this is the same string as in the service 
     registerReceiver(myReceiver, filter); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(myReceiver); 
    } 
} 

이 활동에 브로드 캐스트 이벤트를 수신 할 수있는 일반적인 방법입니다. 액티비티가 포 그라운드에있을 때 수신기를 등록하고 액티비티가 더 이상 보이지 않을 때이를 등록 해제합니다.

+0

감사합니다. 두 응답은 서비스 클래스가 내 부분에서 놓친 행동을 적절히 설정하도록 보장하는 데 중점을 둡니다. 어떤 이유로 나는 registerReceiver() 조각이 서비스에서 발생할 것이라고 생각했지만 그렇지 않을 것입니다. 이제 작동합니다. – Jslmns71