コード例 #1
1
  private static void enqueueDownload(
      Context context,
      Uri uri,
      Uri destinationUri,
      String description,
      String mimeType,
      String mediaType,
      boolean wifiOnly) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      final DownloadManager dm =
          (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
      DownloadManager.Request request = new DownloadManager.Request(uri);

      request.setDestinationUri(destinationUri);
      request.setDescription(description);
      if (mediaType != null) {
        request.addRequestHeader("Accept", mediaType);
      }
      if (mimeType != null) {
        request.setMimeType(mimeType);
      }
      if (wifiOnly) {
        restrictDownloadToWifi(request);
      }
      request.setAllowedOverRoaming(false);

      dm.enqueue(request);
    } else {
      // HACK alert:
      // Gingerbread's DownloadManager needlessly rejected HTTPS URIs. Circumvent that
      // by building and enqueing the request to the provider by ourselves. This is safe
      // as we only rely on internal API that won't change anymore.
      ContentValues values = new ContentValues();
      values.put("uri", uri.toString());
      values.put("is_public_api", true);
      values.put("notificationpackage", context.getPackageName());
      values.put("destination", 4);
      values.put("hint", destinationUri.toString());
      if (mediaType != null) {
        values.put("http_header_0", "Accept:" + mediaType);
      }
      values.put("description", description);
      if (mimeType != null) {
        values.put("mimetype", mimeType);
      }
      values.put("visibility", 0);
      values.put("allowed_network_types", wifiOnly ? DownloadManager.Request.NETWORK_WIFI : ~0);
      values.put("allow_roaming", false);
      values.put("is_visible_in_downloads_ui", true);

      context.getContentResolver().insert(Uri.parse("content://downloads/my_downloads"), values);
    }
  }
コード例 #2
0
  public void setCaptImage(Uri ur, int src) {
    BitMapManipulation bm = new BitMapManipulation();
    // String path;
    switch (imgIdG) {
      case 0:
        captView[0].findViewById(R.id.captBtn1).setVisibility(View.GONE);
        captImg[0].setVisibility(View.VISIBLE);
        captImg[0].setLongClickable(true);
        captImg[0].setOnTouchListener(this);

        if (captImg[0] != null) {
          captImg[0].destroyDrawingCache();
        }
        System.gc();
        Runtime.getRuntime().gc();
        bmp[0] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
        resetView(captImg[0]);
        captImg[0].setImageBitmap(bmp[0]);
        captImg[0].invalidate();

        Toast.makeText(this, "id: " + imgIdG, Toast.LENGTH_SHORT).show();
        break;
      case 1:
        if (MAX_COL == 1) {
          captView[1].findViewById(R.id.captBtn1).setVisibility(View.GONE);
          captImg[1].setVisibility(View.VISIBLE);
          captImg[1].setOnTouchListener(this);
          bmp[1] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
          resetView(captImg[1]);
          captImg[1].setImageBitmap(bmp[1]);
        } else {
          captView[0].findViewById(R.id.captBtn2).setVisibility(View.GONE);
          captImg[1].setVisibility(View.VISIBLE);
          captImg[1].setOnTouchListener(this);
          bmp[1] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
          resetView(captImg[1]);
          captImg[1].setImageBitmap(bmp[1]);
        }
        Toast.makeText(this, "id: " + imgIdG, Toast.LENGTH_SHORT).show();
        break;
      case 2:
        captView[1].findViewById(R.id.captBtn1).setVisibility(View.GONE);
        captImg[2].setVisibility(View.VISIBLE);
        captImg[2].setOnTouchListener(this);
        bmp[2] = bm.createBMP(src, ur.toString(), captImg[2].getWidth(), captImg[2].getHeight());
        resetView(captImg[2]);
        captImg[2].setImageBitmap(bmp[2]);
        break;
      case 3:
        captView[1].findViewById(R.id.captBtn2).setVisibility(View.GONE);
        captImg[3].setVisibility(View.VISIBLE);
        captImg[3].setOnTouchListener(this);
        bmp[3] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
        resetView(captImg[3]);
        captImg[3].setImageBitmap(bmp[3]);
        break;
    }
    System.gc();
    Runtime.getRuntime().gc();
  }
