コード例 #1
0
ファイル: MediaScannerUtils.java プロジェクト: kexuejin/Dir
 public static void informPathsDeleted(Context c, List<String> paths) {
   MediaScannerConnection.scanFile(
       c.getApplicationContext(),
       paths.toArray(new String[paths.size()]),
       null,
       sLogScannerListener);
 }
 public void onMediaScannerConnected()
 {
     if (mMediaScannerConnection != null)
     {
         mMediaScannerConnection.scanFile(mFilename, mMimeType);
     }
 }
  @SuppressLint("SimpleDateFormat")
  private void storePictureInGallery(String url) {
    // Setting up file to write the image to.
    SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
    String s = getAlbumDir() + "/img" + gmtDateFormat.format(new Date()) + ".png";
    MRAIDLog.i(TAG, "Saving image into: " + s);
    File f = new File(s);
    // Open InputStream to download the image.
    InputStream is;
    try {
      is = new URL(url).openStream();
      // Set up OutputStream to write data into image file.
      OutputStream os = new FileOutputStream(f);
      copyStream(is, os);
      MediaScannerConnection.scanFile(
          context,
          new String[] {f.getAbsolutePath()},
          null,
          new OnScanCompletedListener() {

            @Override
            public void onScanCompleted(String path, Uri uri) {
              MRAIDLog.d("File saves successfully to " + path);
            }
          });
      MRAIDLog.i(TAG, "Saved image successfully");
    } catch (MalformedURLException e) {
      MRAIDLog.e(TAG, "Not able to save image due to invalid URL: " + e.getLocalizedMessage());
    } catch (IOException e) {
      MRAIDLog.e(TAG, "Unable to save image: " + e.getLocalizedMessage());
    }
  }
コード例 #4
0
  public static String savePhoto(byte[] data, Context context) {
    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

      Log.d(TAG, "Can't create directory to save image.");
      return null;
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = BitmapUtils.PICTURE_PREFIX + date + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();
      Log.d(TAG, "New Image saved:" + photoFile);

      // Let media scanner scan the image so it will be immediately visible in the gallery
      MediaScannerConnection.scanFile(context, new String[] {filename}, null, null);

      return filename;
    } catch (Exception error) {
      Log.d(TAG, "File" + filename + "not saved: " + error.getMessage());
    }
    return null;
  }
コード例 #5
0
ファイル: SyncTask.java プロジェクト: tthomas48/Synchophy
 @Override
 public void onMediaScannerConnected() {
   for (String filename : toScan) {
     conn.scanFile(filename, null);
   }
   toScan.clear();
 }
コード例 #6
0
ファイル: GPUImage.java プロジェクト: qtstsq55/Perspective
    private void saveImage(final String folderName, final String fileName, final Bitmap image) {
      File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
      File file = new File(path, folderName + "/" + fileName);
      try {
        file.getParentFile().mkdirs();
        image.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
        MediaScannerConnection.scanFile(
            mContext,
            new String[] {file.toString()},
            null,
            new MediaScannerConnection.OnScanCompletedListener() {
              @Override
              public void onScanCompleted(final String path, final Uri uri) {
                if (mListener != null) {
                  mHandler.post(
                      new Runnable() {

                        @Override
                        public void run() {
                          mListener.onPictureSaved(uri);
                        }
                      });
                }
              }
            });
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      }
    }
