【问题标题】:Passing parameter to a running service thread将参数传递给正在运行的服务线程
【发布时间】:2013-07-11 19:21:07
【问题描述】:

我有 MP3 播放服务,它有自己的类并使用 Mediaplayer 并与 HTTP 连接。它必须播放在上一个 Activity 中选择的 URL 之一,我将其传递给 PlayerActivity。

我在PlayerActivity onCreate中以这种方式创建服务:

         startService(new Intent(this, PlayerService.class));
         Intent connectionIntent = new Intent(this, PlayerService.class);
         bindService(connectionIntent, mp3PlayerServiceConnection, Context.BIND_AUTO_CREATE);

这是第一个选定的 URL 启动。我在新线程中启动 Mediaplayer 调用以不阻塞 UI(调用本身在 ActivityPlayer 中):

private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName arg0, IBinder binder) {
        mp3Service = ((LocalBinder) binder).getService();

        Thread t = new Thread() {
        public void run() {

            mp3Service.playSong(getApplicationContext(),url);

        }
        };

        t.start();


    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {

    }
 };

问题是如何将一个新的 URL 传递给这个 Service 的线程,当用户销毁这个 Activity 时,进入菜单并选择新的 URL。新的流必须在同一个线程中播放,但我遇到了使用后退按钮返回主页并再次启动应用程序的情况,我同时播放了 2 个 URL。可能是新的Thread() 声明的原因。

那么,当Activity用一个URL创建时,如何把它的URL权传递给Service的线程,所以如果是旧的URL,什么都不会发生,如果是新的,播放器会切换到新的URL,但不能播放2一起流?

【问题讨论】:

  • 您是在 bindService 上返回相同的 Binder 还是新的?
  • 这是来自服务类的代码:public final IBinder localBinder = new LocalBinder(); @Override public IBinder onBind(Intent intent) { return localBinder; } public class LocalBinder extends Binder { PlayerService getService() { return PlayerService.this; } }

标签: android multithreading service parameters


【解决方案1】:

有什么理由不通过广播进行交流?您可以在服务中实现嵌套的BroadcastReceiver(如果需要在活动中),然后从活动中向它发送信号。

如果有任何私人数据,您可以使用LocalBroadcastManager 来防止它被系统范围内的数据。

编辑:

对于其他用途,还有 Android 接口定义语言。

【讨论】:

  • 也许我已经看到了一些关于这个的东西,但是服务通常会先见面,所以我选择了更简单的方式(至少对于 Android 的初学者来说)......
  • 你能在这里谈谈线程的使用吗?是否有可能同时出现 2 个线程的错误位置?
  • 您可以在清单中指定process=:process_desc:将使服务在它自己的进程中运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 2011-04-17
  • 2011-10-08
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多