Ejemplo n.º 1
0
  public static void rebuildStats(Context context, String localId) {
    Realm realm = Realm.getInstance(Migration.getConfig(context));

    RealmResults<TrackStats> statsRes =
        realm.where(TrackStats.class).equalTo("local_id", localId).findAll();

    if (!statsRes.isEmpty()) {
      /*
      Log.d(TAG, "hi5");
      Log.d(TAG, "==================");
      Log.d(TAG, "track.getTitle(): " + track.getTitle());
      Log.d(TAG, "track.getCompletedCount(): " + track.getCompletedCount());
      Log.d(TAG, "track.getSkippedCount(): " + track.getSkippedCount());
      Log.d(TAG, "track.getLikedCount(): " + track.getLikedCount());
      Log.d(TAG, "track.getDislikedCount(): " + track.getDislikedCount());

      res.where().equalTo("type", TrackStats.SONG_SELECTED) //TODO not implemented yet
       */

      int completedCount = 0;
      int skippedCount = 0;
      int likedCount = 0;
      int dislikedCount = 0;
      int halfPlayedCount = 0;
      int selectedCount = 0;

      for (TrackStats ts : statsRes) {
        switch (ts.getType()) {
          case TrackStats.SONG_COMPLETED:
            completedCount++;
            break;
          case TrackStats.SONG_HALF_PLAYED:
            halfPlayedCount++;
            break;
          case TrackStats.SONG_SELECTED:
            selectedCount++;
            break;
          case TrackStats.SONG_SKIPPED:
            skippedCount++;
            break;
          case TrackStats.SONG_LIKED:
            likedCount++;
            break;
          case TrackStats.SONG_DISLIKED:
            dislikedCount++;
            break;
        }
      }

      Track track = realm.where(Track.class).equalTo("local_id", localId).findFirst();

      realm.beginTransaction();

      track.setCompletedCount(completedCount);
      track.setHalfPlayedCount(halfPlayedCount);
      track.setSelectedCount(selectedCount);

      track.setSkippedCount(skippedCount);

      track.setLikedCount(likedCount);
      track.setDislikedCount(dislikedCount);

      track.setStatsUpdatedAt(DateTime.now(Calendar.getInstance().getTimeZone()).toString());

      realm.commitTransaction();
    }
  }
Ejemplo n.º 2
0
  public static void updateLibrary(Context context, boolean rebuildStats) {
    Log.d(TAG, "updateLibrary() start");

    Realm realm = Realm.getInstance(Migration.getConfig(context));

    realm.beginTransaction();
    RealmResults<Track> res = realm.where(Track.class).findAll();
    for (int x = 0; x < res.size(); x++) {
      res.get(x).setIsAvailable(false);
    }
    realm.commitTransaction();

    String where = MediaStore.Audio.Media.IS_MUSIC + " = 1";
    String[] selectionArgs = null;
    String orderBy = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;

    ContentResolver contentResolver = context.getContentResolver();

    Cursor[] cursors = new Cursor[2];
    cursors[0] =
        contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            TRACK_COLUMNS,
            where,
            selectionArgs,
            orderBy);

    cursors[1] =
        contentResolver.query(
            MediaStore.Audio.Media.INTERNAL_CONTENT_URI,
            TRACK_COLUMNS,
            where,
            selectionArgs,
            orderBy);

    Cursor cursor = new MergeCursor(cursors);

    int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
    int displayNameColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
    int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
    int titleKeyColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE_KEY);
    int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
    int trackColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK);
    int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
    // int dateAddedColumn 	= cursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED);
    int dataColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
    int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
    int albumIdColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
    int albumKeyColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_KEY);

    realm.beginTransaction();

    while (cursor.moveToNext()) {
      int minimumDurationToConsiderAsSong = 61500;

      Track track = null;

      String local_id =
          Track.getLocalId(
              cursor.getString(titleColumn),
              cursor.getString(artistColumn),
              cursor.getString(albumColumn));

      Track res2 = realm.where(Track.class).equalTo("local_id", local_id).findFirst();

      if (res2 != null) {
        if (cursor.getInt(durationColumn) < minimumDurationToConsiderAsSong) {
          res2.removeFromRealm();
        } else {
          track = res2;
          track.setIsAvailable(true);

          if (!track.isHidden()) {
            if (rebuildStats) {
              rebuildStats(context, track.getLocal_id());
            }
          }
        }
      } else {
        if (cursor.getInt(durationColumn) > minimumDurationToConsiderAsSong) {
          //                    Log.d(TAG, "hi6 - means its a new record");
          //                    Log.d(TAG, "cursor.getString(titleColumn): " +
          // cursor.getString(titleColumn));
          //                    Log.d(TAG, "cursor.getString(artistColumn): " +
          // cursor.getString(artistColumn));
          //                    Log.d(TAG, "cursor.getString(albumColumn): " +
          // cursor.getString(albumColumn));

          track =
              new Track(
                  cursor.getString(titleColumn),
                  cursor.getString(artistColumn),
                  cursor.getString(albumColumn),
                  cursor.getString(dataColumn));

          track.setId(cursor.getLong(idColumn));
          track.setDisplayName(cursor.getString(displayNameColumn));
          track.setTitleKey(cursor.getString(titleKeyColumn));
          track.setDuration(cursor.getInt(durationColumn));
          track.setTrackNo(cursor.getInt(trackColumn));
          track.setAlbumId(cursor.getString(albumIdColumn));
          track.setAlbumKey(cursor.getString(albumKeyColumn));

          track = realm.copyToRealm(track);
        }
      }

      if (track != null) {
        track.setPath(cursor.getString(dataColumn));
      }
    }
    realm.commitTransaction();

    cursor.close();
    Log.d(TAG, "updateLibrary() end");
  }