コード例 #7
0
  private void saveWave(String fileName, File fileToSave) throws IOException {
    int dataLength = (int) fileToSave.length();
    byte[] rawData = new byte[dataLength];

    DataInputStream input = null;
    try {
      input = new DataInputStream(new FileInputStream(fileToSave));
      input.read(rawData);
    } finally {
      if (input != null) {
        input.close();
      }
    }

    DataOutputStream output = null;
    try {
      File file = new File(fileDir + fileName + ".wav");
      output = new DataOutputStream(new FileOutputStream(file, false));
      // WAVE header
      // see http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
      writeString(output, "RIFF"); // chunk id
      writeInt(output, 36 + dataLength); // chunk size
      writeString(output, "WAVE"); // format
      writeString(output, "fmt "); // subchunk 1 id
      writeInt(output, 16); // subchunk 1 size
      writeShort(output, (short) 1); // audio format (1 = PCM)
      writeShort(output, (short) 1); // number of channels
      writeInt(output, SAMPLE_RATE); // sample rate
      writeInt(output, SAMPLE_RATE * 2); // byte rate
      writeShort(output, (short) 2); // block align
      writeShort(output, (short) 16); // bits per sample
      writeString(output, "data"); // subchunk 2 id
      writeInt(output, dataLength); // subchunk 2 size
      // Audio data (conversion big endian -> little endian)
      short[] shorts = new short[rawData.length / 2];
      ByteBuffer.wrap(rawData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
      ByteBuffer bytes = ByteBuffer.allocate(shorts.length * 2);
      for (short s : shorts) {
        bytes.putShort(s);
      }
      output.write(bytes.array());

      MediaScannerConnection.scanFile(
          ctx,
          new String[] {file.toString()},
          null,
          new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
              Log.i("ExternalStorage", "Scanned " + path + ":");
              Log.i("ExternalStorage", "-> uri=" + uri);
            }
          });

    } finally {
      if (output != null) {
        output.close();
      }
    }
  }
コード例 #8
0
ファイル: RLSysUtil.java プロジェクト: CadeLaRen/emule_video
 /**
  * 浏览某种类型的文件
  *
  * @param context
  * @param files 待浏览的文件夹
  * @param mimeTypes 文件类型
  */
 public static void scanMediaFiles(final Context context, String[] files, String[] mimeTypes) {
   MediaScannerConnection.scanFile(
       context,
       files,
       mimeTypes,
       new OnScanCompletedListener() {
         @Override
         public void onScanCompleted(String arg0, Uri arg1) {
           Log.i("weitu", "arg0:" + arg0 + ";arg1:" + arg1);
         }
       });
 }
コード例 #9
0
  /**
   * Adds file and returns content uri.
   *
   * @param file
   * @return
   */
  private Uri addToMediaDB(File file) {
    ContentValues cv = new ContentValues();
    long current = System.currentTimeMillis();
    long modDate = file.lastModified();
    Date date = new Date(current);

    String sTime = DateFormat.getTimeFormat(mContext).format(date);
    String sDate = DateFormat.getDateFormat(mContext).format(date);
    String title = sDate + " " + sTime;

    // Lets label the recorded audio file as NON-MUSIC so that the file
    // won't be displayed automatically, except for in the playlist.

    // Currently if scan media, all db information will be cleared
    // so no need to put all information except MediaStore.Audio.Media.DATA

    // cv.put(MediaStore.Audio.Media.IS_MUSIC, "0");
    // cv.put(MediaStore.Audio.Media.TITLE, title);
    cv.put(MediaStore.Audio.Media.DATA, file.getAbsolutePath());
    // cv.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
    cv.put(MediaStore.Audio.Media.MIME_TYPE, mRequestedType);

    // cv.put(MediaStore.Audio.Media.ARTIST,
    // mContext.getString(R.string.your_recordings));
    // cv.put(MediaStore.Audio.Media.ALBUM,
    // mContext.getString(R.string.audio_recordings));
    // cv.put(MediaStore.Audio.Media.DURATION, this.sampleLength());
    // Log.d(TAG, "Inserting audio record: " + cv.toString());
    ContentResolver resolver = mContext.getContentResolver();
    Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    // Log.d(TAG, "ContentURI: " + base);
    Uri result = resolver.insert(base, cv);

    if (result == null) {
      Log.e(TAG, "----- Unable to save recorded audio !!");
      return null;
    }

    if (getPlaylistId() == -1) {
      createPlaylist(resolver);
    }
    int audioId = Integer.valueOf(result.getLastPathSegment());
    addToPlaylist(resolver, audioId, getPlaylistId());

    // Notify those applications such as Music listening to the
    // scanner events that a recorded audio file just created.
    mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));

    // scan file
    MediaScannerConnection.scanFile(mContext, new String[] {file.getAbsolutePath()}, null, null);

    return result;
  }
コード例 #10
0
ファイル: MediaScannerUtils.java プロジェクト: kexuejin/Dir
  public static void informFolderAdded(Context c, File parentFile) {
    if (parentFile == null) return;

    ArrayList<String> filePaths = new ArrayList<String>();
    informFolderAddedCore(filePaths, parentFile);

    MediaScannerConnection.scanFile(
        c.getApplicationContext(),
        filePaths.toArray(new String[filePaths.size()]),
        null,
        sLogScannerListener);
  }
