@Override
 public LocalFilesystemURL toLocalUri(Uri inputURL) {
   if (!"file".equals(inputURL.getScheme())) {
     return null;
   }
   File f = new File(inputURL.getPath());
   // Removes and duplicate /s (e.g. file:///a//b/c)
   Uri resolvedUri = Uri.fromFile(f);
   String rootUriNoTrailingSlash = rootUri.getEncodedPath();
   rootUriNoTrailingSlash =
       rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
   if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
     return null;
   }
   String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
   // Strip leading slash
   if (!subPath.isEmpty()) {
     subPath = subPath.substring(1);
   }
   Uri.Builder b =
       new Uri.Builder()
           .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
           .authority("localhost")
           .path(name);
   if (!subPath.isEmpty()) {
     b.appendEncodedPath(subPath);
   }
   if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
     // Add trailing / for directories.
     b.appendEncodedPath("");
   }
   return LocalFilesystemURL.parse(b.build());
 }
示例#2
0
  @Override
  public void onCreate(Bundle theSavedInstanceState) {
    super.onCreate(theSavedInstanceState);

    // create folder for external storage
    myContext = new ContextWrapper(this);
    myContext.getExternalFilesDir(null);

    Intent anIntent = getIntent();
    String aDataType = anIntent != null ? anIntent.getType() : "";
    Uri aDataUrl = anIntent != null ? anIntent.getData() : null;
    String aDataPath = aDataUrl != null ? aDataUrl.getEncodedPath() : "";

    myTextView = new TextView(this);
    myTextView.setMovementMethod(new ScrollingMovementMethod());
    myTextView.setText(
        "sView loader in progress...\n  URL: " + aDataPath + "\n  Type: " + aDataType);
    setContentView(myTextView);

    StringBuilder anInfo = new StringBuilder();
    if (!StActivity.loadNatives(this, anInfo)) {
      // StActivity.exitWithError(this, "Broken apk?\n" + anInfo);
      return;
    }
    myTextView.append("\n\n" + anInfo);

    Intent anImgViewer = new Intent(this, StActivity.class);
    anImgViewer.setDataAndType(aDataUrl, aDataType);
    startActivityForResult(anImgViewer, 0);
  }
示例#3
0
  public static String getCacheFilenameForUri(Uri uri) {
    StringBuilder filename = new StringBuilder();
    filename.append(uri.getScheme()).append("_").append(uri.getHost()).append("_");
    String encodedPath = uri.getEncodedPath();
    if (!TextUtils.isEmpty(encodedPath)) {
      int length = encodedPath.length();
      if (length > 60) {
        encodedPath = encodedPath.substring(length - 60);
      }
      encodedPath = encodedPath.replace('/', '_');
      filename.append(encodedPath).append("_");
    }
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(uri.toString().getBytes("UTF-8"));
      byte[] digest = md.digest();
      for (byte b : digest) {
        if ((0xff & b) < 0x10) {
          filename.append("0").append(Integer.toHexString((0xFF & b)));
        } else {
          filename.append(Integer.toHexString(0xFF & b));
        }
      }
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      filename.append(uri.toString().hashCode());
    }

    return filename.toString();
  }
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   HideImaShow();
   File file = null;
   if (resultCode == Activity.RESULT_OK) {
     if (requestCode == R.id.resource_take) {
       file = temFile;
       imgList.add(file);
     } else if (requestCode == R.id.resource_pick) {
       Uri uri = data.getData();
       if (uri.getScheme().equals("content")) {
         file = new File(SystemMethodUtil.changeURItoPath(uri, context));
         if (file.getAbsolutePath().toLowerCase().endsWith(".jpg")) {
           imgList.add(file);
         } else {
           Toast.makeText(context, "不支持的图片格式", Toast.LENGTH_SHORT).show();
         }
       } else if (uri.getScheme().equals("file")) {
         file = new File(uri.getEncodedPath());
         if (file.getAbsolutePath().toLowerCase().endsWith(".jpg")) {
           imgList.add(file);
         } else {
           Toast.makeText(context, "不支持的图片格式", Toast.LENGTH_SHORT).show();
         }
       }
     }
   }
   notifyAdapter();
 }
示例#5
0
 public File getFileForUri(Uri uri)
 {
     Object obj1 = uri.getEncodedPath();
     int i = ((String) (obj1)).indexOf('/', 1);
     Object obj = Uri.decode(((String) (obj1)).substring(1, i));
     obj1 = Uri.decode(((String) (obj1)).substring(i + 1));
     obj = (File)mRoots.get(obj);
     if (obj == null)
     {
         throw new IllegalArgumentException((new StringBuilder()).append("Unable to find configured root for ").append(uri).toString());
     }
     uri = new File(((File) (obj)), ((String) (obj1)));
     try
     {
         obj1 = uri.getCanonicalFile();
     }
     catch (IOException ioexception)
     {
         throw new IllegalArgumentException((new StringBuilder()).append("Failed to resolve canonical path for ").append(uri).toString());
     }
     if (!((File) (obj1)).getPath().startsWith(((File) (obj)).getPath()))
     {
         throw new SecurityException("Resolved path jumped beyond configured root");
     } else
     {
         return ((File) (obj1));
     }
 }