コード例 #3
0
 public static Intent getSaveIntent(
     Context context,
     ImagePreset preset,
     File destination,
     Uri selectedImageUri,
     Uri sourceImageUri,
     boolean doFlatten,
     int quality,
     float sizeFactor,
     boolean needsExit) {
   Intent processIntent = new Intent(context, ProcessingService.class);
   processIntent.putExtra(ProcessingService.SOURCE_URI, sourceImageUri.toString());
   processIntent.putExtra(ProcessingService.SELECTED_URI, selectedImageUri.toString());
   processIntent.putExtra(ProcessingService.QUALITY, quality);
   processIntent.putExtra(ProcessingService.SIZE_FACTOR, sizeFactor);
   if (destination != null) {
     processIntent.putExtra(ProcessingService.DESTINATION_FILE, destination.toString());
   }
   processIntent.putExtra(ProcessingService.PRESET, preset.getJsonString(ImagePreset.JASON_SAVED));
   processIntent.putExtra(ProcessingService.SAVING, true);
   processIntent.putExtra(ProcessingService.EXIT, needsExit);
   if (doFlatten) {
     processIntent.putExtra(ProcessingService.FLATTEN, true);
   }
   return processIntent;
 }
コード例 #4
0
ファイル: MapDemoActivity.java プロジェクト: phreed/cs282
  /**
   * Performed when the show location button is clicked. - extract and validate the latitude and
   * longitude - try starting activities with various intents
   *
   * @param view the button view object (unused)
   */
  public void showLocation(View view) {

    final Double latitude = extractLatitude(this.latitudeView);
    final Double longitude = extractLongitude(this.longitudeView);
    if (longitude.isNaN() || latitude.isNaN()) return;

    final Uri geoUri = getLocationUri(geoUriPrefix, latitude, longitude);
    Log.d(TAG, "starting activity with " + geoUri.toString());

    try {
      final Intent locateIntent = new Intent(android.content.Intent.ACTION_VIEW, geoUri);
      startActivity(locateIntent);
      // Activity started successfully
      return;
    } catch (ActivityNotFoundException ex) {
      Log.w(TAG, "no application to handle the intent " + geoUri.toString());
    }

    final Uri gmapsUri = getLocationUri(gmapsUriPrefix, latitude, longitude);
    Log.d(TAG, "starting activity with " + gmapsUri.toString());

    try {
      final Intent locateIntent = new Intent(android.content.Intent.ACTION_VIEW, gmapsUri);
      startActivity(locateIntent);
      // Activity started successfully
      return;
    } catch (ActivityNotFoundException ex) {
      Log.w(TAG, "no application to handle the intent " + gmapsUri.toString());
      Toast.makeText(MapDemoActivity.this, R.string.no_app_capable, Toast.LENGTH_LONG).show();
    }
  }
コード例 #5
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();
  }
コード例 #6
0
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Constants.REQUEST_CAMERA) {
      try {
        if (resultCode == Activity.RESULT_OK) {
          // displayPhotoActivity(1);

          PreferenceHelper.getPrefernceHelperInstace(getActivity())
              .setString(PreferenceHelper.IMAGE_URL, imageUri.toString());

          Picasso.with(getActivity()).load(imageUri).centerCrop().fit().into(profilePic);

        } else {
          UriToUrl.deleteUri(getActivity(), imageUri);
        }
      } catch (Exception e) {
        // Toaster.make(getApplicationContext(),
        // R.string.error_img_not_found);
      }
    } else if (resultCode == Activity.RESULT_OK && requestCode == Constants.REQUEST_GALLERY) {
      try {
        imageUri = data.getData();

        PreferenceHelper.getPrefernceHelperInstace(getActivity())
            .setString(PreferenceHelper.IMAGE_URL, imageUri.toString());

        Picasso.with(getActivity()).load(imageUri).centerCrop().fit().into(profilePic);
        // displayPhotoActivity(2);
      } catch (Exception e) {
        // Toaster.make(getApplicationContext(),
        // R.string.error_img_not_found);
      }
    }
  }
コード例 #7
0
 /*
  * send file to other device via wifi-d
  */
 private void sendFile(final WifiP2pInfo info) {
   String logcomments = "Default log comment";
   // KH - getFileToSend now writes to external storage, so keep this if
   if (isExternalStorageWritable()) {
     File file = getFileToSend();
     if (file != null) {
       Uri uri = Uri.fromFile(file);
       statusText.setText(
           "Sending file: "
               + uri.toString()
               + "\nAt: "
               + Utils.getDateAndTime()
               + "\n of size: "
               + file.length()
               + " B");
       Log.d(TAG, "Sending file: " + uri.toString() + "\nAt: " + Utils.getDateAndTime());
       Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
       serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
       serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
       serviceIntent.putExtra(
           FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
           info.groupOwnerAddress.getHostAddress());
       serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, PORT);
       logcomments = logComment.getText().toString();
       serviceIntent.putExtra(FileTransferService.EXTRAS_LOG_COMMENT, logcomments);
       getActivity().startService(serviceIntent);
     } else {
       statusText.setText("File to send does not exist! ");
       Log.d(TAG, "File to send does not exist! ");
     }
   } else {
     statusText.setText("Storage is not writeable");
     Log.d(TAG, "Storage is not writeable");
   }
 }
