OmniGears: add auto start config for media player event

Change-Id: Ib10d93d8e382d22ba93d74dcc636e3913352fc46
diff --git a/res/values/custom_strings.xml b/res/values/custom_strings.xml
index 88847ca..2307e8d 100644
--- a/res/values/custom_strings.xml
+++ b/res/values/custom_strings.xml
@@ -703,4 +703,6 @@
     <string name="event_service_enabled_title">Enable event service</string>
     <string name="event_service_running">Service is running</string>
     <string name="event_service_stopped">Service is not running</string>
+    <string name="category_media_player_info_title">Select an app to be started for this event</string>
+    <string name="media_player_autostart_title">Send media play event after start</string>
 </resources>
diff --git a/res/xml/event_service_settings.xml b/res/xml/event_service_settings.xml
index 7dbee8b..4b1bf2c 100644
--- a/res/xml/event_service_settings.xml
+++ b/res/xml/event_service_settings.xml
@@ -27,6 +27,13 @@
             android:key="category_media_player"
             android:title="@string/category_media_player_title">
 
+            <Preference
+                android:key="category_media_player_info"
+                android:summary="@string/category_media_player_info_title"
+                android:persistent="false"
+                android:icon="@drawable/ic_info_outline_24dp"
+                android:dependency="event_service_enabled" />
+
             <org.omnirom.omnigears.preference.AppSelectListPreference
                 android:key="bt_a2dp_connect_app"
                 android:title="@string/bt_a2dp_connect_app_title"
@@ -39,5 +46,11 @@
                 android:persistent="false"
                 android:dependency="event_service_enabled" />
 
+            <SwitchPreference
+                android:key="media_player_autostart"
+                android:title="@string/media_player_autostart_title"
+                android:persistent="false"
+                android:dependency="event_service_enabled" />
+
         </PreferenceCategory>
 </PreferenceScreen>
diff --git a/src/org/omnirom/omnigears/service/EventService.java b/src/org/omnirom/omnigears/service/EventService.java
index 79e4533..0acaa70 100644
--- a/src/org/omnirom/omnigears/service/EventService.java
+++ b/src/org/omnirom/omnigears/service/EventService.java
@@ -17,10 +17,7 @@
 */
 package org.omnirom.omnigears.service;
 
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
+import android.app.ActivityManagerNative;
 import android.app.Service;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothA2dp;
@@ -32,17 +29,18 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
-import android.location.LocationManager;
+import android.media.IAudioService;
 import android.media.AudioManager;
-import android.net.ConnectivityManager;
-import android.os.BatteryManager;
-import android.os.HandlerThread;
+import android.media.session.MediaSessionLegacyHelper;
+import android.os.Handler;
 import android.os.Binder;
 import android.os.IBinder;
 import android.os.PowerManager;
 import android.os.UserHandle;
-import android.provider.Settings;
+import android.os.ServiceManager;
+import android.os.SystemClock;
 import android.util.Log;
+import android.view.KeyEvent;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -52,6 +50,9 @@
     private static final boolean DEBUG = true;
     private PowerManager.WakeLock mWakeLock;
     private static boolean mIsRunning;
+    private Handler mHandler = new Handler();
+    private boolean mWiredHeadsetConnected;
+    private boolean mA2DPConnected;
 
     private BroadcastReceiver mStateListener = new BroadcastReceiver() {
         @Override
@@ -62,7 +63,7 @@
                 if (DEBUG) Log.d(TAG, "onReceive " + action);
                 if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                     if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF){
-                    } else {
+                        mA2DPConnected = false;
                     }
                 }
                 if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
@@ -72,35 +73,55 @@
                 if (BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                     int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
                             BluetoothProfile.STATE_CONNECTED);
