Может кто-нибудь помочь мне с Android RemoteControlClient?

Я пытаюсь получитьRemoteControlClient настроить так, чтобы музыкой моего приложения можно было управлять с помощью виджета, который появляется на экране блокировки (например, SoundCloud, Google Play Music и другие музыкальные / видео приложения). Я не уверен, что не так с моим кодом и почему он не правильно перехватывает, но вот что у меня есть до сих пор ...

Класс MusicService, который пытается обработать обновления RemoteControlClient.

public class MusicService extends Service
{
public static final String ACTION_PLAY = "com.stfi.music.action.PLAY";
private RemoteController controller = null;

@Override
public void onCreate()
{
    super.onCreate();

    System.out.println("Creating the service.");

    if(controller == null)
    {
        controller = new RemoteController();
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    String action = intent.getAction();
    System.out.println("Got an action of " + action);

           /* Logic to get my Song cur */
    controller.register(this);
    controller.updateMetaData(cur);

    return START_STICKY;
}

@Override
public void onDestroy()
{
    super.onDestroy();
    System.out.println("Destorying MusicService");
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
}

Это использует класс, который я назвалRemoteController где находится мойRemoteControlClient.

public class RemoteController { 
private RemoteControlClient remoteControlClient;
private Bitmap dummyAlbumArt;


public void register(Context context)
{
    if (remoteControlClient == null)
    {
        System.out.println("Trying to register it.");

        dummyAlbumArt = BitmapFactory.decodeResource(context.getResources(), R.drawable.dummy_album_art);

        AudioManager audioManager = (AudioManager) context.getSystemService(context.AUDIO_SERVICE);

        ComponentName myEventReceiver = new ComponentName(context.getPackageName(), MediaButtonReceiver.class.getName());
        audioManager.registerMediaButtonEventReceiver(myEventReceiver);

        // build the PendingIntent for the remote control client 
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(myEventReceiver);
        // create and register the remote control client 
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0);
        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
                | RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
                );
        audioManager.registerRemoteControlClient(remoteControlClient);


    }
} 

/** 
 * Update the state of the remote control. 
 */ 
public void updateState(boolean isPlaying)
{
    if(remoteControlClient != null)
    {
        if (isPlaying)
        {
            remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
        }

        else
        { 
            remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
        } 
    } 
} 

/** 
 * Updates the state of the remote control to "stopped". 
 */ 
public void stop()
{ 
    if (remoteControlClient != null)
    {
        remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
    } 
} 

public void updateMetaData(Song song)
{
    if (remoteControlClient != null && song != null)
    {
        System.out.println("Updating metadata");
        MetadataEditor editor = remoteControlClient.editMetadata(true);
        editor.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, dummyAlbumArt);
        editor.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, (long)1000);
        editor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, "Artist");
        editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Title");
        editor.apply();

        updateState(true);
    }
}

/** 
 * Release the remote control. 
 */ 
public void release() { 
    remoteControlClient = null;
} 
} 

Каждый раз, когда я хочу обновить виджет, я звонюstartService(new Intent(MusicService.ACTION_PLAY));, Похоже, что он правильно создает службу, и он всегда доходит до того, что говорит «Обновление метаданных», но по какой-то причине, когда я блокирую свой экран и разблокирую его, я не вижу никакого виджета на своем экране блокировки.

Ниже приведены важные части моего манифеста, поскольку это может как-то вызвать проблему ...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stfi"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="17" />

<application
    android:hardwareAccelerated="true"
    android:allowBackup="true"
    android:icon="@drawable/stfi"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:theme="@style/MyActionBarTheme" >
    <meta-data
        android:name="android.app.default_searchable"
        android:value=".activities.SearchActivity" />

    <activity
        android:name=".StartingToFeelIt"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>
    ...other activities listed

    <service
        android:name=".helpers.MyNotificationService"
        android:enabled="true"
        android:label="MyNotificationServiceLabel" >
    </service>
    <service
        android:name=".music.MusicService"
        android:exported="false" >
        <intent-filter>

            <action android:name="com.stfi.music.action.PLAY" />

        </intent-filter>
        <intent-filter>
            <action android:name="com.example.android.musicplayer.action.URL" />

            <data android:scheme="http" />
        </intent-filter>
    </service>

    <receiver
        android:name=".music.MediaButtonReceiver"
        android:exported="false" >
    </receiver>
</application>

Прямо сейчас мой MediaButtonReceiver на самом деле ничего не делает. Я просто пытаюсь настроить крючки. Если хотите, это мой класс MediaButtonReceiver ...

public class MediaButtonReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
    System.out.println("Receiving something.");
    if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON))
    {
        final KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

        if (event != null && event.getAction() == KeyEvent.ACTION_UP)
        {

            if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
            {
                System.out.println("You clicked pause.");
            }

            else if(event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY)
            {
                System.out.println("You clicked play.");
            }

            else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_NEXT)
            {
                System.out.println("You clicked next.");
            }

            else if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PREVIOUS)
            {
                System.out.println("You clicked previous.");
            }
        }
    }
}

}

Ответы на вопрос(1)

Ваш ответ на вопрос