コード例 #11
0
ファイル: ExternalData.java プロジェクト: nanunmaro/sample
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
      case R.id.buttonSaveFile:
        String fileName = saveFile.getText().toString();
        // constructor with two parameters
        file = new File(path, fileName + ".png");
        checkState();
        if (writable == readable == true) {
          path.mkdirs();
          try {
            InputStream inputstream = getResources().openRawResource(R.drawable.blacksmiley);
            OutputStream outstream = new FileOutputStream(file);
            byte[] data = new byte[inputstream.available()];
            inputstream.read(data);
            outstream.write(data);
            inputstream.close();
            outstream.close();

            Toast t = Toast.makeText(ExternalData.this, "file has been saved", Toast.LENGTH_SHORT);
            t.show();
            // update files for the user to use
            MediaScannerConnection.scanFile(
                ExternalData.this,
                new String[] {file.toString()},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {

                  @Override
                  public void onScanCompleted(String path, Uri uri) {
                    // TODO Auto-generated method stub
                    Toast t =
                        Toast.makeText(ExternalData.this, "scan complete", Toast.LENGTH_SHORT);
                    t.show();
                  }
                });

          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        break;
      case R.id.buttonConfirmSaveAs:
        save.setVisibility(View.VISIBLE);
        break;
    }
  }
コード例 #12
0
  public void scanFileToPhotoAlbum(String path) {

    MediaScannerConnection.scanFile(
        getActivity(),
        new String[] {path},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {

          public void onScanCompleted(String path, Uri uri) {
            Log.i("TAG", "Finished scanning " + path);
          }
        });
  }
コード例 #13
0
 /** Send broadcast to notify system to scan music file. */
 private void scanSDCard() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
     // whether SDK is over 4.4
     String[] paths = new String[] {Environment.getExternalStorageDirectory().toString()};
     MediaScannerConnection.scanFile(mActivity, paths, null, null);
   } else {
     Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
     intent.setClassName(
         "com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
     intent.setData(Uri.parse("file://" + MusicUtils.getMusicDir()));
     mActivity.sendBroadcast(intent);
   }
 }
コード例 #14
0
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.bSaveFile:
        String f = saveFile.getText().toString();
        file = new File(path, f + ".png");

        checkState();
        if (canW == canR == true) {
          path.mkdirs();
          try {
            InputStream is = getResources().openRawResource(R.drawable.plusselected);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            Toast t = Toast.makeText(ExternalData.this, "File has been saved", Toast.LENGTH_LONG);
            t.show();

            // Update files for the user to use
            MediaScannerConnection.scanFile(
                ExternalData.this,
                new String[] {file.toString()},
                null,
                new MediaScannerConnection.OnScanCompletedListener() {

                  @Override
                  public void onScanCompleted(String path, Uri uri) {
                    Toast t =
                        Toast.makeText(ExternalData.this, "Scan Complete", Toast.LENGTH_SHORT);
                    t.show();
                  }
                });

          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        break;

      case R.id.bConfirmSaveAs:
        save.setVisibility(View.VISIBLE);
        break;
    }
  }
コード例 #15
0
ファイル: ResourceUtils.java プロジェクト: AlexTaran/picworld
 public static void saveObjectToExternalStorage(
     Context context, Serializable obj, String filename) {
   File root = android.os.Environment.getExternalStorageDirectory();
   File myFolder = new File(root, "PicWorld");
   myFolder.mkdir();
   File file = new File(myFolder, filename);
   try {
     FileOutputStream f = new FileOutputStream(file);
     ObjectOutputStream os = new ObjectOutputStream(f);
     os.writeObject(obj);
     os.close();
     f.close();
   } catch (Exception e) {
     Log.e("F**K", "Exception while saving serialized object to file! " + e.getMessage());
   }
   MediaScannerConnection.scanFile(context, new String[] {file.getAbsolutePath()}, null, null);
 }