示例#6
0
  @Override
  public boolean imageShowSuccess(Uri uri) {
    if (uri != null) {
      if (DEBUG) {
        Log.d(
            "imageShowSuccess",
            "[[imageShowSuccess]] uri : "
                + uri.getScheme()
                + " uri path : "
                + uri.getPath()
                + " uri title : "
                + uri.getHost()
                + " encode path = "
                + uri.getEncodedPath()
                + " toString : "
                + uri.toString());
      }
      String checkUrl = uri.getPath();
      if (!TextUtils.isEmpty(checkUrl) && checkUrl.toLowerCase().startsWith("http")) {
        // do nothing
      } else if (!TextUtils.isEmpty(checkUrl) && checkUrl.toLowerCase().startsWith(FILE_CONTENT)) {
        checkUrl = checkUrl.substring(FILE_CONTENT.length());
      }
      if (!TextUtils.isEmpty(checkUrl) && checkUrl.equals(mUrl)) {
        return mCurrentBtLoadSuccess;
      }
    }

    return false;
  }
  /**
   * This function loads all the songs corresponding to the artist selected by the user.
   *
   * <p>If there are no songs for that artist, or there is an error retrieving them, the function
   * returns in between without loading any album names.
   */
  private void loadFileSystem() {
    ContentResolver contentResolver = this.getContentResolver();
    Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection =
        MediaStore.Audio.Media.IS_MUSIC + " != 0 AND " + MediaStore.Audio.Media.ARTIST + " LIKE ?";
    String[] projection = {
      MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST
    };
    String[] arguments = {artistName};

    Log.d("SingleArtistListing", "The uri is " + uri.getEncodedPath());
    Cursor cursor =
        contentResolver.query(uri, projection, selection, arguments, MediaStore.Audio.Media.TITLE);

    // if there is an error reading the songs on the SD card of the phone
    if (cursor == null) {
      Log.d(
          "SingleArtistListing", "There was an error reading music files from the music library.");
      messageToast.cancel();
      messageToast =
          Toast.makeText(
              activity,
              "There was an error reading music files from the music library",
              Toast.LENGTH_SHORT);
      messageToast.show();
      return;
    }
    // if there are no songs present in the music library of the SD card of the phone memory.
    else if (cursor.getCount() == 0) {
      Log.d("SingleArtistListing", "There are no music files present in the library!");
      messageToast.cancel();
      messageToast =
          Toast.makeText(activity, "There are no songs for this artist", Toast.LENGTH_SHORT);
      messageToast.show();
      return;
    }

    // songs are present in the music library on the SD card of the phone memory.
    else {
      Log.d("SingleArtistListing", "Songs present for the artist");
      artistSongNamesAdapter =
          new ArrayAdapter<String>(
              this.getApplicationContext(), R.layout.album_name_view, R.id.albumName, songNames);

      if (artistSongNamesAdapter == null) {
        Log.d("songListing", "Artist List data is null");
        messageToast.cancel();
        messageToast =
            Toast.makeText(
                activity, "Error reading music files from the music library!", Toast.LENGTH_SHORT);
        messageToast.show();
        return;
      }
      while (cursor.moveToNext()) {
        artistSongNamesAdapter.add(cursor.getString(1));
      }
      this.artistSongs.setAdapter(artistSongNamesAdapter);
    }
  }
示例#8
0
  public void setImageURI(Uri uri, boolean forceOriginLoad) {
    unRegistehandler();
    mCurrentBtLoadSuccess = false;

    if (uri != null) {
      if (DEBUG) {
        Log.d(
            "setImageURI",
            "[[setImageURI]] uri : "
                + uri.getScheme()
                + " uri path : "
                + uri.getPath()
                + " uri title : "
                + uri.getHost()
                + " encode path = "
                + uri.getEncodedPath()
                + " toString : "
                + uri.toString());
      }
      String path = uri.getPath();
      if (!TextUtils.isEmpty(path) && path.toLowerCase().startsWith("http")) {
        this.setImageUrl(uri.getPath(), forceOriginLoad);
        return;
      } else if (!TextUtils.isEmpty(path) && path.toLowerCase().startsWith(FILE_CONTENT)) {
        String localUri = path.substring(FILE_CONTENT.length());
        if (!TextUtils.isEmpty(localUri)) {
          this.setImageUrlLocal(localUri, forceOriginLoad);
          return;
        }
      }
      mUrl = null;
      setImageDrawable(mDefaultSrc);
    } else {
      mUrl = null;
      if (mCurrentDownloadRequest != null) {
        mCurrentDownloadRequest.cancelDownload();
      }
      if (mHasAnimation) {
        this.clearAnimation();
      }
      // super.setImageURI(uri);
      if (mWebImageViewStatusListener != null) {
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                mWebImageViewStatusListener.onLoadImageFailed(WebImageView.this, mUrl);
              }
            });
      }
      setImageDrawable(mDefaultSrc);
    }
  }
