Beispiel #1
1
  private void showNotification() {
    try {
      // add notification to status bar
      NotificationCompat.Builder builder =
          new NotificationCompat.Builder(this)
              .setSmallIcon(R.drawable.icon)
              .setLargeIcon(AudioUtil.getCover(this, mCurrentMedia, 64))
              .setContentTitle(mCurrentMedia.getTitle())
              .setTicker(mCurrentMedia.getTitle() + " - " + mCurrentMedia.getArtist())
              .setContentText(
                  Util.isJellyBeanOrLater()
                      ? mCurrentMedia.getArtist()
                      : mCurrentMedia.getSubtitle())
              .setContentInfo(mCurrentMedia.getAlbum())
              .setAutoCancel(false)
              .setOngoing(true);

      Intent notificationIntent = new Intent(this, AudioPlayerActivity.class);
      notificationIntent.setAction(Intent.ACTION_MAIN);
      notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
      notificationIntent.putExtra(START_FROM_NOTIFICATION, true);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

      builder.setContentIntent(pendingIntent);
      startForeground(3, builder.build());
    } catch (NoSuchMethodError e) {
      // Compat library is wrong on 3.2
      // http://code.google.com/p/android/issues/detail?id=36359
      // http://code.google.com/p/android/issues/detail?id=36502
    }
  }
Beispiel #2
0
  public Media(
      Context context,
      String location,
      long time,
      long length,
      int type,
      Bitmap picture,
      String title,
      String artist,
      String genre,
      String album,
      int width,
      int height,
      String artworkURL) {
    mLocation = location;
    mFilename = null;
    mTime = time;
    mLength = length;
    mType = type;
    mPicture = picture;
    mWidth = width;
    mHeight = height;

    mTitle = title;
    mArtist = Util.getValue(artist, R.string.unknown_artist);
    mGenre = Util.getValue(genre, R.string.unknown_genre);
    mAlbum = Util.getValue(album, R.string.unknown_album);
    mArtworkURL = artworkURL;
  }
