Search in sources :

Example 1 with MusicSpec

use of nodomain.freeyourgadget.gadgetbridge.model.MusicSpec in project Gadgetbridge by Freeyourgadget.

the class NotificationListener method handleMediaSessionNotification.

/**
     * Try to handle media session notifications that tell info about the current play state.
     *
     * @param notification The notification to handle.
     * @return true if notification was handled, false otherwise
     */
public boolean handleMediaSessionNotification(Notification notification) {
    // this code requires Android 5.0 or newer
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return false;
    }
    MusicSpec musicSpec = new MusicSpec();
    MusicStateSpec stateSpec = new MusicStateSpec();
    Bundle extras = notification.extras;
    if (extras == null)
        return false;
    if (extras.get(Notification.EXTRA_MEDIA_SESSION) == null)
        return false;
    MediaController c;
    try {
        c = new MediaController(getApplicationContext(), (MediaSession.Token) extras.get(Notification.EXTRA_MEDIA_SESSION));
        PlaybackState s = c.getPlaybackState();
        stateSpec.position = (int) (s.getPosition() / 1000);
        stateSpec.playRate = Math.round(100 * s.getPlaybackSpeed());
        stateSpec.repeat = 1;
        stateSpec.shuffle = 1;
        switch(s.getState()) {
            case PlaybackState.STATE_PLAYING:
                stateSpec.state = MusicStateSpec.STATE_PLAYING;
                break;
            case PlaybackState.STATE_STOPPED:
                stateSpec.state = MusicStateSpec.STATE_STOPPED;
                break;
            case PlaybackState.STATE_PAUSED:
                stateSpec.state = MusicStateSpec.STATE_PAUSED;
                break;
            default:
                stateSpec.state = MusicStateSpec.STATE_UNKNOWN;
                break;
        }
        MediaMetadata d = c.getMetadata();
        if (d == null)
            return false;
        if (d.containsKey(MediaMetadata.METADATA_KEY_ARTIST))
            musicSpec.artist = d.getString(MediaMetadata.METADATA_KEY_ARTIST);
        if (d.containsKey(MediaMetadata.METADATA_KEY_ALBUM))
            musicSpec.album = d.getString(MediaMetadata.METADATA_KEY_ALBUM);
        if (d.containsKey(MediaMetadata.METADATA_KEY_TITLE))
            musicSpec.track = d.getString(MediaMetadata.METADATA_KEY_TITLE);
        if (d.containsKey(MediaMetadata.METADATA_KEY_DURATION))
            musicSpec.duration = (int) d.getLong(MediaMetadata.METADATA_KEY_DURATION) / 1000;
        if (d.containsKey(MediaMetadata.METADATA_KEY_NUM_TRACKS))
            musicSpec.trackCount = (int) d.getLong(MediaMetadata.METADATA_KEY_NUM_TRACKS);
        if (d.containsKey(MediaMetadata.METADATA_KEY_TRACK_NUMBER))
            musicSpec.trackNr = (int) d.getLong(MediaMetadata.METADATA_KEY_TRACK_NUMBER);
        // finally, tell the device about it
        GBApplication.deviceService().onSetMusicInfo(musicSpec);
        GBApplication.deviceService().onSetMusicState(stateSpec);
        return true;
    } catch (NullPointerException e) {
        return false;
    }
}
Also used : MusicStateSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec) MusicSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicSpec) MediaController(android.media.session.MediaController) Bundle(android.os.Bundle) MediaMetadata(android.media.MediaMetadata) PlaybackState(android.media.session.PlaybackState)

Example 2 with MusicSpec

use of nodomain.freeyourgadget.gadgetbridge.model.MusicSpec in project Gadgetbridge by Freeyourgadget.

the class MusicPlaybackReceiver method onReceive.