コード例 #8
0
 /**
  * Creates a cursor loader, based on the appropriate URI builder of the contract class.
  *
  * @param dataUri The data uri of the key the photos of which we are interested in.
  */
 public static CursorLoader createLoader(Activity activity, Uri dataUri) {
   Log.d(Constants.TAG, "Photo Attributes Adapter cursor loader - dataUri: " + dataUri.toString());
   Uri baseUri = KeychainContract.UserPackets.buildPhotoAttributesUri(dataUri);
   Log.d(Constants.TAG, "baseUri: " + baseUri.toString());
   return new CursorLoader(
       activity, baseUri, PhotoAttributesAdapter.USER_PACKETS_PROJECTION, null, null, null);
 }
コード例 #9
0
    @Override
    protected List<MovieBean> doInBackground(String... params) {

      Log.d(LOG_TAG, "Inside doInBackground() sort by ==> " + params[0]);

      if (params.length == 0) return null;

      HttpURLConnection httpURLConnection = null;
      BufferedReader reader = null;
      String movieListJson = null;

      try {
        Uri builtUri =
            Uri.parse(URLConstants.FETCH_MOVIE_BASE_URL)
                .buildUpon()
                .appendPath(params[0])
                .appendQueryParameter(URLConstants.API_KEY_PARAM, PlatformConstants.API_KEY)
                .build();

        Log.d(LOG_TAG, "uri => " + builtUri.toString());

        URL url = new URL(builtUri.toString());

        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();

        InputStream inputStream = httpURLConnection.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();

        if (inputStream == null) {
          movieListJson = null;
        }

        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
          stringBuffer.append(line + "\n");
        }

        if (stringBuffer.length() == 0) {
          movieListJson = null;
        }

        movieListJson = stringBuffer.toString();

      } catch (MalformedURLException e) {
        Log.d(LOG_TAG, "MalformedURLException " + e.getMessage());
      } catch (IOException e) {
        Log.e(LOG_TAG, "IOException => " + e.getMessage());
      }

      try {
        return getMovieBeanListFromJson(movieListJson);
      } catch (JSONException e) {
        e.printStackTrace();
      }

      return null;
    }
コード例 #10
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   Intent intent = getIntent();
   Uri uri = intent.getData();
   if (uri != null) {
     MainActivity.addLink(this, uri.toString());
     Uri newUri = Uri.parse("view-source:" + uri.toString());
     startChrome(newUri);
   }
   if (Intent.ACTION_SEND.equals(intent.getAction())) {
     Bundle extras = intent.getExtras();
     if (extras != null) {
       String text = extras.getString(Intent.EXTRA_TEXT);
       Pattern pattern = Pattern.compile(URL_PATTERN);
       if (text != null) {
         Matcher m = pattern.matcher(text);
         if (m.find()) {
           String url = m.group(1);
           MainActivity.addLink(this, url);
           Uri newUri = Uri.parse("view-source:" + url);
           startChrome(newUri);
         }
       }
     }
   }
   this.finish();
 }
コード例 #11
0
  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] parameters = getIntent().getStringArrayExtra(EXTRAS);
    if (parameters != null) {
      for (String s : parameters) {
        s = s.replace("\\,", ",");
      }
    }
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      Uri uri = getIntent().getData();
      if (uri != null) {
        Log.i(TAG, "MojoShellActivity opening " + uri);
        if (parameters == null) {
          parameters = new String[] {uri.toString()};
        } else {
          String[] newParameters = new String[parameters.length + 1];
          System.arraycopy(parameters, 0, newParameters, 0, parameters.length);
          newParameters[parameters.length] = uri.toString();
          parameters = newParameters;
        }
      }
    }

    // TODO(ppi): Gotcha - the call below will work only once per process lifetime, but the OS
    // has no obligation to kill the application process between destroying and restarting the
    // activity. If the application process is kept alive, initialization parameters sent with
    // the intent will be stale.
    // TODO(qsr): We should be passing application context here as required by
    // InitApplicationContext on the native side. Currently we can't, as PlatformViewportAndroid
    // relies on this being the activity context.
    ShellMain.ensureInitialized(this, parameters);
    ShellMain.start();
  }