Beispiel #3
0
  /**
   * Set up the remote control and tell the system we want to be the default receiver for the MEDIA
   * buttons
   *
   * @see http://android-developers.blogspot.fr/2010/06/allowing-applications-to-play-nicer.html
   */
  @TargetApi(14)
  public void setUpRemoteControlClient() {
    Context context = VLCApplication.getAppContext();
    AudioManager audioManager = (AudioManager) context.getSystemService(AUDIO_SERVICE);

    if (Util.isICSOrLater()) {
      audioManager.registerMediaButtonEventReceiver(mRemoteControlClientReceiverComponent);

      if (mRemoteControlClient == null) {
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mRemoteControlClientReceiverComponent);
        PendingIntent mediaPendingIntent =
            PendingIntent.getBroadcast(context, 0, mediaButtonIntent, 0);

        // create and register the remote control client
        mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);
        audioManager.registerRemoteControlClient(mRemoteControlClient);
      }

      mRemoteControlClient.setTransportControlFlags(
          RemoteControlClient.FLAG_KEY_MEDIA_PLAY
              | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
              | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
              | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
              | RemoteControlClient.FLAG_KEY_MEDIA_STOP);
    } else if (Util.isFroyoOrLater()) {
      audioManager.registerMediaButtonEventReceiver(mRemoteControlClientReceiverComponent);
    }
  }
 private String getParentDir(String path) {
   try {
     path = new URI(Util.PathToURI(path + "/..")).normalize().getPath();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return Util.stripTrailingSlash(path);
 }
 @Override
 public View onCreateView(
     LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   super.onCreateView(inflater, container, savedInstanceState);
   View v = inflater.inflate(R.layout.about_licence, container, false);
   String revision = Util.readAsset("revision.txt", "Unknown revision");
   WebView t = (WebView) v.findViewById(R.id.webview);
   t.loadData(
       Util.readAsset("licence.htm", "").replace("!COMMITID!", revision), "text/html", "UTF8");
   return v;
 }
Beispiel #6
0
  @SuppressLint("NewApi")
  public static void prepareCacheFolder(Context context) {
    if (Util.isFroyoOrLater() && Util.hasExternalStorage() && context.getExternalCacheDir() != null)
      CACHE_DIR = context.getExternalCacheDir().getPath();
    else
      CACHE_DIR =
          Environment.getExternalStorageDirectory().getPath()
              + "/Android/data/"
              + context.getPackageName()
              + "/cache";
    COVER_DIR = CACHE_DIR + "/covers/";

    File file = new File(COVER_DIR);
    if (!file.exists()) file.mkdirs();
  }
  public boolean browse(String directoryName) {
    if (this.mCurrentDir == null) {
      // We're on the storage list
      String storages[] = Util.getMediaDirectories();
      for (String storage : storages) {
        storage = Util.stripTrailingSlash(storage);
        if (storage.endsWith(directoryName)) {
          this.mCurrentRoot = storage;
          this.mCurrentDir = storage;
          this.mCurrentDir = Util.stripTrailingSlash(this.mCurrentDir);
          break;
        }
      }
    } else {
      try {
        this.mCurrentDir =
            new URI(Util.PathToURI(this.mCurrentDir + "/" + directoryName)).normalize().getPath();
        this.mCurrentDir = Util.stripTrailingSlash(this.mCurrentDir);

        if (this.mCurrentDir.equals(getParentDir(this.mCurrentRoot))) {
          // Returning on the storage list
          this.mCurrentDir = null;
          this.mCurrentRoot = null;
        }
      } catch (URISyntaxException e) {
        Log.e(TAG, "URISyntaxException in browse()", e);
        return false;
      } catch (NullPointerException e) {
        Log.e(TAG, "NullPointerException in browse()", e);
        return false;
      }
    }

    Log.d(TAG, "Browsing to " + this.mCurrentDir);

    if (directoryName.equals("..")) this.mCurrentNode = this.mCurrentNode.parent;
    else {
      this.mCurrentNode = this.mCurrentNode.getChildNode(directoryName);
      if (mCurrentNode.subfolderCount() < 1) {
        // Clear the ".." entry
        this.mCurrentNode.children.clear();
        this.populateNode(mCurrentNode, mCurrentDir);
      }
    }

    this.notifyDataSetChanged();
    return true;
  }
Beispiel #8
0
  private static Bitmap readCoverBitmap(Context context, String path, int dipWidth) {
    Bitmap cover = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    int width = Util.convertDpToPx(dipWidth);

    /* Get the resolution of the bitmap without allocating the memory */
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    if (options.outWidth > 0 && options.outHeight > 0) {
      options.inJustDecodeBounds = false;
      options.inSampleSize = 2;

      // Find the best decoding scale for the bitmap
      while (options.outWidth / options.inSampleSize > width) options.inSampleSize++;
      options.inSampleSize--;

      // Decode the file (with memory allocation this time)
      cover = BitmapFactory.decodeFile(path, options);

      if (cover != null && options.outWidth > width) {
        int height = (int) (width * options.outHeight / ((double) options.outWidth));
        cover = Bitmap.createScaledBitmap(cover, width, height, false);
      }
    }

    return cover;
  }
 private void setContextMenuItems(Menu menu, View v) {
   if (v.getId() != R.id.songs) {
     menu.setGroupVisible(R.id.songs_view_only, false);
     menu.setGroupVisible(R.id.phone_only, false);
   }
   if (!Util.isPhone()) menu.setGroupVisible(R.id.phone_only, false);
 }
Beispiel #10
0
  @TargetApi(8)
  private void changeAudioFocus(boolean gain) {
    if (!Util.isFroyoOrLater()) // NOP if not supported
    return;

    audioFocusListener =
        new OnAudioFocusChangeListener() {
          @Override
          public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
                || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
              /*
               * Lower the volume to 36% to "duck" when an alert or something
               * needs to be played.
               */
              LibVLC.getExistingInstance().setVolume(36);
            } else {
              LibVLC.getExistingInstance().setVolume(100);
            }
          }
        };

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (gain)
      am.requestAudioFocus(
          audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    else am.abandonAudioFocus(audioFocusListener);
  }
Beispiel #11
0
 private static String getCoverFromFolder(Context context, Media media) {
   File f = Util.URItoFile(media.getLocation());
   if (f != null && f.getParentFile() != null && f.getParentFile().listFiles() != null)
     for (File s : f.getParentFile().listFiles()) {
       if (s.getAbsolutePath().endsWith("png") || s.getAbsolutePath().endsWith("jpg"))
         return s.getAbsolutePath();
     }
   return null;
 }
 private void DirectoryAdapter_Core(String rootDir) {
   if (rootDir != null) rootDir = Util.stripTrailingSlash(rootDir);
   Log.v(TAG, "rootMRL is " + rootDir);
   mInflater = LayoutInflater.from(VLCApplication.getAppContext());
   mRootNode = new DirectoryAdapter.Node(rootDir);
   mCurrentDir = rootDir;
   this.populateNode(mRootNode, rootDir);
   mCurrentNode = mRootNode;
 }
