Fix crash in legacy apps that register without a looper

Some legacy apps registered their media button receiver in a thread
without a looper. If this happens we need to use the main looper to
prevent a crash.

bug: 16306226
Change-Id: Idf472e649393e2a7ce2a3e1cbb3476003ab17f34
diff --git a/cmds/media/src/com/android/commands/media/Media.java b/cmds/media/src/com/android/commands/media/Media.java
index d9faf4c..b5e1bf5 100644
--- a/cmds/media/src/com/android/commands/media/Media.java
+++ b/cmds/media/src/com/android/commands/media/Media.java
@@ -218,7 +218,7 @@
         void printUsageMessage() {
             try {
                 System.out.println("V2Monitoring session " + mController.getTag()
-                        + "...  available commands:");
+                        + "...  available commands: play, pause, next, previous");
             } catch (RemoteException e) {
                 System.out.println("Error trying to monitor session!");
             }
@@ -250,6 +250,14 @@
                         addNewline = false;
                     } else if ("q".equals(line) || "quit".equals(line)) {
                         break;
+                    } else if ("play".equals(line)) {
+                        mController.play();
+                    } else if ("pause".equals(line)) {
+                        mController.pause();
+                    } else if ("next".equals(line)) {
+                        mController.next();
+                    } else if ("previous".equals(line)) {
+                        mController.previous();
                     } else {
                         System.out.println("Invalid command: " + line);
                     }
diff --git a/media/java/android/media/session/MediaSessionLegacyHelper.java b/media/java/android/media/session/MediaSessionLegacyHelper.java
index a182982..aa196a9 100644
--- a/media/java/android/media/session/MediaSessionLegacyHelper.java
+++ b/media/java/android/media/session/MediaSessionLegacyHelper.java
@@ -290,7 +290,6 @@
             if (DEBUG) {
                 Log.d(TAG, "addMediaButtonListener already added " + pi);
             }
-            return;
         }
         holder.mMediaButtonListener = new MediaButtonListener(pi, context);
         // TODO determine if handling transport performer commands should also
@@ -468,7 +467,11 @@
                 mSessions.remove(mPi);
             } else if (mCb == null) {
                 mCb = new SessionCallback();
-                mSession.setCallback(mCb);
+                Handler handler = null;
+                if (Looper.myLooper() == null) {
+                    handler = new Handler(Looper.getMainLooper());
+                }
+                mSession.setCallback(mCb, handler);
             }
         }