示例#9
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // TODO clean impl

    if (data != null) {
      Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

      if (uri != null) {
        ringtone = "content://media" + uri.getEncodedPath();
      }
    }
  }
示例#10
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAlertBuilder = new AlertDialog.Builder(this);

    if (core == null) {
      core = (MuPDFCore) getLastNonConfigurationInstance();

      if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
        mFileName = savedInstanceState.getString("FileName");
      }
    }
    if (core == null) {
      Intent intent = getIntent();
      if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        Uri uri = intent.getData();
        if (uri.toString().startsWith("content://")) {
          // Handle view requests from the Transformer Prime's file manager
          // Hopefully other file managers will use this same scheme, if not
          // using explicit paths.
          Cursor cursor = getContentResolver().query(uri, new String[] {"_data"}, null, null, null);
          if (cursor.moveToFirst()) {
            uri = Uri.parse(cursor.getString(0));
          }
        }
        core = openFile(Uri.decode(uri.getEncodedPath()));
        SearchTaskResult.set(null);
      }
      if (core != null && core.needsPassword()) {
        requestPassword(savedInstanceState);
        return;
      }
    }
    if (core == null) {
      AlertDialog alert = mAlertBuilder.create();
      alert.setTitle(R.string.open_failed);
      alert.setButton(
          AlertDialog.BUTTON_POSITIVE,
          "Dismiss",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              finish();
            }
          });
      alert.show();
      return;
    }

    createUI(savedInstanceState);
  }
示例#11
0
文件: k.java 项目: zezadas/camera
 private Uri b(Uri object, String string, String string2) {
   String string3 = object.toString();
   int n = string3.indexOf(";adurl");
   if (n != -1) {
     return Uri.parse(
         string3.substring(0, n + 1) + string + "=" + string2 + ";" + string3.substring(n + 1));
   }
   object = object.getEncodedPath();
   n = string3.indexOf((String) object);
   return Uri.parse(
       string3.substring(0, object.length() + n)
           + ";"
           + string
           + "="
           + string2
           + ";"
           + string3.substring(object.length() + n));
 }
 private WPEditImageSpan createWPEditImageSpanLocal(Context context, MediaFile mediaFile) {
   Uri imageUri = Uri.parse(mediaFile.getFilePath());
   Bitmap thumbnailBitmap;
   if (MediaUtils.isVideo(imageUri.toString())) {
     thumbnailBitmap =
         BitmapFactory.decodeResource(context.getResources(), R.drawable.media_movieclip);
   } else {
     thumbnailBitmap =
         ImageUtils.getWPImageSpanThumbnailFromFilePath(
             context,
             imageUri.getEncodedPath(),
             ImageUtils.getMaximumThumbnailWidthForEditor(context));
     if (thumbnailBitmap == null) {
       // Use a placeholder in case thumbnail can't be decoded (OOM for instance)
       thumbnailBitmap =
           BitmapFactory.decodeResource(
               context.getResources(), R.drawable.legacy_dashicon_format_image_big_grey);
     }
   }
   WPEditImageSpan imageSpan = new WPEditImageSpan(context, thumbnailBitmap, imageUri);
   mediaFile.setWidth(
       MediaUtils.getMinimumImageWidth(context, imageUri, mBlogSettingMaxImageWidth));
   return imageSpan;
 }