Ejemplo n.º 3
0
  @Override
  public void onCreate() {
    super.onCreate();

    android_id =
        Settings.Secure.getString(
            getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);

    currentPlaylist = new ArrayList<Track>();

    realm = Realm.getInstance(Migration.getConfig(this));
    tracks =
        realm.where(Track.class).equalTo("isHidden", false).equalTo("isAvailable", true).findAll();

    mOnAudioFocusChangeListener =
        new AudioManager.OnAudioFocusChangeListener() {
          @Override
          public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
              case AudioManager.AUDIOFOCUS_GAIN:
                audioFocus = true;

                mp.setVolume(1f, 1f);

                if (wasPlaying) {
                  playPause();
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS:
                audioFocus = false;
                wasPlaying = false;

                if (mp.isPlaying()) {
                  mp.stop();
                  am.abandonAudioFocus(mOnAudioFocusChangeListener);
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                audioFocus = false;
                if (mp.isPlaying()) {
                  playPause();
                }
                break;
              case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                if (mp.isPlaying()) {
                  mp.setVolume(0.2f, 0.2f);
                }
                break;
            }
          }
        };

    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mp = new MediaPlayer();
    mp.setOnPreparedListener(
        new MediaPlayer.OnPreparedListener() {
          @Override
          public void onPrepared(MediaPlayer mp) {
            sendBroadcast(new Intent().setAction(INTENT_MP_READY));

            Log.d(TAG, "mp.onPrepared!");

            mStartTime = System.currentTimeMillis();
            accumulatedPlaytimeForThisTrack = 0;

            playPause();
          }
        });

    mp.setOnCompletionListener(
        new MediaPlayer.OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mp) {
            Log.d(
                TAG,
                "onCompletion is called! I want to monitor in the future to see if when i skip a song, will this method be played");

            if (currentTrack != null) {
              createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_COMPLETED);
              prepNextSong();
            }
          }
        });

    mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

    mReceiver =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "intent.getAction(): " + intent.getAction());
            switch (intent.getAction()) {
              case MainActivity.INTENT_PLAY_PAUSE:
                playPause();
                break;
              case MainActivity.INTENT_NEXT:
                checkIfRegisterAsSkip();
                prepNextSong();
                break;
              case MainActivity.INTENT_LIKED:
                if (currentTrack != null) {
                  createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_LIKED);
                }
                break;
              case MainActivity.INTENT_DISLIKED:
                if (currentTrack != null) {
                  createTrackStats(currentTrack.getLocal_id(), TrackStats.SONG_DISLIKED);
                }
                prepNextSong();
                break;
              case INTENT_SESSION_TRACKS_GENERATED:
                prepNextSong();
                break;
              case INTENT_DISMISS_NOTIFICATION:
                stopMediaPlayerService();
                break;
              case INTENT_THERE_IS_NO_SONGS:
                stopMediaPlayerService();
                break;
              case AudioManager.ACTION_AUDIO_BECOMING_NOISY:
                pause();
                break;
              case android.content.Intent.ACTION_HEADSET_PLUG:
                int state = intent.getIntExtra("state", 4);
                if (state == 0) {
                  // unplugged
                  pause();
                } else if (state == 1) {
                  // plugged in
                  if (currentTrack != null) {
                    play();
                  }
                } else {
                  // others??
                }
                break;
            }
          }
        };

    intentFilter = new IntentFilter();
    intentFilter.addAction(MainActivity.INTENT_PLAY_PAUSE);
    intentFilter.addAction(MainActivity.INTENT_NEXT);
    intentFilter.addAction(MainActivity.INTENT_LIKED);
    intentFilter.addAction(MainActivity.INTENT_DISLIKED);
    intentFilter.addAction(INTENT_DISMISS_NOTIFICATION);
    intentFilter.addAction(INTENT_THERE_IS_NO_SONGS);
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    intentFilter.addAction(android.content.Intent.ACTION_HEADSET_PLUG);
    // intentFilter.addAction(INTENT_SESSION_TRACKS_GENERATED);

    registerReceiver(mReceiver, intentFilter);

    initNotification();
  }