コード例 #12
0
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   Log.i(TAG, " requestcode: " + requestCode);
   Log.i(TAG, " resultCode: " + resultCode);
   switch (requestCode) {
     case 100:
       if (resultCode == Activity.RESULT_OK) {
         Uri selectedImage = imageUri;
         getActivity().getContentResolver().notifyChange(selectedImage, null);
         ContentResolver cr = getActivity().getContentResolver();
         Bitmap bitmap;
         try {
           bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
           imgFavorite.setImageBitmap(bitmap);
           Log.i(TAG, " butmap " + bitmap.toString());
           Log.i(TAG, " img view " + imgFavorite.toString());
           Log.i(TAG, " img uri " + imageUri.toString());
           imageAdapter.addmThumbIds(imageUri.toString());
         } catch (Exception e) {
           Log.e("Camera", e.toString());
         } finally {
           imageAdapter.notifyDataSetChanged();
         }
       }
   }
 }
コード例 #13
0
ファイル: Util.java プロジェクト: huanghua119/LovelyNote
  public static Bitmap getBitmap(ContentResolver contentResolver, Uri uri) {
    InputStream in = null;
    try {
      in = contentResolver.openInputStream(uri);

      // Decode image size
      BitmapFactory.Options o = new BitmapFactory.Options();
      o.inJustDecodeBounds = true;

      BitmapFactory.decodeStream(in, null, o);
      in.close();

      int scale = Util.scalePow2(o.outHeight, o.outWidth);
      BitmapFactory.Options o2 = new BitmapFactory.Options();
      o2.inSampleSize = scale;
      in = contentResolver.openInputStream(uri);
      Bitmap b = BitmapFactory.decodeStream(in, null, o2);
      in.close();

      return b;
    } catch (FileNotFoundException e) {
      Log.e(TAG, "file " + uri.toString() + " not found");
    } catch (IOException e) {
      Log.e(TAG, "file " + uri.toString() + " not found");
    }
    return null;
  }
コード例 #14
0
ファイル: SGFLoadActivity.java プロジェクト: jinhu/gobandroid
  public String uri2string(Uri intent_uri)
      throws FileNotFoundException, MalformedURLException, IOException {

    if (intent_uri.toString().startsWith("/"))
      return FileHelper.file2String(new File(intent_uri.toString()));

    InputStream in;

    if (intent_uri.toString().startsWith("content://"))
      in = getContentResolver().openInputStream(intent_uri);
    else in = new BufferedInputStream(new URL("" + intent_uri).openStream(), 4096);

    FileOutputStream file_writer = null;

    // if it comes from network
    if (intent_uri.toString().startsWith("http")) { // https catched also
      new File(GoPrefs.getSGFPath() + "/downloads").mkdirs();
      File f = new File(GoPrefs.getSGFPath() + "/downloads/" + intent_uri.getLastPathSegment());
      f.createNewFile();
      file_writer = new FileOutputStream(f);
    }

    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1; ) {
      out.append(new String(b, 0, n));
      if (file_writer != null) file_writer.write(b, 0, n);
    }
    if (file_writer != null) file_writer.close();

    return out.toString();
  }
コード例 #15
0
 public static String loadArticles(Article.Category category, int page) throws IOException {
   if (page > 0) {
     Uri uri = Uri.parse(category.link);
     uri = uri.buildUpon().appendPath("page").appendPath(page + "").build();
     Log.d(LOG_TAG, "Link to load: " + uri.toString());
     return load(new URL(uri.toString()));
   } else throw new IllegalArgumentException("Page number should be > 0");
 }
コード例 #16
0
 public void setImage(Uri uri) {
   ImageDownloadManager manager = ImageDownloadManager.GetInstance();
   if (mUri != null) manager.cancelLoad(mUri.toString());
   mUri = uri;
   // this.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.image_default));
   AFLog.d("start load in cache view: " + uri.toString());
   manager.loadImage(this, uri);
 }