Beispiel #13
0
  @SuppressLint("NewApi")
  public static synchronized Bitmap getCover(Context context, Media media, int width) {
    String coverPath = null;
    Bitmap cover = null;
    String cachePath = null;

    if (width <= 0) {
      Log.e(TAG, "Invalid cover width requested");
      return null;
    }

    // if external storage is not available, skip covers to prevent slow audio browsing
    if (!Util.hasExternalStorage()) return null;

    try {
      // try to load from cache
      int hash = MurmurHash.hash32(media.getArtist() + media.getAlbum());
      cachePath = COVER_DIR + (hash >= 0 ? "" + hash : "m" + (-hash)) + "_" + width;

      // try to get the cover from the LRUCache first
      BitmapCache cache = BitmapCache.getInstance();
      cover = cache.getBitmapFromMemCache(cachePath);
      if (cover != null) return cover;

      // try to get the cover from the storage cache
      File cacheFile = new File(cachePath);
      if (cacheFile != null && cacheFile.exists()) {
        if (cacheFile.length() > 0) coverPath = cachePath;
        else return null;
      }

      // try to get it from VLC
      if (coverPath == null || !cacheFile.exists()) coverPath = getCoverFromVlc(context, media);

      // no found yet, looking in folder
      if (coverPath == null || !(new File(coverPath)).exists())
        coverPath = getCoverFromFolder(context, media);

      // try to get the cover from android MediaStore
      if (coverPath == null || !(new File(coverPath)).exists())
        coverPath = getCoverFromMediaStore(context, media);

      // read (and scale?) the bitmap
      cover = readCoverBitmap(context, coverPath, width);

      // store cover into both cache
      writeBitmap(cover, cachePath);
      cache.addBitmapToMemCache(cachePath, cover);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return cover;
  }
Beispiel #14
0
  @Override
  public void onCreate() {
    super.onCreate();

    // Get libVLC instance
    try {
      mLibVLC = LibVLC.getInstance();
    } catch (LibVlcException e) {
      e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventManager = EventManager.getInstance();
    mRemoteControlClientReceiverComponent =
        new ComponentName(getPackageName(), RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
      /* Backward compatibility for API 7 */
      filter = new IntentFilter();
      if (stealRemoteControl) filter.setPriority(Integer.MAX_VALUE);
      filter.addAction(Intent.ACTION_MEDIA_BUTTON);
      mRemoteControlClientReceiver = new RemoteControlClientReceiver();
      registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    DirectoryAdapter.Node selectedNode = mCurrentNode.children.get(position);
    DirectoryViewHolder holder;
    View v = convertView;

    Context context = VLCApplication.getAppContext();

    /* If view not created */
    if (v == null) {
      v = mInflater.inflate(R.layout.directory_view_item, parent, false);
      holder = new DirectoryViewHolder();
      holder.layout = v.findViewById(R.id.layout_item);
      holder.title = (TextView) v.findViewById(R.id.title);
      holder.text = (TextView) v.findViewById(R.id.text);
      holder.icon = (ImageView) v.findViewById(R.id.dvi_icon);
      v.setTag(holder);
    } else holder = (DirectoryViewHolder) v.getTag();

    Util.setItemBackground(holder.layout, position);

    String holderText = "";
    if (selectedNode.isFile()) {
      Log.d(TAG, "Loading media " + selectedNode.name);
      Media m = new Media(getMediaLocation(position), false);
      holder.title.setText(m.getTitle());
      holderText = m.getSubtitle();
    } else holder.title.setText(selectedNode.getVisibleName());

    if (selectedNode.name == "..") holderText = context.getString(R.string.parent_folder);
    else if (!selectedNode.isFile()) {
      int folderCount = selectedNode.subfolderCount();
      int mediaFileCount = selectedNode.subfilesCount();
      holderText = "";

      if (folderCount > 0)
        holderText +=
            context
                .getResources()
                .getQuantityString(R.plurals.subfolders_quantity, folderCount, folderCount);
      if (folderCount > 0 && mediaFileCount > 0) holderText += ", ";
      if (mediaFileCount > 0)
        holderText +=
            context
                .getResources()
                .getQuantityString(R.plurals.mediafiles_quantity, mediaFileCount, mediaFileCount);
    }
    holder.text.setText(holderText);
    if (selectedNode.isFile()) holder.icon.setImageResource(R.drawable.icon);
    else holder.icon.setImageResource(R.drawable.ic_folder);

    return v;
  }
Beispiel #16
0
  private void extractTrackInfo(TrackInfo[] tracks) {
    if (tracks == null) return;

    for (TrackInfo track : tracks) {
      if (track.Type == TrackInfo.TYPE_VIDEO) {
        mType = TYPE_VIDEO;
        mWidth = track.Width;
        mHeight = track.Height;
      } else if (mType == TYPE_ALL && track.Type == TrackInfo.TYPE_AUDIO) {
        mType = TYPE_AUDIO;
      } else if (track.Type == TrackInfo.TYPE_META) {
        mLength = track.Length;
        mTitle = track.Title;
        mArtist = Util.getValue(track.Artist, R.string.unknown_artist);
        mAlbum = Util.getValue(track.Album, R.string.unknown_album);
        mGenre = Util.getValue(track.Genre, R.string.unknown_genre);
        mArtworkURL = track.ArtworkURL;
        Log.d(TAG, "Title " + mTitle);
        Log.d(TAG, "Artist " + mArtist);
        Log.d(TAG, "Genre " + mGenre);
        Log.d(TAG, "Album " + mAlbum);
      }
    }

    /* No useful ES found */
    if (mType == TYPE_ALL) {
      int dotIndex = mLocation.lastIndexOf(".");
      if (dotIndex != -1) {
        String fileExt = mLocation.substring(dotIndex);
        if (Media.VIDEO_EXTENSIONS.contains(fileExt)) {
          mType = TYPE_VIDEO;
        } else if (Media.AUDIO_EXTENSIONS.contains(fileExt)) {
          mType = TYPE_AUDIO;
        }
      }
    }
  }
Beispiel #17
0
  public static void setRingtone(Media song, Activity activity) {
    File newringtone = Util.URItoFile(song.getLocation());
    if (!newringtone.exists()) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, newringtone.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
    values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
    values.put(MediaStore.Audio.Media.IS_ALARM, false);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    Uri uri = MediaStore.Audio.Media.getContentUriForPath(newringtone.getAbsolutePath());
    Uri newUri;
    try {
      activity
          .getContentResolver()
          .delete(
              uri,
              MediaStore.MediaColumns.DATA + "=\"" + newringtone.getAbsolutePath() + "\"",
              null);
      newUri = activity.getContentResolver().insert(uri, values);
      RingtoneManager.setActualDefaultRingtoneUri(
          activity.getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);
    } catch (Exception e) {
      Toast.makeText(
              activity.getApplicationContext(),
              activity.getString(R.string.ringtone_error),
              Toast.LENGTH_SHORT)
          .show();
      return;
    }

    Toast.makeText(
            activity.getApplicationContext(),
            activity.getString(R.string.ringtone_set, song.getTitle()),
            Toast.LENGTH_SHORT)
        .show();
  }
Beispiel #18
0
  @TargetApi(14)
  private void updateRemoteControlClientMetadata() {
    if (!Util.isICSOrLater()) // NOP check
    return;

    if (mRemoteControlClient != null) {
      MetadataEditor editor = mRemoteControlClient.editMetadata(true);
      editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, mCurrentMedia.getAlbum());
      editor.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, mCurrentMedia.getArtist());
      editor.putString(MediaMetadataRetriever.METADATA_KEY_GENRE, mCurrentMedia.getGenre());
      editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, mCurrentMedia.getTitle());
      editor.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, mCurrentMedia.getLength());
      editor.putBitmap(MetadataEditor.BITMAP_KEY_ARTWORK, getCover());
      editor.apply();
    }
  }
