我查看过从服务到活动发送消息的众多帖子,但我无法让它发挥作用。我的接收器永远不会被呼叫。如果活动不在前台是否重要?
这是我的方案 - 我正在运行Web服务器作为服务。当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而似乎没有必要将它放在清单中,我还添加了一个intent过滤器:
<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>
提前致谢。
答案 0 :(得分:0)
好的,我有一个解决方法,但我希望有更好的东西。这就是我做的事情
以下是检查活动是否正在运行的代码
public boolean isHubRunning()
{
boolean isServiceFound = false;
ActivityManager activityManager = (ActivityManager)appContext.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
isServiceFound = false;
for (int i = 0; i < services.size(); i++)
{
//DebugMsg(services.get(i).topActivity.toString());
if (services.get(i).topActivity.toString().contains("juicemediahub.HubPlayer"))
{
isServiceFound = true;
}
}
DebugMsg("Hub Player Running = " + String.valueOf(isServiceFound));
return isServiceFound;
}
答案 1 :(得分:0)
如果您想要始终获取内容,则应使用接收器。在您的清单中定义它,它将始终捕获您的广播,活动是否正在运行。类似的东西:
<receiver android:name=".StartOnUser">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>