-                    if (state == BluetoothProfile.STATE_CONNECTED) {
+                    if (state == BluetoothProfile.STATE_CONNECTED && !mA2DPConnected) {
+                        mA2DPConnected = true;
                         if (DEBUG) Log.d(TAG, "BluetoothProfile.STATE_CONNECTED = true" );
                         String app = getPrefs(context).getString(EventServiceSettings.EVENT_A2DP_CONNECT, null);
                         if (app != null) {
                             if (DEBUG) Log.d(TAG, "AudioManager.ACTION_HEADSET_PLUG app = " + app);
                             try {
                                 context.startActivityAsUser(createIntent(app), UserHandle.CURRENT);
+                                if (getPrefs(context).getBoolean(EventServiceSettings.EVENT_MEDIA_PLAYER_START, false)) {
+                                    mHandler.postDelayed(new Runnable() {
+                                        @Override
+                                        public void run() {
+                                            dispatchMediaKeyToAudioService(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
+                                        }
+                                    }, 1000);
+                                }
                             } catch (Exception e) {
                                 Log.e(TAG, "BluetoothProfile.STATE_CONNECTED", e);
                             }
                         }
                     } else {
+                        mA2DPConnected = false;
                         if (DEBUG) Log.d(TAG, "BluetoothProfile.STATE_CONNECTED = false" );
                     }
                 }
                 if (AudioManager.ACTION_HEADSET_PLUG.equals(action)) {
                     boolean useHeadset = intent.getIntExtra("state", 0) == 1;
-                    if (useHeadset) {
+                    if (useHeadset && !mWiredHeadsetConnected) {
+                        mWiredHeadsetConnected = true;
                         if (DEBUG) Log.d(TAG, "AudioManager.ACTION_HEADSET_PLUG = true" );
                         String app = getPrefs(context).getString(EventServiceSettings.EVENT_WIRED_HEADSET_CONNECT, null);
                         if (app != null) {
                             if (DEBUG) Log.d(TAG, "AudioManager.ACTION_HEADSET_PLUG app = " + app);
                             try {
                                 context.startActivityAsUser(createIntent(app), UserHandle.CURRENT);
+                                if (getPrefs(context).getBoolean(EventServiceSettings.EVENT_MEDIA_PLAYER_START, false)) {
+                                    mHandler.postDelayed(new Runnable() {
+                                        @Override
+                                        public void run() {
+                                            dispatchMediaKeyToAudioService(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
+                                        }
+                                    }, 1000);
+                                }
                             } catch (Exception e) {
                                 Log.e(TAG, "AudioManager.ACTION_HEADSET_PLUG", e);
                             }
                         }
                     } else {
+                        mWiredHeadsetConnected = false;
                         if (DEBUG) Log.d(TAG, "AudioManager.ACTION_HEADSET_PLUG = false" );
                     }
                 }
@@ -178,4 +199,21 @@
         intent.setComponent(componentName);
         return intent;
     }
+
+    private void dispatchMediaKeyToAudioService(int keycode) {
+        if (ActivityManagerNative.isSystemReady()) {
+            IAudioService audioService = IAudioService.Stub
+                    .asInterface(ServiceManager.checkService(Context.AUDIO_SERVICE));
+            if (audioService != null) {
+                if (DEBUG) Log.d(TAG, "dispatchMediaKeyToAudioService " + keycode);
+
+                KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(),
+                        SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN,
+                        keycode, 0);
+                MediaSessionLegacyHelper.getHelper(this).sendMediaButtonEvent(event, true);
+                event = KeyEvent.changeAction(event, KeyEvent.ACTION_UP);
+                MediaSessionLegacyHelper.getHelper(this).sendMediaButtonEvent(event, true);
+            }
+        }
+    }
 }
diff --git a/src/org/omnirom/omnigears/service/EventServiceSettings.java b/src/org/omnirom/omnigears/service/EventServiceSettings.java
index e9ac4d3..ffabedb 100644
--- a/src/org/omnirom/omnigears/service/EventServiceSettings.java
+++ b/src/org/omnirom/omnigears/service/EventServiceSettings.java
@@ -54,10 +54,12 @@
     public static final String EVENT_A2DP_CONNECT = "bt_a2dp_connect_app";
     public static final String EVENT_WIRED_HEADSET_CONNECT = "headset_connect_app";
     public static final String EVENT_SERVICE_ENABLED = "event_service_enabled";
+    public static final String EVENT_MEDIA_PLAYER_START = "media_player_autostart";
 
     private AppSelectListPreference mA2DPappSelect;
     private AppSelectListPreference mWiredHeadsetAppSelect;
     private SwitchPreference mEnable;
+    private SwitchPreference mAutoStart;
     private Handler mHandler = new Handler();
 
     @Override
@@ -80,6 +82,10 @@
         mEnable.setSummary(isServiceRunning() ? getResources().getString(R.string.event_service_running)
                 : getResources().getString(R.string.event_service_stopped));
 
+        mAutoStart = (SwitchPreference) findPreference(EVENT_MEDIA_PLAYER_START);
+        mAutoStart.setChecked(getPrefs().getBoolean(EventServiceSettings.EVENT_MEDIA_PLAYER_START, false));
+        mAutoStart.setOnPreferenceChangeListener(this);
+
         mA2DPappSelect = (AppSelectListPreference) findPreference(EVENT_A2DP_CONNECT);
         mEnable.setChecked(getPrefs().getBoolean(EventServiceSettings.EVENT_SERVICE_ENABLED, false));
         String value = getPrefs().getString(EVENT_A2DP_CONNECT, null);
@@ -120,6 +126,10 @@
                 }
             }, 1000);
             return true;
+        } else if (preference == mAutoStart) {
+            boolean value = ((Boolean) newValue).booleanValue();
+            getPrefs().edit().putBoolean(EVENT_MEDIA_PLAYER_START, value).commit();
+            return true;
         }
         return false;
     }