Beispiel #19
0
  private synchronized void saveCurrentMedia() {
    if (!Util.hasExternalStorage()) return;

    FileOutputStream output;
    BufferedWriter bw;

    try {
      output = new FileOutputStream(AudioUtil.CACHE_DIR + "/" + "CurrentMedia.txt");
      bw = new BufferedWriter(new OutputStreamWriter(output));
      bw.write(mCurrentMedia != null ? mCurrentMedia.getLocation() : "");
      bw.write('\n');
      bw.write(mShuffling ? "1" : "0");
      bw.write('\n');
      bw.close();
      output.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #20
0
  private synchronized void saveMediaList() {
    if (!Util.hasExternalStorage()) return;

    FileOutputStream output;
    BufferedWriter bw;

    try {
      output = new FileOutputStream(AudioUtil.CACHE_DIR + "/" + "MediaList.txt");
      bw = new BufferedWriter(new OutputStreamWriter(output));
      for (int i = 0; i < mMediaList.size(); i++) {
        Media item = mMediaList.get(i);
        bw.write(item.getLocation());
        bw.write('\n');
      }
      bw.close();
      output.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Beispiel #21
0
  private synchronized void loadLastPlaylist() {
    if (!Util.hasExternalStorage()) return;

    String line;
    FileInputStream input;
    BufferedReader br;
    int rowCount = 0;

    int position = 0;
    String currentMedia;
    List<String> mediaPathList = new ArrayList<String>();

    try {
      // read CurrentMedia
      input = new FileInputStream(AudioUtil.CACHE_DIR + "/" + "CurrentMedia.txt");
      br = new BufferedReader(new InputStreamReader(input));
      currentMedia = br.readLine();
      mShuffling = "1".equals(br.readLine());
      br.close();
      input.close();

      // read MediaList
      input = new FileInputStream(AudioUtil.CACHE_DIR + "/" + "MediaList.txt");
      br = new BufferedReader(new InputStreamReader(input));
      while ((line = br.readLine()) != null) {
        mediaPathList.add(line);
        if (line.equals(currentMedia)) position = rowCount;
        rowCount++;
      }
      br.close();
      input.close();

      // load playlist
      mInterface.load(mediaPathList, position, false, false);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (RemoteException e) {
      e.printStackTrace();
    }
  }
Beispiel #22
0
 public String getFileName() {
   if (mFilename == null) {
     mFilename = Util.URItoFileName(mLocation);
   }
   return mFilename;
 }
  @SuppressWarnings("deprecation")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    // Create onClickListen
    Preference directoriesPref = findPreference("directories");
    directoriesPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {

          @Override
          public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent(getApplicationContext(), BrowserActivity.class);
            startActivity(intent);
            return true;
          }
        });

    // Create onClickListen
    Preference clearHistoryPref = findPreference("clear_history");
    clearHistoryPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {

          @Override
          public boolean onPreferenceClick(Preference preference) {
            new AlertDialog.Builder(PreferencesActivity.this)
                .setTitle(R.string.clear_history)
                .setMessage(R.string.validation)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(
                    android.R.string.yes,
                    new DialogInterface.OnClickListener() {

                      @Override
                      public void onClick(DialogInterface dialog, int whichButton) {
                        DatabaseManager db = DatabaseManager.getInstance(getApplicationContext());
                        db.clearSearchhistory();
                      }
                    })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
            return true;
          }
        });

    // HW decoding
    CheckBoxPreference checkboxHW = (CheckBoxPreference) findPreference("enable_iomx");
    checkboxHW.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          @Override
          public boolean onPreferenceClick(Preference preference) {
            CheckBoxPreference checkboxHW = (CheckBoxPreference) preference;
            LibVLC.useIOMX(checkboxHW.isChecked());
            return true;
          }
        });

    // Headset detection option
    CheckBoxPreference checkboxHS = (CheckBoxPreference) findPreference("enable_headset_detection");
    checkboxHS.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {
          @Override
          public boolean onPreferenceClick(Preference preference) {
            CheckBoxPreference checkboxHS = (CheckBoxPreference) preference;
            AudioServiceController.getInstance().detectHeadset(checkboxHS.isChecked());
            return true;
          }
        });

    // Change verbosity (logcat)
    CheckBoxPreference checkboxVerbosity =
        (CheckBoxPreference) findPreference("enable_verbose_mode");
    checkboxVerbosity.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {

          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            try {
              LibVLC.getInstance().changeVerbosity((Boolean) newValue);
            } catch (LibVlcException e) {
              Log.e(TAG, "Failed to change logs verbosity");
              e.printStackTrace();
              return true;
            }
            String newstatus = ((Boolean) newValue) ? "enabled" : "disabled";
            Log.i(TAG, "Verbosity mode is now " + newstatus);
            return true;
          }
        });

    // Audio output
    ListPreference aoutPref = (ListPreference) findPreference("aout");
    int aoutEntriesId = Util.isGingerbreadOrLater() ? R.array.aouts : R.array.aouts_froyo;
    aoutPref.setEntries(aoutEntriesId);
    aoutPref.setEntryValues(aoutEntriesId);
    aoutPref.setOnPreferenceChangeListener(
        new OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
            LibVLC.setAout(PreferencesActivity.this, (String) newValue, true);
            return true;
          }
        });

    // Attach debugging items
    Preference quitAppPref = findPreference("quit_app");
    quitAppPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {

          @Override
          public boolean onPreferenceClick(Preference preference) {
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
          }
        });
    Preference clearMediaPref = findPreference("clear_media_db");
    clearMediaPref.setOnPreferenceClickListener(
        new OnPreferenceClickListener() {

          @Override
          public boolean onPreferenceClick(Preference preference) {
            DatabaseManager.getInstance(getBaseContext()).emptyDatabase();
            Toast.makeText(getBaseContext(), "Media database cleared!", Toast.LENGTH_SHORT).show();
            return true;
          }
        });
  }