コード例 #16
0
  protected void
      scanlist() { // cap nhat file photo vua duoc restore (trong /mtn/sdcardDCIM/.thumbnails)

    if (MyHiddenPhotoActivity.listToScan != null) {
      String[] temp = (String[]) MyHiddenPhotoActivity.listToScan.toArray(new String[0]);
      MediaScannerConnection.scanFile(
          this,
          temp,
          null,
          new OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {
              Log.i("ExternalStorage", "Scanned " + path + ":");
              Log.i("ExternalStorage", "-> uri=" + uri);
            }
          });
    }
  }
コード例 #17
0
  @Override
  public void confirmStorePhotoDialogPositiveClick(DialogFragment dialog) {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {

      File path =
          new File(
              Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                  + "/"
                  + getResources().getString(R.string.app_name));
      File img = new File(path, room.getRoomNumber() + ".jpg");

      if (path.mkdirs() || path.isDirectory()) {
        try {
          InputStream is = getResources().openRawResource(resource);
          OutputStream os = new FileOutputStream(img);
          byte[] data = new byte[is.available()];
          is.read(data);
          os.write(data);
          is.close();
          os.close();

          final Toast success_toast =
              Toast.makeText(
                  getApplicationContext(),
                  getResources().getString(R.string.msg_photo_stored_succesfull),
                  Toast.LENGTH_SHORT);
          MediaScannerConnection.scanFile(
              this,
              new String[] {img.toString()},
              null,
              new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                  success_toast.show();
                }
              });
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #18
0
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_save_image) {
      File file = getImageBitmap();
      ProgressDialog dialog = new ProgressDialog(ImageActivity.this);
      dialog.setMessage("Please Wait");
      dialog.setIndeterminate(true);
      dialog.show();
      MediaScannerConnection.scanFile(
          ImageActivity.this,
          new String[] {file.getAbsolutePath()},
          null,
          new MediaScannerConnection.OnScanCompletedListener() {

            public void onScanCompleted(String path, Uri uri) {
              Log.i("TAG", "Finished scanning " + path);
            }
          });
      if (f) {
        Toast toast = Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
        putSharedPreference(getApplicationContext(), "COUNT", ++count);
      } else {
        Toast toast =
            Toast.makeText(getApplicationContext(), "Couldn\'t Save Image ", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        toast.show();
      }
      dialog.cancel();
    } else if (item.getItemId() == R.id.action_image_share) {
      File file = getImageBitmap();
      Uri uri = Uri.fromFile(file);
      Intent sendIntent = new Intent();
      sendIntent.setAction(Intent.ACTION_SEND);
      sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
      sendIntent.setType("image/*");
      startActivity(Intent.createChooser(sendIntent, "Share Image"));
    } else if (item.getItemId() == android.R.id.home) {
      onBackPressed();
    }

    return super.onOptionsItemSelected(item);
  }
コード例 #19
0
  private void scanFile(String path, final boolean edit) {

    MediaScannerConnection.scanFile(
        SlideImageActivity.this,
        new String[] {path},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {

          public void onScanCompleted(String path, Uri uri) {
            Log.i("TAG", "Finished scanning " + path);
            if (edit) {
              Intent editIntent = new Intent(Intent.ACTION_EDIT);
              // editIntent.setType("image/*");
              editIntent.setDataAndType(uri, "image/*");
              startActivity(Intent.createChooser(editIntent, null));
            }
          }
        });
  }
コード例 #20
0
ファイル: Utils.java プロジェクト: danishkhan2931/olahack
  public static boolean checkForDirectory(Context context, String path) {
    File f = new File(Environment.getExternalStorageDirectory().getPath());
    f = new File(f, path);
    if (f.exists() == true && f.isDirectory() == true) {
      Debug.e(path + " already exists.");
      return true;
    }
    Debug.e(path + " doesnt exists. So trying to create");
    f.mkdirs();
    f.setExecutable(true);
    f.setReadable(true);
    f.setWritable(true);
    // initiate media scan and put the new things into the path array to
    // make the scanner aware of the location and the files you want to see
    MediaScannerConnection.scanFile(context, new String[] {f.toString()}, null, null);

    Boolean successs = (f.exists() && f.isDirectory());
    Debug.i("checking if it was successfully created. " + successs);
    return successs;
  }
コード例 #21
0
ファイル: FileUtil.java プロジェクト: CodingPapi/smartapp-src
  /** 通知系统扫描SDCard,及时更新媒体库 */
  public static void scanSdCard(Context mContext) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
      mContext.sendBroadcast(
          new Intent(
              Intent.ACTION_MEDIA_MOUNTED,
              Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
    } else {
      mContext.sendBroadcast(
          new Intent(
              Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
              Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath())));
    }

    // 4.4之后的系统无法通过广播更新,所以使用下面这个方法扫描更新
    MediaScannerConnection.scanFile(
        mContext,
        new String[] {Environment.getExternalStorageDirectory().getAbsolutePath()},
        null,
        null);
  }