@Override
public void onReceive(Context context, Intent intent) {
    /*
        Bundle bundle = intent.getExtras();
        for (String key : bundle.keySet()) {
            Object value = bundle.get(key);
            LOG.info(String.format("%s %s (%s)", key,
                    value != null ? value.toString() : "null", value != null ? value.getClass().getName() : "no class"));
        }
        */
    MusicSpec musicSpec = new MusicSpec(lastMusicSpec);
    MusicStateSpec stateSpec = new MusicStateSpec(lastStateSpec);
    Bundle incomingBundle = intent.getExtras();
    if (incomingBundle == null) {
        LOG.warn("Not processing incoming null bundle.");
        return;
    }
    for (String key : incomingBundle.keySet()) {
        Object incoming = incomingBundle.get(key);
        if (incoming instanceof String && "artist".equals(key)) {
            musicSpec.artist = (String) incoming;
        } else if (incoming instanceof String && "album".equals(key)) {
            musicSpec.album = (String) incoming;
        } else if (incoming instanceof String && "track".equals(key)) {
            musicSpec.track = (String) incoming;
        } else if (incoming instanceof String && "title".equals(key) && musicSpec.track == null) {
            musicSpec.track = (String) incoming;
        } else if (incoming instanceof Integer && "duration".equals(key)) {
            musicSpec.duration = (Integer) incoming / 1000;
        } else if (incoming instanceof Long && "duration".equals(key)) {
            musicSpec.duration = ((Long) incoming).intValue() / 1000;
        } else if (incoming instanceof Integer && "position".equals(key)) {
            stateSpec.position = (Integer) incoming / 1000;
        } else if (incoming instanceof Long && "position".equals(key)) {
            stateSpec.position = ((Long) incoming).intValue() / 1000;
        } else if (incoming instanceof Boolean && "playing".equals(key)) {
            stateSpec.state = (byte) (((Boolean) incoming) ? MusicStateSpec.STATE_PLAYING : MusicStateSpec.STATE_PAUSED);
            stateSpec.playRate = (byte) (((Boolean) incoming) ? 100 : 0);
        } else if (incoming instanceof String && "duration".equals(key)) {
            musicSpec.duration = Integer.parseInt((String) incoming) / 1000;
        } else if (incoming instanceof String && "trackno".equals(key)) {
            musicSpec.trackNr = Integer.parseInt((String) incoming);
        } else if (incoming instanceof String && "totaltrack".equals(key)) {
            musicSpec.trackCount = Integer.parseInt((String) incoming);
        } else if (incoming instanceof Integer && "pos".equals(key)) {
            stateSpec.position = (Integer) incoming;
        } else if (incoming instanceof Integer && "repeat".equals(key)) {
            if ((Integer) incoming > 0) {
                stateSpec.repeat = 1;
            } else {
                stateSpec.repeat = 0;
            }
        } else if (incoming instanceof Integer && "shuffle".equals(key)) {
            if ((Integer) incoming > 0) {
                stateSpec.shuffle = 1;
            } else {
                stateSpec.shuffle = 0;
            }
        }
    }
    if (!lastMusicSpec.equals(musicSpec)) {
        lastMusicSpec = musicSpec;
        LOG.info("Update Music Info: " + musicSpec.artist + " / " + musicSpec.album + " / " + musicSpec.track);
        GBApplication.deviceService().onSetMusicInfo(musicSpec);
    } else {
        LOG.info("Got metadata changed intent, but nothing changed, ignoring.");
    }
    if (!lastStateSpec.equals(stateSpec)) {
        lastStateSpec = stateSpec;
        LOG.info("Update Music State: state=" + stateSpec.state + ", position= " + stateSpec.position);
        GBApplication.deviceService().onSetMusicState(stateSpec);
    } else {
        LOG.info("Got state changed intent, but not enough has changed, ignoring.");
    }
}
Also used : MusicStateSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec) MusicSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicSpec) Bundle(android.os.Bundle)

Example 3 with MusicSpec

use of nodomain.freeyourgadget.gadgetbridge.model.MusicSpec in project Gadgetbridge by Freeyourgadget.

the class NotificationListener method handleMediaSessionNotification.

/**
 * Try to handle media session notifications that tell info about the current play state.
 *
 * @param mediaSession The mediasession to handle.
 * @return true if notification was handled, false otherwise
 */