示例#13
0
  private void serializeWaypoints(Context context, XmlSerializer serializer, Uri media)
      throws IOException {
    if (isCancelled()) {
      throw new IOException("Fail to execute request due to canceling");
    }
    Cursor mediaCursor = null;
    Cursor waypointCursor = null;
    BufferedReader buf = null;
    ContentResolver resolver = context.getContentResolver();
    try {
      mediaCursor =
          resolver.query(
              media,
              new String[] {Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT},
              null,
              null,
              null);
      if (mediaCursor.moveToFirst()) {
        do {
          Uri waypointUri =
              Waypoints.buildUri(
                  mediaCursor.getLong(1), mediaCursor.getLong(2), mediaCursor.getLong(3));
          waypointCursor =
              resolver.query(
                  waypointUri,
                  new String[] {
                    Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.ALTITUDE, Waypoints.TIME
                  },
                  null,
                  null,
                  null);
          serializer.text("\n");
          serializer.startTag("", "wpt");
          if (waypointCursor != null && waypointCursor.moveToFirst()) {
            serializer.attribute(null, "lat", Double.toString(waypointCursor.getDouble(0)));
            serializer.attribute(null, "lon", Double.toString(waypointCursor.getDouble(1)));
            serializer.text("\n");
            serializer.startTag("", "ele");
            serializer.text(Double.toString(waypointCursor.getDouble(2)));
            serializer.endTag("", "ele");
            serializer.text("\n");
            serializer.startTag("", "time");
            Date time = new Date(waypointCursor.getLong(3));
            synchronized (ZULU_DATE_FORMATER) {
              serializer.text(ZULU_DATE_FORMATER.format(time));
            }
            serializer.endTag("", "time");
          }
          if (waypointCursor != null) {
            waypointCursor.close();
            waypointCursor = null;
          }

          Uri mediaUri = Uri.parse(mediaCursor.getString(0));
          if (mediaUri.getScheme().equals("file")) {
            if (mediaUri.getLastPathSegment().endsWith("3gp")) {
              String fileName = includeMediaFile(mediaUri.getLastPathSegment());
              quickTag(serializer, "", "name", fileName);
              serializer.startTag("", "link");
              serializer.attribute(null, "href", fileName);
              quickTag(serializer, "", "text", fileName);
              serializer.endTag("", "link");
            } else if (mediaUri.getLastPathSegment().endsWith("jpg")) {
              String mediaPathPrefix = Constants.getSdCardDirectory(mContext);
              String fileName = includeMediaFile(mediaPathPrefix + mediaUri.getLastPathSegment());
              quickTag(serializer, "", "name", fileName);
              serializer.startTag("", "link");
              serializer.attribute(null, "href", fileName);
              quickTag(serializer, "", "text", fileName);
              serializer.endTag("", "link");
            } else if (mediaUri.getLastPathSegment().endsWith("txt")) {
              quickTag(serializer, "", "name", mediaUri.getLastPathSegment());
              serializer.startTag("", "desc");
              if (buf != null) {
                buf.close();
              }
              buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath()));
              String line;
              while ((line = buf.readLine()) != null) {
                serializer.text(line);
                serializer.text("\n");
              }
              serializer.endTag("", "desc");
            }
          } else if (mediaUri.getScheme().equals("content")) {
            if ((GPStracking.AUTHORITY + ".string").equals(mediaUri.getAuthority())) {
              quickTag(serializer, "", "name", mediaUri.getLastPathSegment());
            } else if (mediaUri.getAuthority().equals("media")) {

              Cursor mediaItemCursor = null;
              try {
                mediaItemCursor =
                    resolver.query(
                        mediaUri,
                        new String[] {MediaColumns.DATA, MediaColumns.DISPLAY_NAME},
                        null,
                        null,
                        null);
                if (mediaItemCursor.moveToFirst()) {
                  String fileName = includeMediaFile(mediaItemCursor.getString(0));
                  quickTag(serializer, "", "name", fileName);
                  serializer.startTag("", "link");
                  serializer.attribute(null, "href", fileName);
                  quickTag(serializer, "", "text", mediaItemCursor.getString(1));
                  serializer.endTag("", "link");
                }
              } finally {
                if (mediaItemCursor != null) {
                  mediaItemCursor.close();
                }
              }
            }
          }
          serializer.text("\n");
          serializer.endTag("", "wpt");
        } while (mediaCursor.moveToNext());
      }
    } finally {
      if (mediaCursor != null) {
        mediaCursor.close();
      }
      if (waypointCursor != null) {
        waypointCursor.close();
      }
      if (buf != null) buf.close();
    }
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    int sortMode = TRACK_MENU;
    if (icicle == null) {
      mSelectedUri = getIntent().getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
      mDrmLevel = getIntent().getIntExtra(DrmStore.DrmExtra.EXTRA_DRM_LEVEL, -1);
      MusicLogUtils.d(TAG, "onCreate: drmlevel=" + mDrmLevel);
    } else {
      mSelectedUri = (Uri) icicle.getParcelable(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
      // Retrieve list state. This will be applied after the
      // QueryHandler has run
      mListState = icicle.getParcelable(LIST_STATE_KEY);
      mListHasFocus = icicle.getBoolean(FOCUS_KEY);
      sortMode = icicle.getInt(SORT_MODE_KEY, sortMode);
      mPrevSelectedPos = icicle.getInt(SELECTED_POS, -1);
      mDrmLevel = icicle.getInt(DRM_LEVEL, -1);
      MusicLogUtils.d(TAG, "onCreate: drmlevel(restored)=" + mDrmLevel);
    }
    if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) {
      mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    } else {
      mBaseUri = getIntent().getData();
      if (mBaseUri == null) {
        MusicLogUtils.w(TAG, "No data URI given to PICK action");
        finish();
        return;
      }
    }

    setContentView(R.layout.music_picker);

    LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
    /*
            if (FeatureOption.MTK_THEMEMANAGER_APP) {
                mainLayout.setThemeContentBgColor(0xff000000);
            }
    */
    mSortOrder = MediaStore.Audio.Media.TITLE_KEY;

    if (FeatureOption.MTK_DRM_APP) {
      mDrmClient = new DrmManagerClient(this);
    }

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);

    mAdapter =
        new TrackListAdapter(
            this, listView, R.layout.music_picker_item, new String[] {}, new int[] {});

    setListAdapter(mAdapter);

    listView.setTextFilterEnabled(true);

    // We manually save/restore the listview state
    listView.setSaveEnabled(false);

    mQueryHandler = new QueryHandler(this);

    mProgressContainer = findViewById(R.id.progressContainer);
    mListContainer = findViewById(R.id.listContainer);

    mOkayButton = findViewById(R.id.okayButton);
    mOkayButton.setOnClickListener(this);
    mCancelButton = findViewById(R.id.cancelButton);
    mCancelButton.setOnClickListener(this);

    // If there is a currently selected Uri, then try to determine who
    // it is.
    if (mSelectedUri != null) {
      Uri.Builder builder = mSelectedUri.buildUpon();
      String path = mSelectedUri.getEncodedPath();
      int idx = path.lastIndexOf('/');
      if (idx >= 0) {
        path = path.substring(0, idx);
      }
      builder.encodedPath(path);
      Uri baseSelectedUri = builder.build();
      MusicLogUtils.v(TAG, "Selected Uri: " + mSelectedUri);
      MusicLogUtils.v(TAG, "Selected base Uri: " + baseSelectedUri);
      MusicLogUtils.v(TAG, "Base Uri: " + mBaseUri);
      if (baseSelectedUri.equals(mBaseUri)) {
        // If the base Uri of the selected Uri is the same as our
        // content's base Uri, then use the selection!
        mSelectedId = ContentUris.parseId(mSelectedUri);
      }
    }

    setSortMode(sortMode);
  }