コード例 #22
0
  private void refreshMediaScanner(final String imagePath) {
    MediaScannerConnection.scanFile(
        this,
        new String[] {imagePath},
        null,
        new MediaScannerConnection.OnScanCompletedListener() {
          @Override
          public void onScanCompleted(String path, Uri uri) {

            PickerActivity.this.runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    reloadAlbums();
                  }
                });

            Log.d("onActivityResult", "New image should appear in camera folder");
          }
        });
  }
コード例 #23
0
ファイル: MainActivity.java プロジェクト: 872641675/UVCCamera
 @Override
 public boolean onLongClick(final View view) {
   switch (view.getId()) {
     case R.id.camera_view_L:
     case R.id.camera_view_R:
       if (mHandler.isOpened()) {
         final File outputFile =
             MediaMuxerWrapper.getCaptureFile(Environment.DIRECTORY_DCIM, ".png");
         mHandler.captureStill(outputFile.toString());
         try {
           if (DEBUG) Log.i(TAG, "MediaScannerConnection#scanFile");
           MediaScannerConnection.scanFile(
               getApplicationContext(), new String[] {outputFile.toString()}, null, null);
         } catch (final Exception e) {
           Log.e(TAG, "MediaScannerConnection#scanFile:", e);
         }
         return true;
       }
   }
   return false;
 }
コード例 #24
0
  @Override
  protected void onPostExecute(String result) {

    mProgressDialog.dismiss();
    // listXAdapter.ReStartAdapter();
    // Intent ixX = new Intent();
    // ixX.setAction(Test_Downloader_By_service.CUSTOM_INTENT);
    // ixX.putExtra("progress", 100);
    // ixX.putExtra("vid", id);
    // ixX.putExtra("title", title);
    // context.getApplicationContext().sendBroadcast(ixX);
    DBClass_Downloader dbClass_downloader = new DBClass_Downloader(context);
    dbClass_downloader.UpdateDownloadData(url, "Downloaded");
    try {
      MediaScannerConnection.scanFile(context, new String[] {result}, null, null);
    } catch (Exception e) {
    }

    if (result == null)
      Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
    else Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
  }
コード例 #25
0
    @Override
    protected void onPostExecute(Integer result) {
      Toast toast = Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT);
      toast.show();

      // Fix for android issue 195362, in which files do not show in the MTP file explorer
      // until a device reboot occurs.
      // See https://code.google.com/p/android/issues/detail?id=195362
      MediaScannerConnection.scanFile(
          getActivity(), new String[] {output.getAbsolutePath()}, null, null);

      FragmentManager manager = getActivity().getSupportFragmentManager();

      DialogFragment diag =
          (DialogFragment) manager.findFragmentByTag(BackUpDialog.class.getName());

      diag.dismiss();

      manager
          .beginTransaction()
          .remove(manager.findFragmentByTag(TaskManagerFragment.DEFAULT_TAG))
          .commit();
    }
コード例 #26
0
  /**
   * Disables the data logger, closes the file and notifies the system that a new file is available
   * also sends the file to the cloud
   */
  protected void disableLogging() {
    File f1 = null;

    if (mLoggingEnabled && (mDataLogger != null)) {
      try {
        f1 = mDataLogger.getFile();
        // notify media scanner
        context.sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mDataLogger.getFile())));

        // close logger
        mDataLogger.close();

        Toast.makeText(context, "Logging Disabled", Toast.LENGTH_SHORT).show();

      } catch (IOException e) {
        Toast.makeText(context, "Error disabling logging " + e.getMessage(), Toast.LENGTH_LONG)
            .show();
      }
    }

    final File f2 = f1;

    String dir =
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .getAbsolutePath();
    MediaScannerConnection.scanFile(context, new String[] {dir + "/" + latestFilename}, null, null);

    Toast.makeText(context, "File written", Toast.LENGTH_SHORT).show();

    // sends file to the cloud
    UploadFile toTheCloud = new UploadFile(context);
    toTheCloud.beginUpload(f2.getAbsolutePath());

    // set disabled flag
    mLoggingEnabled = false;
  }