public boolean handleMediaSessionNotification(MediaSessionCompat.Token mediaSession) {
    final MusicSpec musicSpec = new MusicSpec();
    final MusicStateSpec stateSpec = new MusicStateSpec();
    MediaControllerCompat c;
    try {
        c = new MediaControllerCompat(getApplicationContext(), mediaSession);
        PlaybackStateCompat s = c.getPlaybackState();
        stateSpec.position = (int) (s.getPosition() / 1000);
        stateSpec.playRate = Math.round(100 * s.getPlaybackSpeed());
        stateSpec.repeat = 1;
        stateSpec.shuffle = 1;
        switch(s.getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
                stateSpec.state = MusicStateSpec.STATE_PLAYING;
                break;
            case PlaybackStateCompat.STATE_STOPPED:
                stateSpec.state = MusicStateSpec.STATE_STOPPED;
                break;
            case PlaybackStateCompat.STATE_PAUSED:
                stateSpec.state = MusicStateSpec.STATE_PAUSED;
                break;
            default:
                stateSpec.state = MusicStateSpec.STATE_UNKNOWN;
                break;
        }
        MediaMetadataCompat d = c.getMetadata();
        if (d == null)
            return false;
        if (d.containsKey(MediaMetadata.METADATA_KEY_ARTIST))
            musicSpec.artist = d.getString(MediaMetadataCompat.METADATA_KEY_ARTIST);
        if (d.containsKey(MediaMetadata.METADATA_KEY_ALBUM))
            musicSpec.album = d.getString(MediaMetadataCompat.METADATA_KEY_ALBUM);
        if (d.containsKey(MediaMetadata.METADATA_KEY_TITLE))
            musicSpec.track = d.getString(MediaMetadataCompat.METADATA_KEY_TITLE);
        if (d.containsKey(MediaMetadata.METADATA_KEY_DURATION))
            musicSpec.duration = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_DURATION) / 1000;
        if (d.containsKey(MediaMetadata.METADATA_KEY_NUM_TRACKS))
            musicSpec.trackCount = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS);
        if (d.containsKey(MediaMetadata.METADATA_KEY_TRACK_NUMBER))
            musicSpec.trackNr = (int) d.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER);
        // finally, tell the device about it
        if (mSetMusicInfoRunnable != null) {
            mHandler.removeCallbacks(mSetMusicInfoRunnable);
        }
        mSetMusicInfoRunnable = new Runnable() {

            @Override
            public void run() {
                GBApplication.deviceService().onSetMusicInfo(musicSpec);
            }
        };
        mHandler.postDelayed(mSetMusicInfoRunnable, 100);
        if (mSetMusicStateRunnable != null) {
            mHandler.removeCallbacks(mSetMusicStateRunnable);
        }
        mSetMusicStateRunnable = new Runnable() {

            @Override
            public void run() {
                GBApplication.deviceService().onSetMusicState(stateSpec);
            }
        };
        mHandler.postDelayed(mSetMusicStateRunnable, 100);
        return true;
    } catch (NullPointerException | RemoteException | SecurityException e) {
        return false;
    }
}
Also used : MusicStateSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec) PlaybackStateCompat(android.support.v4.media.session.PlaybackStateCompat) MediaMetadataCompat(android.support.v4.media.MediaMetadataCompat) MusicSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicSpec) MediaControllerCompat(android.support.v4.media.session.MediaControllerCompat) RemoteException(android.os.RemoteException)

Example 4 with MusicSpec

use of nodomain.freeyourgadget.gadgetbridge.model.MusicSpec in project Gadgetbridge by Freeyourgadget.

the class DeviceCommunicationService method handleAction.