示例#15
0
  /**
   * Called when the activity is first created.
   *
   * @param icicle
   */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    /// M: set the music style Audio.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    int sortMode = TRACK_MENU;
    if (icicle == null) {
      mSelectedUri = getIntent().getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
      /// M: Retrieve the Drmlevel from intent @{
      mDrmLevel = getIntent().getIntExtra(OmaDrmStore.DrmExtra.EXTRA_DRM_LEVEL, -1);
      MusicLogUtils.d(TAG, "onCreate: drmlevel=" + mDrmLevel);
      /// @}
    } else {
      mSelectedUri = (Uri) icicle.getParcelable(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
      // Retrieve list state. This will be applied after the
      // QueryHandler has run.
      mListState = icicle.getParcelable(LIST_STATE_KEY);
      mListHasFocus = icicle.getBoolean(FOCUS_KEY);
      sortMode = icicle.getInt(SORT_MODE_KEY, sortMode);
      /// M: Returns the value associated with the given key(SELECTED_POS|DRM_LEVEL), or
      // defaultValue
      // if no mapping of the desired type exists for the given key. @{
      mPrevSelectedPos = icicle.getInt(SELECTED_POS, -1);
      mDrmLevel = icicle.getInt(DRM_LEVEL, -1);
      MusicLogUtils.d(
          TAG, "onCreate: drmlevel(restored) = " + mDrmLevel + ", mSelectedUri = " + mSelectedUri);
      /// @}
    }
    if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) {
      mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    } else {
      mBaseUri = getIntent().getData();
      if (mBaseUri == null) {
        MusicLogUtils.w(TAG, "No data URI given to PICK action");
        finish();
        return;
      }
    }

    setContentView(R.layout.music_picker);
    /// M: Creates a DrmManagerClient.
    if (MusicFeatureOption.IS_SUPPORT_DRM) {
      mDrmClient = new OmaDrmClient(this);
    }
    /// M: add for chinese sorting
    mSortOrder = MediaStore.Audio.Media.TITLE_PINYIN_KEY;

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);

    mAdapter =
        new TrackListAdapter(
            this, listView, R.layout.music_picker_item, new String[] {}, new int[] {});

    setListAdapter(mAdapter);

    listView.setTextFilterEnabled(true);

    // We manually save/restore the listview state
    listView.setSaveEnabled(false);

    mQueryHandler = new QueryHandler(this);

    // mProgressContainer = findViewById(R.id.progressContainer);
    // mListContainer = findViewById(R.id.listContainer);

    mOkayButton = findViewById(R.id.okayButton);
    mOkayButton.setOnClickListener(this);
    /// M: Only when user select a audio we need set ok button enable.
    mOkayButton.setEnabled(false);

    mCancelButton = findViewById(R.id.cancelButton);
    mCancelButton.setOnClickListener(this);

    // If there is a currently selected Uri, then try to determine who
    // it is.
    if (mSelectedUri != null) {
      Uri.Builder builder = mSelectedUri.buildUpon();
      String path = mSelectedUri.getEncodedPath();
      int idx = path.lastIndexOf('/');
      if (idx >= 0) {
        path = path.substring(0, idx);
      }
      builder.encodedPath(path);
      Uri baseSelectedUri = builder.build();
      MusicLogUtils.v(TAG, "Selected Uri: " + mSelectedUri);
      MusicLogUtils.v(TAG, "Selected base Uri: " + baseSelectedUri);
      MusicLogUtils.v(TAG, "Base Uri: " + mBaseUri);
      if (baseSelectedUri.equals(mBaseUri)) {
        // If the base Uri of the selected Uri is the same as our
        // content's base Uri, then use the selection!
        mSelectedId = ContentUris.parseId(mSelectedUri);
      }
    }

    /// M: add IntentFilter action and register a Listener for SD card status changed @{
    IntentFilter f = new IntentFilter();
    f.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
    f.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    f.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    f.addAction(Intent.ACTION_MEDIA_MOUNTED);
    f.addDataScheme("file");
    registerReceiver(mScanListener, f);
    /// @}
    mIsBroadcastReg = true;
    setSortMode(sortMode);
  }
  public static void parseFile(Context context, String fileUri, RequestManager.Task task) {

    Uri uri = Uri.parse(fileUri);

    final StringBuffer headerString = new StringBuffer();

    String tempFile = null;
    String scheme = uri.getScheme();

    if ("http".equals(scheme)) {
      tempFile = getUniqueTempFileName(context, uri.getLastPathSegment());
      if (tempFile != null) {
        final boolean manifest = fileUri.toLowerCase(Locale.US).endsWith(".ism/manifest");
        final String callbackFile = tempFile;
        DataHandlerCallback dataCallback =
            new DataHandlerCallback() {

              @SuppressLint("WorldReadableFiles")
              public void handleData(InputStream is) {
                try {
                  FileOutputStream fos = new FileOutputStream(callbackFile, true);
                  int dataCounter = 0, read;
                  byte[] buffer = new byte[2048];

                  try {
                    while ((read = is.read(buffer)) != -1) {
                      dataCounter += read;
                      fos.write(buffer, 0, read);

                      String header;
                      if (manifest) {
                        header = findManifestHeader(callbackFile);
                      } else {
                        header = findHeader(callbackFile);
                      }

                      if (header != null) {
                        DrmLog.debug("header found");
                        // We have the header, stop download
                        headerString.append(header);
                        break;
                      }

                      if (!manifest && dataCounter > 20 * 1024) {
                        // PR header has not been found in the
                        // first 20kB of the file, it is
                        // probably a non-DRM file, stop
                        // trying to renew.
                        break;
                      }
                    }
                  } finally {
                    fos.close();
                  }
                } catch (IOException e) {
                  DrmLog.logException(e);
                }
              }
            };

        Response response =
            UrlConnectionClient.get(
                context, task.mDlsSessionId, uri.toString(), null, dataCallback, null);

        if (response == null) {
          task.mHttpError = Constants.HTTP_ERROR_INTERNAL_ERROR;
        } else if (response.getStatus() != 200) {
          task.mHttpError = response.getStatus();
          int innerHttpError = response.getInnerStatus();
          if (innerHttpError != 0) {
            task.mInnerHttpError = innerHttpError;
          }
        }
      }
    } else if ((scheme == null || scheme.equals("file"))) {
      File file = null;
      try {
        file = new File(URLDecoder.decode(uri.getEncodedPath(), "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        DrmLog.logException(e);
      }
      if (file != null && file.exists()) {
        String header = findHeader(file.getAbsolutePath());
        if (header != null && header.length() > 0) {
          headerString.append(header);
        }
      } else {
        task.mHttpError = Constants.HTTP_ERROR_INTERNAL_ERROR;
      }
    }
    if (headerString.length() > 0) {
      String header = headerString.toString();
      task.mHeader = header;
    } else if (task.mHttpError != Constants.HTTP_ERROR_INTERNAL_ERROR) {
      // The file is not a DRM file
      task.mHttpError = Constants.HTTP_ERROR_UNHANDLED_ERROR_IN_PK;
    }
    if (tempFile != null) {
      if (!(new File(tempFile).delete())) {
        // it's OK if we couldn't delete the file
      }
    }
  }
示例#17
0
    private final int copyFiles(File[] list, Uri dest) throws InterruptedException {
      File file = null;
      for (int i = 0; i < list.length; i++) {
        InputStream is = null;
        OutputStream os = null;
        file = list[i];
        if (file == null) {
          error(ctx.getString(R.string.unkn_err));
          break;
        }
        Uri dest_uri = null;
        try {
          if (isStopReq()) {
            error(ctx.getString(R.string.canceled));
            break;
          }
          String fn = file.getName();
          String to_append = "%2f" + Utils.escapePath(fn);
          dest_uri = dest.buildUpon().encodedPath(dest.getEncodedPath() + to_append).build();
          String mime = getMime(dest_uri);
          if (file.isDirectory()) {
            if (depth++ > 40) {
              error(ctx.getString(R.string.too_deep_hierarchy));
              break;
            }
            if (mime != null) {
              if (!Document.MIME_TYPE_DIR.equals(mime)) {
                error(ctx.getString(R.string.cant_md));
                break;
              }
            } else {
              DocumentsContract.createDocument(cr, dest, Document.MIME_TYPE_DIR, fn);
            }
            copyFiles(file.listFiles(), dest_uri);
            if (errMsg != null) break;
            depth--;
            counter++;
          } else {
            if (mime != null) {
              int res = askOnFileExist(ctx.getString(R.string.file_exist, fn), commander);
              if (res == Commander.SKIP) continue;
              if (res == Commander.ABORT) break;
              if (res == Commander.REPLACE) {
                File dest_file = new File(getPath(dest_uri, false));
                if (dest_file.equals(file)) {
                  Log.w(TAG, "Not going to copy file to itself");
                  continue;
                }
                Log.v(TAG, "Overwritting file " + fn);
                DocumentsContract.deleteDocument(cr, dest_uri);
              }
            } else mime = Utils.getMimeByExt(Utils.getFileExt(fn));
            dest_uri = DocumentsContract.createDocument(cr, dest, mime, fn);
            if (dest_uri == null) {
              error(ctx.getString(R.string.cant_create, fn, ""));
              break;
            }
            String dest_path = dest_uri.getPath();
            if (dest_path.indexOf(fn, dest_path.length() - fn.length() - 1) < 0) // SAF suxx
            dest_uri = DocumentsContract.renameDocument(cr, dest_uri, fn);

            is = new FileInputStream(file);
            os = cr.openOutputStream(dest_uri);
            long copied = 0, size = file.length();

            long start_time = 0;
            int speed = 0;
            int so_far = (int) (totalBytes * conv);

            String sz_s = Utils.getHumanSize(size);
            int fnl = fn.length();
            String rep_s =
                ctx.getString(
                    R.string.copying, fnl > CUT_LEN ? "\u2026" + fn.substring(fnl - CUT_LEN) : fn);
            int n = 0;
            long nn = 0;

            while (true) {
              if (nn == 0) {
                start_time = System.currentTimeMillis();
                sendProgress(
                    rep_s + sizeOfsize(copied, sz_s), so_far, (int) (totalBytes * conv), speed);
              }
              n = is.read(buf);
              if (n < 0) {
                long time_delta = System.currentTimeMillis() - start_time;
                if (time_delta > 0) {
                  speed = (int) (MILLI * nn / time_delta);
                  sendProgress(
                      rep_s + sizeOfsize(copied, sz_s), so_far, (int) (totalBytes * conv), speed);
                }
                break;
              }
              os.write(buf, 0, n);
              nn += n;
              copied += n;
              totalBytes += n;
              if (isStopReq()) {
                Log.d(TAG, "Interrupted!");
                error(ctx.getString(R.string.canceled));
                return counter;
              }
              long time_delta = System.currentTimeMillis() - start_time;
              if (time_delta > DELAY) {
                speed = (int) (MILLI * nn / time_delta);
                // Log.v( TAG, "bytes: " + nn + " time: " + time_delta + " speed: " + speed );
                nn = 0;
              }
            }
            is.close();
            os.close();
            is = null;
            os = null;
            /*
            ContentValues cv = new ContentValues();
            cv.put( Document.COLUMN_LAST_MODIFIED, file.lastModified() );
            cr.update( dest_uri, cv, null, null ); //throws..
            */
            if (i >= list.length - 1)
              sendProgress(
                  ctx.getString(R.string.copied_f, fn) + sizeOfsize(copied, sz_s),
                  (int) (totalBytes * conv));
            counter++;
          }
          if (move) {
            if (!file.delete()) {
              sendProgress(ctx.getString(R.string.cant_del, fn), -1);
              delerr_counter++;
            }
          }
        } catch (Exception e) {
          Log.e(TAG, "", e);
          error(ctx.getString(R.string.rtexcept, file.getAbsolutePath(), e.getMessage()));
        } finally {
          try {
            if (is != null) is.close();
            if (os != null) os.close();
          } catch (IOException e) {
            error(ctx.getString(R.string.acc_err, file.getAbsolutePath(), e.getMessage()));
          }
        }
      }
      return counter;
    }
示例#18
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    int sortMode = TRACK_MENU;
    if (icicle == null) {
      mSelectedUri = getIntent().getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
    } else {
      mSelectedUri = (Uri) icicle.getParcelable(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
      // Retrieve list state. This will be applied after the
      // QueryHandler has run
      mListState = icicle.getParcelable(LIST_STATE_KEY);
      mListHasFocus = icicle.getBoolean(FOCUS_KEY);
      sortMode = icicle.getInt(SORT_MODE_KEY, sortMode);
    }
    if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) {
      mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    } else {
      mBaseUri = getIntent().getData();
      if (mBaseUri == null) {
        Log.w("MusicPicker", "No data URI given to PICK action");
        finish();
        return;
      }
    }

    setContentView(R.layout.music_picker);
    if (android.os.Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_REMOVED)
        || android.os.Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_UNMOUNTED)) {
      Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show();
    }

    mSortOrder = MediaStore.Audio.Media.TITLE_KEY;

    final ListView listView = getListView();

    listView.setItemsCanFocus(false);

    mAdapter =
        new TrackListAdapter(
            this, listView, R.layout.music_picker_item, new String[] {}, new int[] {});

    setListAdapter(mAdapter);

    listView.setTextFilterEnabled(true);

    // We manually save/restore the listview state
    listView.setSaveEnabled(false);

    mQueryHandler = new QueryHandler(this);

    mProgressContainer = findViewById(R.id.progressContainer);
    mListContainer = findViewById(R.id.listContainer);

    mOkayButton = findViewById(R.id.okayButton);
    mOkayButton.setOnClickListener(this);
    mCancelButton = findViewById(R.id.cancelButton);
    mCancelButton.setOnClickListener(this);

    // If there is a currently selected Uri, then try to determine who
    // it is.
    if (mSelectedUri != null) {
      Uri.Builder builder = mSelectedUri.buildUpon();
      String path = mSelectedUri.getEncodedPath();
      int idx = path.lastIndexOf('/');
      if (idx >= 0) {
        path = path.substring(0, idx);
      }
      builder.encodedPath(path);
      Uri baseSelectedUri = builder.build();
      if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri);
      if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri);
      if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri);
      if (baseSelectedUri.equals(mBaseUri)) {
        // If the base Uri of the selected Uri is the same as our
        // content's base Uri, then use the selection!
        mSelectedId = ContentUris.parseId(mSelectedUri);
      }
    }

    setSortMode(sortMode);
  }