コード例 #17
0
 /**
  * Creates and returns the correct render builder for the specified VideoType and uri.
  *
  * @param renderType The RenderType to use for creating the correct RenderBuilder
  * @param uri The video's Uri
  * @param defaultMediaType The MediaType to use when auto-detection fails
  * @return The appropriate RenderBuilder
  */
 private RenderBuilder getRendererBuilder(
     VideoType renderType, Uri uri, MediaUtil.MediaType defaultMediaType) {
   switch (renderType) {
     case HLS:
       return new HlsRenderBuilder(getContext(), getUserAgent(), uri.toString());
     default:
       return new RenderBuilder(getContext(), getUserAgent(), uri.toString(), defaultMediaType);
   }
 }
コード例 #18
0
  public List<Arrival> busTimetable(final Arrival arrival) throws Exception {
    final Calendar now = Calendar.getInstance(Locale.UK);

    final Uri url =
        Uri.parse("http://transportapi.com")
            .buildUpon()
            .path(
                String.format(
                    "v3/uk/bus/route/%s/%s/inbound/%s/%s/%s/timetable",
                    arrival.bus.operator,
                    arrival.bus.route,
                    arrival.stop.atcocode,
                    dateFormat.format(now.getTime()),
                    timeFormat.format(now.getTime())))
            .appendQueryParameter("api_key", apiKey)
            .appendQueryParameter("app_id", appId)
            .appendQueryParameter("group", "no")
            .build();
    Log.d("JSON API", String.format("Requesting %s", url));

    final HttpResponse response = http.execute(new HttpGet(url.toString()));
    final StatusLine status = response.getStatusLine();

    if (status.getStatusCode() != HttpStatus.SC_OK) {
      response.getEntity().getContent().close();
      throw new IOException(status.getReasonPhrase());
    }

    final Document doc = Jsoup.parse(EntityUtils.toString(response.getEntity()), url.toString());
    final Element stopList = doc.getElementsByClass("busroutelist").first();
    final Elements stopListItems = stopList.getElementsByTag("li");

    ArrayList<Arrival> result = new ArrayList<Arrival>();
    for (Element stopListItem : stopListItems) {
      String destcode;
      String destname;
      Time desttime;

      Element timeElement = stopListItem.getElementsByClass("routelist-time").first();
      desttime = parseSimpleTime(timeElement.text().substring(0, 5));

      Element destElement = stopListItem.getElementsByClass("routelist-destination").first();
      String href = destElement.getElementsByTag("a").first().attr("href");
      destcode = href;
      if (destcode.startsWith("/v3/uk/bus/stop/")) {
        destcode = destcode.substring("/v3/uk/bus/stop/".length());
      }
      if (destcode.indexOf('/') > 0) {
        destcode = destcode.substring(0, destcode.indexOf('/'));
      }

      destname = destElement.text();

      result.add(new Arrival(arrival.bus, new Stop(destcode, destname), desttime));
    }
    return result;
  }
コード例 #19
0
  private void handleActivityResult(@NonNull Intent data, int reqCode) throws SecurityException {
    final Uri uri;
    String filePath = null;
    if (reqCode == REQUEST_PICK_FILE) {
      uri = data.getData();
      if (uri != null) {
        filePath = uri.getPath();
      }
    } else {
      uri = null;
      filePath = data.getStringExtra("path");
    }

    Timber.i("uri: %s, filepath: %s", uri, filePath);

    if (!Utils.fileExists(filePath) && uri != null) {
      final ContentResolver cr = getContentResolver();
      Cursor cursor = null;
      try {
        cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToNext()) {
          int index = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
          if (index >= 0) {
            filePath = cursor.getString(index);
          } else if (Build.VERSION.SDK_INT >= 19
              && uri.toString().startsWith(ContentResolver.SCHEME_CONTENT)) {
            String newUri =
                new Uri.Builder()
                    .scheme(ContentResolver.SCHEME_CONTENT)
                    .authority(uri.getAuthority())
                    .appendPath("document")
                    .build()
                    .toString();
            String path = uri.toString();
            index = filePath.indexOf(":");
            if (path.startsWith(newUri) && index >= 0) {
              String firstPath = filePath.substring(0, index);
              filePath = filePath.substring(index + 1);
              String storage = IOUtils.get().getPrimarySdCard();
              if (!firstPath.contains(ROOT_ID_PRIMARY_EMULATED)) {
                storage = IOUtils.get().getSecondarySdCard();
              }
              filePath = storage + "/" + filePath;
            } else {
              filePath = null;
            }
          }
        }
      } finally {
        if (cursor != null) cursor.close();
      }
    }

    if (sCallback != null) {
      sCallback.fileRequested(filePath);
    }
  }