private void handleAction(Intent intent, String action, Prefs prefs) {
    Prefs devicePrefs = new Prefs(GBApplication.getDeviceSpecificSharedPrefs(mGBDevice.getAddress()));
    boolean transliterate = devicePrefs.getBoolean(PREF_TRANSLITERATION_ENABLED, false);
    if (transliterate) {
        for (String extra : GBDeviceService.transliterationExtras) {
            if (intent.hasExtra(extra)) {
                intent.putExtra(extra, LanguageUtils.transliterate(intent.getStringExtra(extra)));
            }
        }
    }
    switch(action) {
        case ACTION_REQUEST_DEVICEINFO:
            mGBDevice.sendDeviceUpdateIntent(this);
            break;
        case ACTION_NOTIFICATION:
            {
                int desiredId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1);
                NotificationSpec notificationSpec = new NotificationSpec(desiredId);
                notificationSpec.phoneNumber = intent.getStringExtra(EXTRA_NOTIFICATION_PHONENUMBER);
                notificationSpec.sender = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SENDER));
                notificationSpec.subject = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_SUBJECT));
                notificationSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_TITLE));
                notificationSpec.body = sanitizeNotifText(intent.getStringExtra(EXTRA_NOTIFICATION_BODY));
                notificationSpec.sourceName = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCENAME);
                notificationSpec.type = (NotificationType) intent.getSerializableExtra(EXTRA_NOTIFICATION_TYPE);
                notificationSpec.attachedActions = (ArrayList<NotificationSpec.Action>) intent.getSerializableExtra(EXTRA_NOTIFICATION_ACTIONS);
                notificationSpec.pebbleColor = (byte) intent.getSerializableExtra(EXTRA_NOTIFICATION_PEBBLE_COLOR);
                notificationSpec.flags = intent.getIntExtra(EXTRA_NOTIFICATION_FLAGS, 0);
                notificationSpec.sourceAppId = intent.getStringExtra(EXTRA_NOTIFICATION_SOURCEAPPID);
                notificationSpec.iconId = intent.getIntExtra(EXTRA_NOTIFICATION_ICONID, 0);
                notificationSpec.dndSuppressed = intent.getIntExtra(EXTRA_NOTIFICATION_DNDSUPPRESSED, 0);
                if (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null) {
                    GBApplication.getIDSenderLookup().add(notificationSpec.getId(), notificationSpec.phoneNumber);
                }
                // TODO: check if at least one of the attached actions is a reply action instead?
                if ((notificationSpec.attachedActions != null && notificationSpec.attachedActions.size() > 0) || (notificationSpec.type == NotificationType.GENERIC_SMS && notificationSpec.phoneNumber != null)) {
                    // NOTE: maybe not where it belongs
                    // I would rather like to save that as an array in SharedPreferences
                    // this would work but I dont know how to do the same in the Settings Activity's xml
                    ArrayList<String> replies = new ArrayList<>();
                    for (int i = 1; i <= 16; i++) {
                        String reply = devicePrefs.getString("canned_reply_" + i, null);
                        if (reply != null && !reply.equals("")) {
                            replies.add(reply);
                        }
                    }
                    notificationSpec.cannedReplies = replies.toArray(new String[0]);
                }
                mDeviceSupport.onNotification(notificationSpec);
                break;
            }
        case ACTION_DELETE_NOTIFICATION:
            {
                mDeviceSupport.onDeleteNotification(intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1));
                break;
            }
        case ACTION_ADD_CALENDAREVENT:
            {
                CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
                calendarEventSpec.id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
                calendarEventSpec.type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
                calendarEventSpec.timestamp = intent.getIntExtra(EXTRA_CALENDAREVENT_TIMESTAMP, -1);
                calendarEventSpec.durationInSeconds = intent.getIntExtra(EXTRA_CALENDAREVENT_DURATION, -1);
                calendarEventSpec.title = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_TITLE));
                calendarEventSpec.description = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_DESCRIPTION));
                calendarEventSpec.location = sanitizeNotifText(intent.getStringExtra(EXTRA_CALENDAREVENT_LOCATION));
                mDeviceSupport.onAddCalendarEvent(calendarEventSpec);
                break;
            }
        case ACTION_DELETE_CALENDAREVENT:
            {
                long id = intent.getLongExtra(EXTRA_CALENDAREVENT_ID, -1);
                byte type = intent.getByteExtra(EXTRA_CALENDAREVENT_TYPE, (byte) -1);
                mDeviceSupport.onDeleteCalendarEvent(type, id);
                break;
            }
        case ACTION_RESET:
            {
                int flags = intent.getIntExtra(EXTRA_RESET_FLAGS, 0);
                mDeviceSupport.onReset(flags);
                break;
            }
        case ACTION_HEARTRATE_TEST:
            {
                mDeviceSupport.onHeartRateTest();
                break;
            }
        case ACTION_FETCH_RECORDED_DATA:
            {
                int dataTypes = intent.getIntExtra(EXTRA_RECORDED_DATA_TYPES, 0);
                mDeviceSupport.onFetchRecordedData(dataTypes);
                break;
            }
        case ACTION_DISCONNECT:
            {
                mDeviceSupport.dispose();
                if (mGBDevice != null) {
                    mGBDevice.setState(GBDevice.State.NOT_CONNECTED);
                    mGBDevice.sendDeviceUpdateIntent(this);
                }
                setReceiversEnableState(false, false, null);
                mGBDevice = null;
                mDeviceSupport = null;
                mCoordinator = null;
                break;
            }
        case ACTION_FIND_DEVICE:
            {
                boolean start = intent.getBooleanExtra(EXTRA_FIND_START, false);
                mDeviceSupport.onFindDevice(start);
                break;
            }
        case ACTION_SET_CONSTANT_VIBRATION:
            {
                int intensity = intent.getIntExtra(EXTRA_VIBRATION_INTENSITY, 0);
                mDeviceSupport.onSetConstantVibration(intensity);
                break;
            }
        case ACTION_CALLSTATE:
            CallSpec callSpec = new CallSpec();
            callSpec.command = intent.getIntExtra(EXTRA_CALL_COMMAND, CallSpec.CALL_UNDEFINED);
            callSpec.number = intent.getStringExtra(EXTRA_CALL_PHONENUMBER);
            callSpec.name = sanitizeNotifText(intent.getStringExtra(EXTRA_CALL_DISPLAYNAME));
            mDeviceSupport.onSetCallState(callSpec);
            break;
        case ACTION_SETCANNEDMESSAGES:
            int type = intent.getIntExtra(EXTRA_CANNEDMESSAGES_TYPE, -1);
            String[] cannedMessages = intent.getStringArrayExtra(EXTRA_CANNEDMESSAGES);
            CannedMessagesSpec cannedMessagesSpec = new CannedMessagesSpec();
            cannedMessagesSpec.type = type;
            cannedMessagesSpec.cannedMessages = cannedMessages;
            mDeviceSupport.onSetCannedMessages(cannedMessagesSpec);
            break;
        case ACTION_SETTIME:
            mDeviceSupport.onSetTime();
            break;
        case ACTION_SETMUSICINFO:
            MusicSpec musicSpec = new MusicSpec();
            musicSpec.artist = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ARTIST));
            musicSpec.album = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_ALBUM));
            musicSpec.track = sanitizeNotifText(intent.getStringExtra(EXTRA_MUSIC_TRACK));
            musicSpec.duration = intent.getIntExtra(EXTRA_MUSIC_DURATION, 0);
            musicSpec.trackCount = intent.getIntExtra(EXTRA_MUSIC_TRACKCOUNT, 0);
            musicSpec.trackNr = intent.getIntExtra(EXTRA_MUSIC_TRACKNR, 0);
            mDeviceSupport.onSetMusicInfo(musicSpec);
            break;
        case ACTION_SETMUSICSTATE:
            MusicStateSpec stateSpec = new MusicStateSpec();
            stateSpec.shuffle = intent.getByteExtra(EXTRA_MUSIC_SHUFFLE, (byte) 0);
            stateSpec.repeat = intent.getByteExtra(EXTRA_MUSIC_REPEAT, (byte) 0);
            stateSpec.position = intent.getIntExtra(EXTRA_MUSIC_POSITION, 0);
            stateSpec.playRate = intent.getIntExtra(EXTRA_MUSIC_RATE, 0);
            stateSpec.state = intent.getByteExtra(EXTRA_MUSIC_STATE, (byte) 0);
            mDeviceSupport.onSetMusicState(stateSpec);
            break;
        case ACTION_REQUEST_APPINFO:
            mDeviceSupport.onAppInfoReq();
            break;
        case ACTION_REQUEST_SCREENSHOT:
            mDeviceSupport.onScreenshotReq();
            break;
        case ACTION_STARTAPP:
            {
                UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
                boolean start = intent.getBooleanExtra(EXTRA_APP_START, true);
                mDeviceSupport.onAppStart(uuid, start);
                break;
            }
        case ACTION_DELETEAPP:
            {
                UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
                mDeviceSupport.onAppDelete(uuid);
                break;
            }
        case ACTION_APP_CONFIGURE:
            {
                UUID uuid = (UUID) intent.getSerializableExtra(EXTRA_APP_UUID);
                String config = intent.getStringExtra(EXTRA_APP_CONFIG);
                Integer id = null;
                if (intent.hasExtra(EXTRA_APP_CONFIG_ID)) {
                    id = intent.getIntExtra(EXTRA_APP_CONFIG_ID, 0);
                }
                mDeviceSupport.onAppConfiguration(uuid, config, id);
                break;
            }
        case ACTION_APP_REORDER:
            {
                UUID[] uuids = (UUID[]) intent.getSerializableExtra(EXTRA_APP_UUID);
                mDeviceSupport.onAppReorder(uuids);
                break;
            }
        case ACTION_INSTALL:
            Uri uri = intent.getParcelableExtra(EXTRA_URI);
            if (uri != null) {
                LOG.info("will try to install app/fw");
                mDeviceSupport.onInstallApp(uri);
            }
            break;
        case ACTION_SET_ALARMS:
            ArrayList<? extends Alarm> alarms = (ArrayList<? extends Alarm>) intent.getSerializableExtra(EXTRA_ALARMS);
            mDeviceSupport.onSetAlarms(alarms);
            break;
        case ACTION_SET_REMINDERS:
            ArrayList<? extends Reminder> reminders = (ArrayList<? extends Reminder>) intent.getSerializableExtra(EXTRA_REMINDERS);
            mDeviceSupport.onSetReminders(reminders);
            break;
        case ACTION_ENABLE_REALTIME_STEPS:
            {
                boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
                mDeviceSupport.onEnableRealtimeSteps(enable);
                break;
            }
        case ACTION_ENABLE_HEARTRATE_SLEEP_SUPPORT:
            {
                boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
                mDeviceSupport.onEnableHeartRateSleepSupport(enable);
                break;
            }
        case ACTION_SET_HEARTRATE_MEASUREMENT_INTERVAL:
            {
                int seconds = intent.getIntExtra(EXTRA_INTERVAL_SECONDS, 0);
                mDeviceSupport.onSetHeartRateMeasurementInterval(seconds);
                break;
            }
        case ACTION_ENABLE_REALTIME_HEARTRATE_MEASUREMENT:
            {
                boolean enable = intent.getBooleanExtra(EXTRA_BOOLEAN_ENABLE, false);
                mDeviceSupport.onEnableRealtimeHeartRateMeasurement(enable);
                break;
            }
        case ACTION_SEND_CONFIGURATION:
            {
                String config = intent.getStringExtra(EXTRA_CONFIG);
                mDeviceSupport.onSendConfiguration(config);
                break;
            }
        case ACTION_READ_CONFIGURATION:
            {
                String config = intent.getStringExtra(EXTRA_CONFIG);
                mDeviceSupport.onReadConfiguration(config);
                break;
            }
        case ACTION_TEST_NEW_FUNCTION:
            {
                mDeviceSupport.onTestNewFunction();
                break;
            }
        case ACTION_SEND_WEATHER:
            {
                WeatherSpec weatherSpec = intent.getParcelableExtra(EXTRA_WEATHER);
                if (weatherSpec != null) {
                    mDeviceSupport.onSendWeather(weatherSpec);
                }
                break;
            }
        case ACTION_SET_LED_COLOR:
            int color = intent.getIntExtra(EXTRA_LED_COLOR, 0);
            if (color != 0) {
                mDeviceSupport.onSetLedColor(color);
            }
            break;
        case ACTION_POWER_OFF:
            mDeviceSupport.onPowerOff();
            break;
        case ACTION_SET_FM_FREQUENCY:
            float frequency = intent.getFloatExtra(EXTRA_FM_FREQUENCY, -1);
            if (frequency != -1) {
                mDeviceSupport.onSetFmFrequency(frequency);
            }
            break;
    }
}
Also used : Reminder(nodomain.freeyourgadget.gadgetbridge.model.Reminder) ArrayList(java.util.ArrayList) Prefs(nodomain.freeyourgadget.gadgetbridge.util.Prefs) GBPrefs(nodomain.freeyourgadget.gadgetbridge.util.GBPrefs) Uri(android.net.Uri) SuppressLint(android.annotation.SuppressLint) MusicStateSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec) MusicSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicSpec) CallSpec(nodomain.freeyourgadget.gadgetbridge.model.CallSpec) NotificationSpec(nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec) NotificationType(nodomain.freeyourgadget.gadgetbridge.model.NotificationType) Alarm(nodomain.freeyourgadget.gadgetbridge.model.Alarm) WeatherSpec(nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec) CannedMessagesSpec(nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec) EXTRA_APP_UUID(nodomain.freeyourgadget.gadgetbridge.model.DeviceService.EXTRA_APP_UUID) UUID(java.util.UUID) CalendarEventSpec(nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec)