示例#19
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    mAlertBuilder = new AlertDialog.Builder(this);
    gAlertBuilder = mAlertBuilder; //  keep a static copy of this that other classes can use

    if (core == null) {
      core = (MuPDFCore) getLastNonConfigurationInstance();

      if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
        mFileName = savedInstanceState.getString("FileName");
      }
    }
    if (core == null) {
      Intent intent = getIntent();
      byte buffer[] = null;

      if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        Uri uri = intent.getData();
        System.out.println("URI to open is: " + uri);
        if (uri.toString().startsWith("content://")) {
          String reason = null;
          try {
            InputStream is = getContentResolver().openInputStream(uri);
            int len = is.available();
            buffer = new byte[len];
            is.read(buffer, 0, len);
            is.close();
          } catch (java.lang.OutOfMemoryError e) {
            System.out.println("Out of memory during buffer reading");
            reason = e.toString();
          } catch (Exception e) {
            System.out.println("Exception reading from stream: " + e);

            // Handle view requests from the Transformer Prime's file manager
            // Hopefully other file managers will use this same scheme, if not
            // using explicit paths.
            // I'm hoping that this case below is no longer needed...but it's
            // hard to test as the file manager seems to have changed in 4.x.
            try {
              Cursor cursor =
                  getContentResolver().query(uri, new String[] {"_data"}, null, null, null);
              if (cursor.moveToFirst()) {
                String str = cursor.getString(0);
                if (str == null) {
                  reason = "Couldn't parse data in intent";
                } else {
                  uri = Uri.parse(str);
                }
              }
            } catch (Exception e2) {
              System.out.println("Exception in Transformer Prime file manager code: " + e2);
              reason = e2.toString();
            }
          }
          if (reason != null) {
            buffer = null;
            Resources res = getResources();
            AlertDialog alert = mAlertBuilder.create();
            setTitle(String.format(res.getString(R.string.cannot_open_document_Reason), reason));
            alert.setButton(
                AlertDialog.BUTTON_POSITIVE,
                getString(R.string.dismiss),
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    finish();
                  }
                });
            alert.show();
            return;
          }
        }
        if (buffer != null) {
          core = openBuffer(buffer, intent.getType());
        } else {
          String path = Uri.decode(uri.getEncodedPath());
          if (path == null) {
            path = uri.toString();
          }
          core = openFile(path);
        }
        SearchTaskResult.set(null);
      }
      if (core != null && core.needsPassword()) {
        requestPassword(savedInstanceState);
        return;
      }
      if (core != null && core.countPages() == 0) {
        core = null;
      }
    }
    if (core == null) {
      AlertDialog alert = mAlertBuilder.create();
      alert.setTitle(R.string.cannot_open_document);
      alert.setButton(
          AlertDialog.BUTTON_POSITIVE,
          getString(R.string.dismiss),
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              finish();
            }
          });
      alert.setOnCancelListener(
          new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
              finish();
            }
          });
      alert.show();
      return;
    }

    createUI(savedInstanceState);

    //  hide the proof button if this file can't be proofed
    if (!core.canProof()) {
      mProofButton.setVisibility(View.INVISIBLE);
    }

    if (isProofing()) {

      //  start the activity with a new array
      mSepEnabled = null;

      //  show the separations button
      mSepsButton.setVisibility(View.VISIBLE);

      //  hide some other buttons
      mLinkButton.setVisibility(View.INVISIBLE);
      mReflowButton.setVisibility(View.INVISIBLE);
      mOutlineButton.setVisibility(View.INVISIBLE);
      mSearchButton.setVisibility(View.INVISIBLE);
      mMoreButton.setVisibility(View.INVISIBLE);
    } else {
      //  hide the separations button
      mSepsButton.setVisibility(View.INVISIBLE);
    }
  }
 public static Uri maxsContactUriFrom(Uri uri) {
   String pathSegment = uri.getEncodedPath();
   return Uri.withAppendedPath(CONTACTS_MODULE_AUTHORITY, pathSegment);
 }