コード例 #20
0
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   Intent intent = getIntent();
   Uri data = intent.getData();
   if (data != null) {
     Toast.makeText(this, "Activity opened by deep link: " + data.toString(), Toast.LENGTH_LONG);
     Log.i(TAG, "Deep link is " + data.toString());
   }
 }
コード例 #21
0
ファイル: BaseCache.java プロジェクト: Ityang/Sea_monster
 protected ReentrantLock getLockForDiskCacheEdit(Uri uri) {
   synchronized (mDiskCacheEditLocks) {
     ReentrantLock lock = mDiskCacheEditLocks.get(uri.toString());
     if (null == lock) {
       lock = new ReentrantLock();
       mDiskCacheEditLocks.put(uri.toString(), lock);
     }
     return lock;
   }
 }
コード例 #22
0
  private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
      // not ready for playback just yet, will try again later
      return;
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
      mMediaPlayer.reset();
      mMediaPlayer.release();
      mMediaPlayer = null;
    }
    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setOnPreparedListener(mPreparedListener);
      mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
      mIsPrepared = false;
      Log.v(TAG, "reset duration to -1 in openVideo");
      mDuration = -1;
      mMediaPlayer.setOnCompletionListener(mCompletionListener);
      mMediaPlayer.setOnErrorListener(mErrorListener);
      mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
      mCurrentBufferPercentage = 0;
      if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
        AssetFileDescriptor afd = null;
        try {
          String path = mUri.toString().substring("file:///android_asset/".length());
          afd = getContext().getAssets().openFd(path);
          mMediaPlayer.setDataSource(
              afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        } finally {
          if (afd != null) {
            afd.close();
          }
        }
      } else {
        setDataSource();
      }
      mMediaPlayer.setDisplay(mSurfaceHolder);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.setScreenOnWhilePlaying(true);
      mMediaPlayer.prepareAsync();
      attachMediaController();
    } catch (IOException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    } catch (IllegalArgumentException ex) {
      Log.w(TAG, "Unable to open content: " + mUri, ex);
      return;
    }
  }
