2013-08-04 42 views
0

我發現很多關於這個話題的線索,但是我無法解決我的問題。下面是代碼:BroadcastReceiver不叫

清單文件:

<service 
      android:name="com.xxx.player.MediaPlayerService.MediaPlayerService" 
      android:enabled="true" > 
      <intent-filter> 
       <action android:name="android.media.AUDIO_BECOMING_NOISY" /> 
      </intent-filter> 

      <receiver android:name="com.xxx.player.MediaPlayerService.MediaPlayerService$ServiceBroadcastReceiver" 
         android:enabled="true" 
         android:exported="false"> 
       <intent-filter> 
        <action android:name="@string/ACTION_PREPARE_AND_PLAY_NEW_FILE"/> 
        <action android:name="@string/ACTION_PREPARE_NEW_FILE"/> 
        <action android:name="@string/ACTION_START"/> 
        <action android:name="@string/ACTION_STOP"/> 
        <action android:name="@string/ACTION_PAUSE"/> 
        <action android:name="@string/ACTION_SEEK_TO"/> 
        <action android:name="@string/ACTION_RELEASE"/> 
       </intent-filter> 
      </receiver> 
     </service> 

廣播類:

public class MediaPlayerService extends Service implements 
     MediaPlayer.OnErrorListener, 
     AudioManager.OnAudioFocusChangeListener, 
     Runnable, 
     SeekBar.OnSeekBarChangeListener { 

    ... 

    public class ServiceBroadcastReceiver extends BroadcastReceiver { 

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

      String action = intent.getAction(); 

      Toast.makeText(getApplicationContext(), "action: " + action, 30000000).show(); 

      if (action.equals(Resources.getSystem().getString(R.string.ACTION_PREPARE_AND_PLAY_NEW_FILE))) { 
       prepareAndPlayNewFile(intent.getStringExtra("mediaData")); 
      } 

     } 

    } 

} 

我提交意向方式:

private void prepareAndPlayNewFile(String mediaData) { 
     Intent myIntent = new Intent(); 
     myIntent.setAction(context.getString(R.string.ACTION_PREPARE_AND_PLAY_NEW_FILE)); 
     myIntent.putExtra("mediaData", mediaData); 
     context.sendBroadcast(myIntent); 
    } 

回答

1

而不是接近你的演奏的媒體,您應該將您的服務綁定到您的活動,而不是爲我使用廣播接收器傳遞。

而且你不應該使用@字符串/ VAR1(這我不知道,如果意圖過濾器與那種列定義的工作)對你的意圖行動,它總是應該是常量字符串,如:

android.intent.action.BLAH 
+0

我會尋找綁定:) – user1315621

+1

通過'startService()發送命令到服務比綁定選項更容易。如果你真的想使用消息總線,不要使用普通廣播,因爲它們是公開的。使用「LocalBroadcastManager」或第三方消息總線(例如Square的Otto,greenrobot的EventBus)。 – CommonsWare

+0

你是否建議最好使用startService()或綁定?什麼是最乾淨最聰明的方式? – user1315621

相關問題