Beispiel #24
0
  /**
   * A function to control the Remote Control Client. It is needed for compatibility with devices
   * below Ice Cream Sandwich (4.0).
   *
   * @param p Playback state
   */
  @TargetApi(14)
  private void setRemoteControlClientPlaybackState(int p) {
    if (!Util.isICSOrLater()) return;

    if (mRemoteControlClient != null) mRemoteControlClient.setPlaybackState(p);
  }
 @Override
 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
   MenuInflater inflater = getActivity().getMenuInflater();
   inflater.inflate(R.menu.audio_list_browser, menu);
   if (!Util.isPhone()) menu.setGroupVisible(R.id.phone_only, false);
 }
 public static String[] getMediaDirectories() {
   ArrayList<String> list = new ArrayList<String>();
   list.addAll(Arrays.asList(Util.getStorageDirectories()));
   list.addAll(Arrays.asList(Util.getCustomDirectories()));
   return list.toArray(new String[list.size()]);
 }
 public String getMediaLocation(int position) {
   if (position >= mCurrentNode.children.size()) return null;
   return Util.PathToURI(this.mCurrentDir + "/" + mCurrentNode.children.get(position).name);
 }
  /**
   * @param n Node to populate
   * @param path Path to populate
   * @param depth Depth of iteration (0 = 1st level of nesting, 1 = 2 level of nesting, etc)
   */
  private void populateNode(DirectoryAdapter.Node n, String path, int depth) {
    if (path == null) {
      // We're on the storage list
      String storages[] = Util.getMediaDirectories();
      for (String storage : storages) {
        File f = new File(storage);
        DirectoryAdapter.Node child = new DirectoryAdapter.Node(f.getName(), getVisibleName(f));
        child.isFile = false;
        this.populateNode(child, storage, 0);
        n.addChildNode(child);
      }
      return;
    }

    File file = new File(path);
    if (!file.exists() || !file.isDirectory()) return;

    ArrayList<String> files = new ArrayList<String>();
    LibVLC.nativeReadDirectory(path, files);
    StringBuilder sb = new StringBuilder(100);
    /* If no sub-directories or I/O error don't crash */
    if (files == null || files.size() < 1) {
      // return
    } else {
      for (int i = 0; i < files.size(); i++) {
        String filename = files.get(i);
        /* Avoid infinite loop */
        if (filename.equals(".") || filename.equals("..") || filename.startsWith(".")) continue;

        DirectoryAdapter.Node nss = new DirectoryAdapter.Node(filename);
        nss.isFile = false;
        sb.append(path);
        sb.append("/");
        sb.append(filename);
        String newPath = sb.toString();
        sb.setLength(0);

        // Don't try to go beyond depth 10 as a safety measure.
        if (LibVLC.nativeIsPathDirectory(newPath) && depth < 10) {
          ArrayList<String> files_int = new ArrayList<String>();
          LibVLC.nativeReadDirectory(newPath, files_int);
          if (files_int.size() < 8) {
              /* Optimisation: If there are more than 8
              sub-folders, don't scan each one, otherwise
              when scaled it is very slow to load */
            String mCurrentDir_old = mCurrentDir;
            mCurrentDir = path;
            this.populateNode(nss, newPath, depth + 1);
            mCurrentDir = mCurrentDir_old;
          }
        } else {
          if (acceptedPath(newPath)) nss.setIsFile();
          else continue;
        }

        n.addChildNode(nss);
      }
      Collections.sort(n.children);
    }

    DirectoryAdapter.Node up = new DirectoryAdapter.Node("..");
    n.children.add(0, up);
  }