コード例 #23
0
  private void deleteRecordImpl(File filePath, String mimeType) {
    String absFilePath = filePath.getAbsolutePath();
    String[] projection = new String[1];
    String selection = null;
    Uri queryUri = null;
    Log.d(TAG, "mimeType:" + mimeType + "  filePath.getAbsolutePath(): " + absFilePath);

    if (mimeType.startsWith("image/")) {
      projection[0] = MediaStore.Images.Media._ID;
      selection = MediaStore.Images.Media.DATA;
      queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if (mimeType.startsWith("video/")) {
      projection[0] = MediaStore.Video.Media._ID;
      selection = MediaStore.Video.Media.DATA;
      queryUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if (mimeType.startsWith("audio/")) {
      projection[0] = MediaStore.Audio.Media._ID;
      selection = MediaStore.Audio.Media.DATA;
      queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    } else {
      Log.d(TAG, "not support mimeType:" + mimeType + "  not deleteRecord()   Return;");
      return;
    }

    Log.d(TAG, "queryUri = " + queryUri.toString());

    // (the other possibility is "internal")
    // Uri imageUri =
    // MediaStore.Images.Media.getContentUri("external");//MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    // Log.d(TAG,"imageUri = " + imageUri.toString());

    // String[] projection = {MediaStore.Images.Media._ID};
    Cursor cursor =
        mContentResolver.query(
            queryUri, projection, selection + " LIKE ?", new String[] {absFilePath}, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
    // Log.d(TAG,"cursor.getColumnName():" + cursor.getColumnName(columnIndex2));

    String idString = cursor.getString(columnIndex);
    Log.d(TAG, "cursor.getCount(): " + cursor.getCount() + "  idString : " + idString);

    // Uri contentPathUri = Uri.parse(cursor.getString(columnIndex));
    // Log.d(TAG, "contentPathUri.getPath() : " + contentPathUri.getPath());
    // Log.d(TAG, "contentPathUri.toString() : " + contentPathUri.toString());

    Uri dstContentUri = Uri.withAppendedPath(queryUri, idString);

    Log.d(TAG, "CR.delete dstContentUri.toString() " + dstContentUri.toString());
    cursor.close();

    mContentResolver.delete(dstContentUri, "", null);
  }
コード例 #24
0
 /** Read the optional fields in the form and fill in the site */
 private void getOptionalFields() {
   site.setName(etName.getText().toString());
   site.setAddress(etAddress.getText().toString());
   site.setPostnr(etPostnr.getText().toString());
   site.setPostaddress(etPostaddress.getText().toString());
   site.setCoordinates(etCoord.getText().toString());
   if (imageUri != null) {
     Log.d(TAG, "Saving URI: " + imageUri.toString());
     site.setImageUriStr(imageUri.toString());
   }
 }
コード例 #25
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {

    // start
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browserhook);
    mDbHelperConverter = new Converter(this);
    mDbHelperConverter.open();
    mDBHelperHistory = new History(this);
    mDBHelperHistory.open();
    mSharedPrefs = getSharedPreferences(PREFS_NAME, 0);

    // bind
    mWdgDirectBtn = (Button) findViewById(R.id.ButtonDirect);
    mWdgDirectBtn.setOnClickListener(this);
    mWdgConvertBtn = (Button) findViewById(R.id.ButtonConvert);
    mWdgConvertBtn.setOnClickListener(this);
    mWdgHistoryBtn = (Button) findViewById(R.id.ButtonHistory);
    mWdgHistoryBtn.setOnClickListener(this);
    mWdgSettingBtn = (Button) findViewById(R.id.ButtonSetting);
    mWdgSettingBtn.setOnClickListener(this);

    // インテントが渡されたか単体起動かを判別
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      URI = getIntent().getData();
      setTitle(getText(R.string.apptitle_main).toString() + ": " + URI.toString()); // タイトルを設定
      IS_STANDALONE = false;
      // Log.d(TAG, "oc:i:got");

      // 履歴が許可されているなら記録
      final Boolean historyAvailable = mSharedPrefs.getBoolean(sPrefKeyDisableHistory, false);
      if (!historyAvailable) {
        Date currentTime_1 = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = formatter.format(currentTime_1);
        // Log.d(TAG, "sba:cv:" + dateString);
        mDBHelperHistory.createItem(URI.toString(), dateString);
      }

      // load shared prefs
      mLastBrowser = mSharedPrefs.getString("lastBrowser", "");

      // build spinner
      buildBrowserSpinner();
      buildConvertSpinner();

    } else {
      IS_STANDALONE = true;
      startConverterlistActivity();
      finish();
    }
    return;
  }
コード例 #26
0
  /*
   * onStartActivity for camera intent and browsing images from gallery
   */
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    /*
     * setting images from camera click intent
     */
    try {
      if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

          /*
           * setting of images captured from camera in imageView
           */
          setCaptImage(fileUri, 0);
          savedPaths[savedIndex] = fileUri.toString();
          savedIndex = (savedIndex + 1) % 2;
          // setPref(fileUri.getPath());
          HomeScreenActivity.appPref.savePath(fileUri.getPath());
        } else if (resultCode == RESULT_CANCELED) {
          // User cancelled the image capture
        } else {
          // Image capture failed, advise user
        }
      }
    } catch (Exception e) {
      Toast.makeText(CaptureActivity.this, "Unable to load image !!", Toast.LENGTH_SHORT).show();
    }

    /*
     * setting images browsing from gallery
     */
    try {
      if (requestCode == SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        // setPref(picturePath);
        HomeScreenActivity.appPref.savePath(picturePath);
        Uri ur = Uri.parse(picturePath);
        savedPaths[savedIndex] = ur.toString();
        savedIndex = (savedIndex + 1) % 2;
        setCaptImage(ur, 1);
        cursor.close();
      }
    } catch (Exception e) {
      Toast.makeText(CaptureActivity.this, "Unable to load image !!", Toast.LENGTH_SHORT).show();
    }
  }