コード例 #27
0
 public static void saveScreenshot(final Context c, int w, int h, GL10 gl) {
   try {
     File dir = new File(MainActivity.home_directory);
     SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
     String timestamp = s.format(new Date());
     File f = new File(dir.getAbsolutePath(), timestamp + ".jpeg");
     FileOutputStream out = new FileOutputStream(f);
     savePixels(0, 0, w, h, gl).compress(Bitmap.CompressFormat.JPEG, 100, out);
     out.close();
     // attempt to put into gallery app
     MediaScannerConnection.scanFile(
         c.getApplicationContext(),
         new String[] {f.toString()},
         null,
         new OnScanCompletedListener() {
           public void onScanCompleted(String path, Uri uri) {
             // Log.d("onScanCompleted", path);
             // c.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
           }
         });
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #28
0
ファイル: MediaScannerUtils.java プロジェクト: kexuejin/Dir
  /** Request a MediaScanner scan for a single file. */
  public static void informFileAdded(Context c, File f) {
    if (f == null) return;

    MediaScannerConnection.scanFile(
        c.getApplicationContext(), new String[] {f.getAbsolutePath()}, null, sLogScannerListener);
  }
コード例 #29
0
ファイル: MainActivity.java プロジェクト: noTours/app
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // window properties, called before layout is loaded
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.splash);

    // brightness
    // Make the screen full bright for this activity.
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = 0.5f;

    // Play Intro Sound
    // mp_intro.reset();
    // String my_path1="/sdcard/notours/system_sounds/welcome_to_notours.mp3";

    // Setting latitude and longitude in the TextView tv_location

    // noTours version
    /*
    TextView tvLocation = (TextView) findViewById(R.id.noTours_version);
        	tvLocation.setText("v2.0.3.Http");
        	tvLocation.setTypeface(null, Typeface.ITALIC);
        	tvLocation.bringToFront();
        	//tvLocation.setHeight(40);
        	tvLocation.setTextColor(Color.LTGRAY);
        	tvLocation.setTextSize(10);
     */

    mp_intro = MediaPlayer.create(this, R.raw.welcome);
    // mp_intro.setDataSource(my_path1);

    // mp_intro.setVolume(1.0f, 1.0f);

    // if(mp_intro.isPlaying()==false) {
    // Log.v("home sound","entrooo");
    mp_intro.start();
    // Log.v("home sound","start");
    // i.e. react on the end of the music-file:
    mp_intro.setOnCompletionListener(
        new OnCompletionListener() {

          // @Override
          public void onCompletion(MediaPlayer arg0) {
            // File has ended !!! Wink
            // Log.v("Intro Sounde"," he terminaaaaaaaaaaaaaaado");
            if (mp_intro.isPlaying()) {
              mp_intro.stop();
            }
            mp_intro.reset();
            mp_intro.release();
          }
        });
    // }
    // End of Play Intro Sound

    // check if noTours directory exists, if not create it!
    File testDirectory = new File(Environment.getExternalStorageDirectory() + "/notours");
    if (!testDirectory.exists()) {
      File nfile = new File(Environment.getExternalStorageDirectory() + "/notours");
      nfile.mkdir();
    }
    File testDirectory22 = new File("/storage/emulated/0/notours/");
    if (!testDirectory22.exists()) {
      File nfile2 = new File("/storage/emulated/0/notours/");
      nfile2.mkdir();
    }

    // copy files from assests if necessary for having a demo!!
    File testDirectory2 =
        new File(Environment.getExternalStorageDirectory() + "/notours/noToursDemo");
    if (!testDirectory2.exists()) {
      File nfile2 = new File(Environment.getExternalStorageDirectory() + "/notours/noToursDemo");
      nfile2.mkdir();
      File nfile3 =
          new File(Environment.getExternalStorageDirectory() + "/notours/noToursDemo/sound");
      nfile3.mkdir();
      copyDemoProject();
    }
    File testDirectory23 = new File("/storage/emulated/0/notours/noToursDemo");
    if (!testDirectory23.exists()) {
      File nfile2 = new File("/storage/emulated/0/notours/noToursDemo");
      nfile2.mkdir();
      File nfile3 = new File("/storage/emulated/0/notours/noToursDemo/sound");
      nfile3.mkdir();
      copyDemoProject2();
    }

    // Re-scan directory for making it available to the users
    // File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    File path11 = new File("/storage/emulated/0/notours/");
    path11.mkdirs();

    // fix
    path11.setExecutable(true);
    path11.setReadable(true);
    path11.setWritable(true);

    // initiate media scan and put the new things into the path array to
    // make the scanner aware of the location and the files you want to see
    MediaScannerConnection.scanFile(this, new String[] {path11.toString()}, null, null);

    // For a specific the project
    // check if noTours directory exists, if not create it!
    /*
    File testDirectory3 = new File(Environment.getExternalStorageDirectory() + "/notours/carcassonne");
    if(!testDirectory3.exists()){
    	File nfile4=new File(Environment.getExternalStorageDirectory()+"/notours/carcassonne");
    	nfile4.mkdir();
    	File nfile5=new File(Environment.getExternalStorageDirectory()+"/notours/carcassonne/sound");
    	nfile5.mkdir();
    	File nfile6=new File(Environment.getExternalStorageDirectory()+"/notours/carcassonne/track");
    	nfile6.mkdir();
    	File nfile7=new File(Environment.getExternalStorageDirectory()+"/notours/carcassonne/image");
    	nfile7.mkdir();
    }
    */

    // thread for displaying the SplashScreen
    Thread splashTread =
        new Thread() {
          @Override
          public void run() {
            try {
              int waited = 0;
              while (_active && (waited < _splashTime)) {
                sleep(100);
                if (_active) {
                  waited += 100;
                }
              }
            } catch (InterruptedException e) {
              // do nothing
            } finally {
              finish();
              // go to the menu
              startActivity(
                  new Intent(
                      "com.example.mapdemo.escoitar.Projects")); // "com.noTours.escoitar.noTours.Menu"));
              // go to the projects menu
              // startActivity(new Intent("com.noTours.escoitar.noTours.Projects"));
              // MenuContinent.c

              // stop();
            }
          }
        };
    splashTread.start();
  }
