2012-04-20 96 views
2

我试图通过位于Google Play音乐应用之上的服务和接收器来扩展有线麦克风远程按钮的功能,并通过广播与其通信。我在Google Nexus S的ICS上。如何从外部应用程序启动MusicPlaybackService?

我的问题是我的代码在MusicPlaybackService运行后效果很好,但情况并非总是如此。如何在不显示任何UI的情况下启动此服务(用户不知道)。我的代码有如下定义:

public static final String SERVICECMD = "com.android.music.musicservicecommand"; 
public static final String CMDNAME = "command"; 
public static final String CMDTOGGLEPAUSE = "togglepause"; 
public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause"; 

我曾尝试以下选项:

1)基于关闭this SO question。我不确定是否关于SERVICECMD,因为问题表明我应该使用“com.android.music.musicservicecommand”,尽管对于ICS我相信软件包名称已经改变。

Intent i = new Intent(SERVICECMD); 
i.putExtra(CMDNAME, CMDTOGGLEPAUSE); 
sendBroadcast(i); 

我也尝试用TOGGLEPAUSE_ACTION替换SERVICECMD。

2)从this android项目问题。

Intent musicIntent = new Intent(); 
musicIntent.setClassName("com.google.android.music", "com.google.android.music.MusicPlaybackService"); 
musicIntent.setAction(TOGGLEPAUSE_ACTION); 
musicIntent.putExtra(CMDNAME, CMDTOGGLEPAUSE); // or "next" or "previous" 
sendBroadcast(musicIntent); 

3)此代码崩溃,下面的错误。我不确定如何继续使用此选项。

Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.google.android.music/com.google.android.music.MusicPlaybackService}; have you declared this activity in your AndroidManifest.xml?

Intent intent = new Intent(); 
intent.putExtra(CMDNAME, CMDTOGGLEPAUSE); 
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
intent.setClassName("com.google.android.music", "com.google.android.music.MusicPlaybackService"); 
startActivity(intent); 

4)我注意到,当耳机从手机删除,MusicPlaybackService是因为它是响应由WiredAccessoryObserver拿起Intent.ACTION_HEADSET_PLUG广播开始。我尝试使用LogCat中显示的值在我的代码中复制该广播。

Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG); 
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 
intent.putExtra("state", 0); 
intent.putExtra("name", "h2w"); 
intent.putExtra("microphone", 1); 
sendBroadcast(intent); 

我真的在寻找一种可以随时启动服务的方法。我对任何事情都很开放。我仍然必须尝试绑定到使用IMediaPlaybackService.aidl的服务,该服务应该随机地中断,并且不理想。提前感谢您的帮助。

编辑

我试着用下面这引发了错误代码绑定到服务:

Caused by: java.lang.SecurityException: Not allowed to bind to service Intent { cmp=com.google.android.music/.MusicPlaybackService }

在我的OnCreate函数

if (mPlaybackService == null) { 
    Intent i = new Intent(); 
    i.setClassName("com.google.android.music","com.google.android.music.MusicPlaybackService"); 
    bindService(i, connection, Context.BIND_AUTO_CREATE); 
} 

在我的课堂

IMediaPlaybackService mPlaybackService = null; 
ServiceConnection connection = new ServiceConnection() { 
    public void onServiceConnected(ComponentName name, IBinder service) {  
     mPlaybackService = IMediaPlaybackService.Stub.asInterface(service); 
} 

    public void onServiceDisconnected(ComponentName name) { 
     mPlaybackService = null; 
    } 
}; 

回答

2

我d不认为这是可能的。我的解决方法是让按钮被按下时,应用程序自己的broadcastreceiver唤醒服务。我只是为我的应用程序请求audiofocus并等待它丢失。

+0

您是否得到了解决方案? – Debugger 2014-12-28 06:17:13

相关问题