Example 5 with MusicSpec

use of nodomain.freeyourgadget.gadgetbridge.model.MusicSpec in project Gadgetbridge by Freeyourgadget.

the class DebugActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_debug);
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_REPLY);
    filter.addAction(DeviceService.ACTION_REALTIME_SAMPLES);
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
    // for ACTION_REPLY
    registerReceiver(mReceiver, filter);
    editContent = findViewById(R.id.editContent);
    final ArrayList<String> spinnerArray = new ArrayList<>();
    for (NotificationType notificationType : NotificationType.values()) {
        spinnerArray.add(notificationType.name());
    }
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
    sendTypeSpinner = findViewById(R.id.sendTypeSpinner);
    sendTypeSpinner.setAdapter(spinnerArrayAdapter);
    Button sendButton = findViewById(R.id.sendButton);
    sendButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            NotificationSpec notificationSpec = new NotificationSpec();
            String testString = editContent.getText().toString();
            notificationSpec.phoneNumber = testString;
            notificationSpec.body = testString;
            notificationSpec.sender = testString;
            notificationSpec.subject = testString;
            notificationSpec.type = NotificationType.values()[sendTypeSpinner.getSelectedItemPosition()];
            notificationSpec.pebbleColor = notificationSpec.type.color;
            GBApplication.deviceService().onNotification(notificationSpec);
        }
    });
    Button incomingCallButton = findViewById(R.id.incomingCallButton);
    incomingCallButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CallSpec callSpec = new CallSpec();
            callSpec.command = CallSpec.CALL_INCOMING;
            callSpec.number = editContent.getText().toString();
            GBApplication.deviceService().onSetCallState(callSpec);
        }
    });
    Button outgoingCallButton = findViewById(R.id.outgoingCallButton);
    outgoingCallButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CallSpec callSpec = new CallSpec();
            callSpec.command = CallSpec.CALL_OUTGOING;
            callSpec.number = editContent.getText().toString();
            GBApplication.deviceService().onSetCallState(callSpec);
        }
    });
    Button startCallButton = findViewById(R.id.startCallButton);
    startCallButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CallSpec callSpec = new CallSpec();
            callSpec.command = CallSpec.CALL_START;
            GBApplication.deviceService().onSetCallState(callSpec);
        }
    });
    Button endCallButton = findViewById(R.id.endCallButton);
    endCallButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            CallSpec callSpec = new CallSpec();
            callSpec.command = CallSpec.CALL_END;
            GBApplication.deviceService().onSetCallState(callSpec);
        }
    });
    Button rebootButton = findViewById(R.id.rebootButton);
    rebootButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GBApplication.deviceService().onReset(GBDeviceProtocol.RESET_FLAGS_REBOOT);
        }
    });
    Button factoryResetButton = findViewById(R.id.factoryResetButton);
    factoryResetButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(DebugActivity.this).setCancelable(true).setTitle(R.string.debugactivity_really_factoryreset_title).setMessage(R.string.debugactivity_really_factoryreset).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    GBApplication.deviceService().onReset(GBDeviceProtocol.RESET_FLAGS_FACTORY_RESET);
                }
            }).setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).show();
        }
    });
    Button heartRateButton = findViewById(R.id.HeartRateButton);
    heartRateButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GB.toast("Measuring heart rate, please wait...", Toast.LENGTH_LONG, GB.INFO);
            GBApplication.deviceService().onHeartRateTest();
        }
    });
    Button setFetchTimeButton = findViewById(R.id.SetFetchTimeButton);
    setFetchTimeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            final Calendar currentDate = Calendar.getInstance();
            Context context = getApplicationContext();
            if (context instanceof GBApplication) {
                GBApplication gbApp = (GBApplication) context;
                final GBDevice device = gbApp.getDeviceManager().getSelectedDevice();
                if (device != null) {
                    new DatePickerDialog(DebugActivity.this, new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            Calendar date = Calendar.getInstance();
                            date.set(year, monthOfYear, dayOfMonth);
                            long timestamp = date.getTimeInMillis() - 1000;
                            GB.toast("Setting lastSyncTimeMillis: " + timestamp, Toast.LENGTH_LONG, GB.INFO);
                            SharedPreferences.Editor editor = GBApplication.getDeviceSpecificSharedPrefs(device.getAddress()).edit();
                            // FIXME: key reconstruction is BAD
                            editor.remove("lastSyncTimeMillis");
                            editor.putLong("lastSyncTimeMillis", timestamp);
                            editor.apply();
                        }
                    }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
                } else {
                    GB.toast("Device not selected/connected", Toast.LENGTH_LONG, GB.INFO);
                }
            }
        }
    });
    Button setMusicInfoButton = findViewById(R.id.setMusicInfoButton);
    setMusicInfoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MusicSpec musicSpec = new MusicSpec();
            String testString = editContent.getText().toString();
            musicSpec.artist = testString + "(artist)";
            musicSpec.album = testString + "(album)";
            musicSpec.track = testString + "(track)";
            musicSpec.duration = 10;
            musicSpec.trackCount = 5;
            musicSpec.trackNr = 2;
            GBApplication.deviceService().onSetMusicInfo(musicSpec);
            MusicStateSpec stateSpec = new MusicStateSpec();
            stateSpec.position = 0;
            // playing
            stateSpec.state = 0x01;
            stateSpec.playRate = 100;
            stateSpec.repeat = 1;
            stateSpec.shuffle = 1;
            GBApplication.deviceService().onSetMusicState(stateSpec);
        }
    });
    Button setTimeButton = findViewById(R.id.setTimeButton);
    setTimeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GBApplication.deviceService().onSetTime();
        }
    });
    Button testNotificationButton = findViewById(R.id.testNotificationButton);
    testNotificationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            testNotification();
        }
    });
    Button testPebbleKitNotificationButton = findViewById(R.id.testPebbleKitNotificationButton);
    testPebbleKitNotificationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            testPebbleKitNotification();
        }
    });
    Button fetchDebugLogsButton = findViewById(R.id.fetchDebugLogsButton);
    fetchDebugLogsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GBApplication.deviceService().onFetchRecordedData(RecordedDataTypes.TYPE_DEBUGLOGS);
        }
    });
    Button testNewFunctionalityButton = findViewById(R.id.testNewFunctionality);
    testNewFunctionalityButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            testNewFunctionality();
        }
    });
    Button shareLogButton = findViewById(R.id.shareLog);
    shareLogButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showWarning();
        }
    });
    Button showWidgetsButton = findViewById(R.id.showWidgetsButton);
    showWidgetsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showAllRegisteredAppWidgets();
        }
    });
    Button unregisterWidgetsButton = findViewById(R.id.deleteWidgets);
    unregisterWidgetsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            unregisterAllRegisteredAppWidgets();
        }
    });
    Button showWidgetsPrefsButton = findViewById(R.id.showWidgetsPrefs);
    showWidgetsPrefsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showAppWidgetsPrefs();
        }
    });
    Button deleteWidgetsPrefsButton = findViewById(R.id.deleteWidgetsPrefs);
    deleteWidgetsPrefsButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            deleteWidgetsPrefs();
        }
    });
    Button removeDevicePreferencesButton = findViewById(R.id.removeDevicePreferences);
    removeDevicePreferencesButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Context context = getApplicationContext();
            GBApplication gbApp = (GBApplication) context;
            final GBDevice device = gbApp.getDeviceManager().getSelectedDevice();
            if (device != null) {
                GBApplication.deleteDeviceSpecificSharedPrefs(device.getAddress());
            }
        }
    });
    Button runDebugFunction = findViewById(R.id.runDebugFunction);
    runDebugFunction.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // SharedPreferences.Editor editor = GBApplication.getPrefs().getPreferences().edit();
        // editor.remove("notification_list_is_blacklist").apply();
        }
    });
    Button addDeviceButtonDebug = findViewById(R.id.addDeviceButtonDebug);
    addDeviceButtonDebug.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            LinkedHashMap<String, Pair<Long, Integer>> allDevices;
            allDevices = getAllSupportedDevices(getApplicationContext());
            final LinearLayout linearLayout = new LinearLayout(DebugActivity.this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            final LinearLayout macLayout = new LinearLayout(DebugActivity.this);
            macLayout.setOrientation(LinearLayout.HORIZONTAL);
            macLayout.setPadding(20, 0, 20, 0);
            final TextView textView = new TextView(DebugActivity.this);
            textView.setText("MAC Address: ");
            final EditText editText = new EditText(DebugActivity.this);
            selectedTestDeviceMAC = randomMac();
            editText.setText(selectedTestDeviceMAC);
            editText.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    selectedTestDeviceMAC = editable.toString();
                }
            });
            macLayout.addView(textView);
            macLayout.addView(editText);
            final Spinner deviceListSpinner = new Spinner(DebugActivity.this);
            ArrayList<SpinnerWithIconItem> deviceListArray = new ArrayList<>();
            for (Map.Entry<String, Pair<Long, Integer>> item : allDevices.entrySet()) {
                deviceListArray.add(new SpinnerWithIconItem(item.getKey(), item.getValue().first, item.getValue().second));
            }
            final SpinnerWithIconAdapter deviceListAdapter = new SpinnerWithIconAdapter(DebugActivity.this, R.layout.spinner_with_image_layout, R.id.spinner_item_text, deviceListArray);
            deviceListSpinner.setAdapter(deviceListAdapter);
            addListenerOnSpinnerDeviceSelection(deviceListSpinner);
            linearLayout.addView(deviceListSpinner);
            linearLayout.addView(macLayout);
            new AlertDialog.Builder(DebugActivity.this).setCancelable(true).setTitle(R.string.add_test_device).setView(linearLayout).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    createTestDevice(DebugActivity.this, selectedTestDeviceKey, selectedTestDeviceMAC);
                }
            }).setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).show();
        }
    });
    CheckBox activity_list_debug_extra_time_range = findViewById(R.id.activity_list_debug_extra_time_range);
    activity_list_debug_extra_time_range.setAllCaps(true);
    boolean activity_list_debug_extra_time_range_value = GBApplication.getPrefs().getPreferences().getBoolean("activity_list_debug_extra_time_range", false);
    activity_list_debug_extra_time_range.setChecked(activity_list_debug_extra_time_range_value);
    activity_list_debug_extra_time_range.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            GBApplication.getPrefs().getPreferences().getBoolean("activity_list_debug_extra_time_range", false);
            SharedPreferences.Editor editor = GBApplication.getPrefs().getPreferences().edit();
            editor.putBoolean("activity_list_debug_extra_time_range", b).apply();
        }
    });
}
Also used : AlertDialog(android.app.AlertDialog) GBApplication(nodomain.freeyourgadget.gadgetbridge.GBApplication) DialogInterface(android.content.DialogInterface) Spinner(android.widget.Spinner) ArrayList(java.util.ArrayList) SpinnerWithIconItem(nodomain.freeyourgadget.gadgetbridge.adapter.SpinnerWithIconItem) GBDevice(nodomain.freeyourgadget.gadgetbridge.impl.GBDevice) LinkedHashMap(java.util.LinkedHashMap) MusicStateSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec) MusicSpec(nodomain.freeyourgadget.gadgetbridge.model.MusicSpec) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) CallSpec(nodomain.freeyourgadget.gadgetbridge.model.CallSpec) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) Context(android.content.Context) EditText(android.widget.EditText) IntentFilter(android.content.IntentFilter) DatePickerDialog(android.app.DatePickerDialog) Calendar(java.util.Calendar) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) CheckBox(android.widget.CheckBox) NotificationType(nodomain.freeyourgadget.gadgetbridge.model.NotificationType) NotificationSpec(nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec) DatePicker(android.widget.DatePicker) ArrayAdapter(android.widget.ArrayAdapter) LinearLayout(android.widget.LinearLayout) SpinnerWithIconAdapter(nodomain.freeyourgadget.gadgetbridge.adapter.SpinnerWithIconAdapter) CompoundButton(android.widget.CompoundButton)

Aggregations

MusicSpec (nodomain.freeyourgadget.gadgetbridge.model.MusicSpec)5 MusicStateSpec (nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec)5 Bundle (android.os.Bundle)2 ArrayList (java.util.ArrayList)2 CallSpec (nodomain.freeyourgadget.gadgetbridge.model.CallSpec)2 NotificationSpec (nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec)2 NotificationType (nodomain.freeyourgadget.gadgetbridge.model.NotificationType)2 SuppressLint (android.annotation.SuppressLint)1 AlertDialog (android.app.AlertDialog)1 DatePickerDialog (android.app.DatePickerDialog)1 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 IntentFilter (android.content.IntentFilter)1 MediaMetadata (android.media.MediaMetadata)1 MediaController (android.media.session.MediaController)1 PlaybackState (android.media.session.PlaybackState)1 Uri (android.net.Uri)1 RemoteException (android.os.RemoteException)1 MediaMetadataCompat (android.support.v4.media.MediaMetadataCompat)1 MediaControllerCompat (android.support.v4.media.session.MediaControllerCompat)1