我查看了许多关于从服务向活动发送消息的帖子,但我无法让它发挥作用。我的接收器永远不会被调用。如果 Activity 不在前台,这有关系吗?
这是我的场景 - 我将 Web 服务器作为服务运行。当网络服务器收到带有播放列表链接的 URL 时,我需要向充当媒体播放器的我的 Activity 发送一条消息。媒体播放器将读取播放列表并开始按顺序播放歌曲、视频等。
我不希望该服务启动媒体播放器活动的新实例,因为有时它可能会发送快进或暂停等命令。
从我的网络服务器服务:
private void sendMessage() {
Log.d("juice NonoHTTPD sender", "Sending message from Hub Web Server to Hub Player");
Intent intent = new Intent();
intent.putExtra(HubPlayer.ACTIVITY_PARAM_HOST, sAppHost);
intent.putExtra(HubPlayer.ACTIVITY_PARAM_PORT, sAppPort);
intent.putExtra(HubPlayer.ACTIVITY_PARAM_TYPE, sAppType);
intent.putExtra(HubPlayer.ACTIVITY_PARAM_URL, sAppPath);
intent.setAction("com.jigawattlabs.hubplayer.play");
appContext.sendBroadcast(intent);
}
从我的活动:
public class HubPlayer extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback
{
private IntentFilter intentFilter = new IntentFilter("com.jigawattlabs.hubplayer.play");
MyBroadcastReceiver mReceiver = new MyBroadcastReceiver();
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.mediaplayer_2);
registerReceiver(mReceiver , intentFilter);
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
extras = intent.getExtras();
sHost = extras.getString(ACTIVITY_PARAM_HOST);
sPort = extras.getString(ACTIVITY_PARAM_PORT);
sType = extras.getString(ACTIVITY_PARAM_TYPE);
sXMLURL = extras.getString(ACTIVITY_PARAM_URL);
DebugMsg("received broadcast in MyBroadcastReceiver.");
processInputRequest();
}
}
}
尽管似乎没有必要将其放入清单中,因为我在代码中注册了 BroadcastReceiver,但我还添加了一个意图过滤器:
<activity android:label="Media Hub Player" android:launchMode="singleTask"
android:screenOrientation="unspecified"
android:name=".HubPlayer" >
<intent-filter>
<action android:name="com.jigawattlabs.hubplayer.play" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
提前致谢。