コード例 #30
0
  // ギャラリー、カメラから戻ってきたときの処理をする関数
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

      Bitmap bm = null;
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inSampleSize = 2; // 元の1/4サイズでbitmap取得

      switch (requestCode) {
        case REQUEST_CAMERA:
          System.out.println(bitmapUri.getPath());
          bm = BitmapFactory.decodeFile(bitmapUri.getPath(), options);
          // 撮影した画像をギャラリーのインデックスに追加されるようにスキャンする。
          // これをやらないと、アプリ起動中に撮った写真が反映されない
          String[] paths = {bitmapUri.getPath()};
          String[] mimeTypes = {"image/*"};
          MediaScannerConnection.scanFile(
              getApplicationContext(),
              paths,
              mimeTypes,
              new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {}
              });
          break;

        case REQUEST_GALLERY:
          try {
            if (data != null || data.getData() != null) {
              bitmapUri = data.getData();
              InputStream is = getContentResolver().openInputStream(data.getData());
              bm = BitmapFactory.decodeStream(is, null, options);
              is.close();
            }
          } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bm = null;
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
          break;

        default:
          finish();
          break;
      }

      ExifInterface exif = null;
      try {
        exif = new ExifInterface(bitmapUri.getPath());
      } catch (IOException e) {
        e.printStackTrace();
      } catch (NullPointerException e) {
        e.printStackTrace();
      }
      Matrix matrix = new Matrix();

      if (exif != null) {
        int orientation =
            exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        if (orientation == 6) {
          matrix.postRotate(90);
        } else if (orientation == 3) {
          matrix.postRotate(180);
        } else if (orientation == 8) {
          matrix.postRotate(270);
        }
      }
      bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

      gpuImage.setImage(bm);
      imageView.setImageBitmap(bm);

    } else {
      finish();
    }
  }