コード例 #27
0
 public final ArrayList<SAFItem> getChildren(Uri u) {
   Cursor c = null;
   try {
     try {
       ContentResolver cr = ctx.getContentResolver();
       String document_id = DocumentsContract.getDocumentId(u);
       Uri children_uri = DocumentsContract.buildChildDocumentsUriUsingTree(u, document_id);
       // Log.d( TAG, "Children URI:" + children_uri );
       final String[] projection = {
         Document.COLUMN_DOCUMENT_ID,
         Document.COLUMN_DISPLAY_NAME,
         Document.COLUMN_LAST_MODIFIED,
         Document.COLUMN_MIME_TYPE,
         Document.COLUMN_SIZE
       };
       c = cr.query(children_uri, projection, null, null, null);
     } catch (SecurityException e) {
       Log.w(TAG, "Security error on " + u.toString(), e);
       return null;
     } catch (Exception e) {
       Log.e(TAG, u.toString(), e);
     }
     if (c != null) {
       ArrayList<SAFItem> tmp_list = new ArrayList<SAFItem>();
       if (c.getCount() == 0) return tmp_list;
       int ici = c.getColumnIndex(Document.COLUMN_DOCUMENT_ID);
       int nci = c.getColumnIndex(Document.COLUMN_DISPLAY_NAME);
       int sci = c.getColumnIndex(Document.COLUMN_SIZE);
       int mci = c.getColumnIndex(Document.COLUMN_MIME_TYPE);
       int dci = c.getColumnIndex(Document.COLUMN_LAST_MODIFIED);
       c.moveToFirst();
       do {
         SAFItem item = new SAFItem();
         String id = c.getString(ici);
         item.origin = DocumentsContract.buildDocumentUriUsingTree(u, id);
         item.attr = c.getString(mci);
         item.dir = Document.MIME_TYPE_DIR.equals(item.attr);
         item.name = (item.dir ? "/" : "") + c.getString(nci);
         item.size = c.getLong(sci);
         item.date = new Date(c.getLong(dci));
         if (item.dir) item.size = -1;
         tmp_list.add(item);
       } while (c.moveToNext());
       return tmp_list;
     }
   } catch (Exception e) {
     Log.e(TAG, "Failed cursor processing for " + u.toString(), e);
   } finally {
     if (c != null) c.close();
   }
   return null;
 }
コード例 #28
0
      @Override
      protected String doInBackground(Uri... params) {
        loading = true;
        Uri uri = params[0];
        if (uri == null || mUri.getHost() == null) return null;
        File cache = FileUtil.generateImageCacheFile(uri.toString());
        if (cache.exists() && cache.canRead()) {
          return cache.getAbsolutePath();
        } else {
          cache.getParentFile().mkdirs();
        }
        File temp = new File(cache.getAbsolutePath() + ".tmp");
        InputStream in = null;
        OutputStream out = null;

        try {
          URL parsedUrl = new URL(uri.toString());
          for (int i = 0; i < 3 && !isCancelled(); i++) {

            HttpURLConnection connection =
                Connectivity.openDefaultConnection(parsedUrl, 3000 + i * 1500, (3000 * (2 + i)));
            if (temp.exists()) {
              connection.addRequestProperty("Range", "bytes=" + temp.length() + "-");
              out = new FileOutputStream(temp, true);
            } else out = new FileOutputStream(temp);
            try {
              int responseCode = connection.getResponseCode();
              if (responseCode == 200 || responseCode == 206) {
                in = connection.getInputStream();
                FileUtil.copyStream(in, out);
                cache.delete();
                if (!temp.renameTo(cache)) {
                  Log.w(TAG, "重命名失败" + temp.getName());
                }
                return cache.getAbsolutePath();
              }
            } catch (SocketTimeoutException e) {
              Log.w(TAG, "retry", e);
            }
          }
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          IOUtils.close(in);
          IOUtils.close(out);
        }
        return null;
      }
コード例 #29
0
 /**
  * Does a read-through cache for ringtone titles.
  *
  * @param uri The uri of the ringtone.
  * @return The ringtone title. {@literal null} if no matching ringtone found.
  */
 private String getRingToneTitle(Uri uri) {
   // Try the cache first
   String title = mRingtoneTitleCache.getString(uri.toString());
   if (title == null) {
     // This is slow because a media player is created during Ringtone object creation.
     Ringtone ringTone = RingtoneManager.getRingtone(mContext, uri);
     title = ringTone.getTitle(mContext);
     if (title != null) {
       mRingtoneTitleCache.putString(uri.toString(), title);
     }
   }
   return title;
 }
コード例 #30
0
 /**
  * Sets <code>url</code> to object of <code>VideoView</code> class (that is in fild of
  * VideoActivity) and starts it.
  *
  * @param uri is string that contains URL
  */
 private void startVideo(Uri uri) {
   Log.i("SetVideo url here:", "url:" + uri.toString());
   if (uri.toString().matches(StringsStore.URL_PATTERN) || uri.toString().contains("file://")) {
     this.__uri = uri;
     videoView.setVideoURI(uri);
     videoView.requestFocus();
     videoView.start();
   } else if (uri.toString().matches(StringsStore.URL_PATTERN)) {
     videoView.setVideoURI(uri);
     videoView.requestFocus();
     videoView.start();
   }
 }