如何从活动传递数据,而无需启动一个新的实例来服务? [英] How to pass data from Activity to Service without starting a new instance?
问题描述
我使用的意图,演员等,并使用startService(意向),在将数据传递到服务没有问题。
I have no problem in passing data to a service using intent, extras, etc and using startService(intent)
Intent intent = new Intent();
intent.setClass(MainActivity.this, MediaPlayerService.class);
intent.setAction(MediaPlayerService.PLAY_PAUSE);
intent.putExtra("URI", URI);
intent.putExtra("TITLE", content.toString());
//PendingIntent.getService(MainActivity.this, 0, intent, 0);
startService(intent);
的问题是,该服务使用的MediaPlayer播放音乐背景服务。使用startService每次我担心它可能产卵多个玩家,最终我得到一个ANR(即使一切顺利运行)
The problem is that the service is a background service using MediaPlayer to play music. Using startService each time I'm afraid that it might be spawning multiple players, and eventually I get an ANR (even if everything is working smoothly)
所有我需要的是告诉MusicPlayerService玩一个新的轨道。有任何想法吗?正如你可以从code我也试过的PendingIntent看到(建议在网络上),但它似乎没有工作。
All I need is to tell the MusicPlayerService to play a new track. Any ideas? As you can see from the code I also tried PendingIntent (suggested on the net) but it didn't seem to work
谢谢!
推荐答案
解决了!
我检查,如果我这样做
Solved! I checked and if I did
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d(TAG,"super called "+startId);
...
我看到startId不断增加,并最终给予超时。通过调用解决
I saw startId was constantly increasing and giving timeouts eventually. Solved by calling
stopService(intent)
...
startService(intent)
这么简单,但这么多的头疼找到它了!
so simple and yet so many headaches to find it out!
这篇关于如何从活动传递数据,而无需启动一个新的实例来服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!