麻烦编写内部内存android

Tom*_*ear 5 storage android exception android-contentresolver android-contentprovider

void launchImageCapture(Activity context) {
    Uri imageFileUri = context.getContentResolver()
        .insert(Media.INTERNAL_CONTENT_URI, new ContentValues());
    m_queue.add(imageFileUri);
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri); 
    context.startActivityForResult(i, ImportActivity.CAMERA_REQUEST); 
}
Run Code Online (Sandbox Code Playgroud)

以上代码一直有效,现在在insert()中为我生成了这个例外.

java.lang.UnsupportedOperationException: Writing to internal storage is not supported.
     at com.android.providers.media.MediaProvider.generateFileName(MediaProvider.java:2336)
     at com.android.providers.media.MediaProvider.ensureFile(MediaProvider.java:1851)
     at com.android.providers.media.MediaProvider.insertInternal(MediaProvider.java:2006)
     at com.android.providers.media.MediaProvider.insert(MediaProvider.java:1974)
     at android.content.ContentProvider$Transport.insert(ContentProvider.java:150)
     at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:140)
     at android.os.Binder.execTransact(Binder.java:287)
     at dalvik.system.NativeStart.run(Native Method)
Run Code Online (Sandbox Code Playgroud)

这不是一个空间问题,我唯一改变的是一个不相关的类的包.另外,我重新启动了手机.

小智 11

面对同样的问题,我很高兴找到这个帖子.尽管在这个变通方法中有两件事让我烦恼,但这篇文章让我看向了正确的方向.我想分享我自己的解决方法/解决方案.

让我先说明我没有看到自己与之共存的东西.

首先,我不想将应用程序私有文件保留为MODE_WORLD_WRITEABLE.这看起来对我来说没有意义,虽然我无法确切知道另一个应用程序如何访问此文件,除非知道在哪里查找具有完整名称和路径的文件.我并不是说它对你的场景来说一定不好,但它仍然以某种方式困扰着我.我希望通过将图片文件专用于我的应用程序来覆盖我的所有基础.在我的商业案例中,图片在应用程序之外是没有用的,绝不应该通过Android Gallery删除它们.我的应用程序将在适当的时间触发清理,以便不吸收Droid设备存储空间.

其次,openFileOutput()不保留任何选项,只是将结果文件保存在getFilesDir()的根目录中.如果我需要一些目录结构来保持秩序怎么办?另外,我的应用程序必须处理多个图片,所以我想生成文件名,以便稍后可以参考.

请注意,使用相机拍摄照片很容易,并将其保存到Droid设备上的公共图像区域(通过MediaStore).从MediaStore操作(查询,更新,删除)媒体也很容易.有趣的是,将相机图片插入MediaStore可以创建一个看似独特的文件名.为具有目录结构的应用程序创建专用文件也很容易."Capturea相机图片并将其保存到内存"的关键是你不能直接这样做,因为Android会阻止ContentResolver使用Media.INTERNAL_CONTENT_URI,并且因为私有app文件根据定义无法通过(外部)访问相机活动.

最后我采用了以下策略:

  1. 从我的应用程序启动Camera活动以获取结果以捕获图像.
  2. 返回我的应用程序时,将捕获插入MediaStore.
  3. 查询MediaStore以获取生成的图像文件名.
  4. 使用Context.getDir()在相对于私有应用程序数据文件夹的任何路径上创建真正的内部文件.
  5. 使用OutputStream将位图数据写入此专用文件.
  6. 从MediaStore中删除捕获.
  7. (可选)在我的应用程序中显示捕获的ImageView.

这是启动凸轮的代码:

public void onClick (View v)
{
    ContentValues values = new ContentValues ();

    values.put (Media.IS_PRIVATE, 1);
    values.put (Media.TITLE, "Xenios Mobile Private Image");
    values.put (Media.DESCRIPTION, "Classification Picture taken via Xenios Mobile.");

    Uri picUri = getActivity ().getContentResolver ().insert (Media.EXTERNAL_CONTENT_URI, values);

    //Keep a reference in app for now, we might need it later.
    ((XeniosMob) getActivity ().getApplication ()).setCamPicUri (picUri);

    Intent takePicture = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);

    //May or may not be populated depending on devices.
    takePicture.putExtra (MediaStore.EXTRA_OUTPUT, picUri);

    getActivity ().startActivityForResult (takePicture, R.id.action_camera_start);
}
Run Code Online (Sandbox Code Playgroud)

这是我的活动获得凸轮结果:

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
    super.onActivityResult (requestCode, resultCode, data);
    if (requestCode == R.id.action_camera_start)
    {
        if (resultCode == RESULT_OK)
        {
            Bitmap pic = null;
            Uri picUri = null;

            //Some Droid devices (as mine: Acer 500 tablet) leave data Intent null.
            if (data == null) {
                picUri = ((XeniosMob) getApplication ()).getCamPicUri ();
            } else
            {
                Bundle extras = data.getExtras ();
                picUri = (Uri) extras.get (MediaStore.EXTRA_OUTPUT);
            }

            try
            {
                pic = Media.getBitmap (getContentResolver (), picUri);
            } catch (FileNotFoundException ex)
            {
                Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
            } catch (IOException ex)
            {
                Logger.getLogger (getClass ().getName ()).log (Level.SEVERE, null, ex);
            }

            //Getting (creating it if necessary) a private directory named app_Pictures
            //Using MODE_PRIVATE seems to prefix the directory name provided with "app_".
            File dir = getDir (Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);

            //Query the MediaStore to retrieve generated filename for the capture.
            Cursor query = getContentResolver ().query (
                        picUri,
                        new String [] {
                            Media.DISPLAY_NAME,
                            Media.TITLE
                        },
                        null, null, null
                    );
            boolean gotOne = query.moveToFirst ();
            File internalFile = null;
            if (gotOne)
            {
                String dn = query.getString (query.getColumnIndexOrThrow (Media.DISPLAY_NAME));
                String title = query.getString (query.getColumnIndexOrThrow (Media.TITLE));
                query.close ();

                //Generated name is a ".jpg" on my device (tablet Acer 500).
                //I prefer to work with ".png".
                internalFile = new File (dir, dn.subSequence (0, dn.lastIndexOf (".")).toString () + ".png");
                internalFile.setReadable (true);
                internalFile.setWritable (true);
                internalFile.setExecutable (true);
                try
                {
                    internalFile.createNewFile ();

                    //Use an output stream to write picture data to internal file.
                    FileOutputStream fos = new FileOutputStream (internalFile);
                    BufferedOutputStream bos = new BufferedOutputStream (fos);

                    //Use lossless compression.
                    pic.compress (Bitmap.CompressFormat.PNG, 100, bos);

                    bos.flush ();
                    bos.close ();
                } catch (FileNotFoundException ex)
                {
                    Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
                } catch (IOException ex)
                {
                    Logger.getLogger (EvaluationActivity.class.getName()).log (Level.SEVERE, null, ex);
                }
            }

            //Update picture Uri to that of internal file.
            ((XeniosMob) getApplication ()).setCamPicUri (Uri.fromFile (internalFile));

            //Don't keep capture in public storage space (no Android Gallery use)
            int delete = getContentResolver ().delete (picUri, null, null);

            //rather just keep Uri references here
            //visit.add (pic);

            //Show the picture in app!
            ViewGroup photoLayout = (ViewGroup) findViewById (R.id.layout_photo_area);
            ImageView iv = new ImageView (photoLayout.getContext ());
            iv.setImageBitmap (pic);
            photoLayout.addView (iv, 120, 120);
        }
        else if (resultCode == RESULT_CANCELED)
        {
            Toast toast = Toast.makeText (this, "Picture capture has been cancelled.", Toast.LENGTH_LONG);
            toast.show ();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

瞧!现在我们有一个真正的应用程序私有图片文件,该名称由Droid设备生成.并且没有任何东西保存在公共存储区域中,从而防止意外的图像操纵.


jam*_*mes 5

这是我的工作代码,用于将捕获的图像从相机保存到应用程序内部存储:

首先,使用所需的文件名创建文件.在这种情况下,它是"MyFile.jpg",然后以下面的意图开始活动.你是回调方法(onActivityResult),一旦完成就会被调用.调用onActivityResult后,您的图像应保存到内部存储.关键注意:用于openFileOutput需要全局的模式.. Context.MODE_WORLD_WRITEABLE工作正常,我还没有测试过其他模式.

try {
FileOutputStream fos = openFileOutput("MyFile.jpg", Context.MODE_WORLD_WRITEABLE);
fos.close();
File f = new File(getFilesDir() + File.separator + "MyFile.jpg");
startActivityForResult(
        new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f))
        , IMAGE_CAPTURE_REQUEST_CODE);
}
catch(IOException e) {

}
Run Code Online (Sandbox Code Playgroud)

并在活动结果方法中:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == IMAGE_CAPTURE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        Log.i(TAG, "Image is saved.");
    }
}
Run Code Online (Sandbox Code Playgroud)

检索你的图像:

try {
InputStream is = openFileInput("MyFile.jpg");
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 4;
Bitmap retrievedBitmap = BitmapFactory.decodeStream(is, null, options);
}
catch(IOException e) {

}
Run Code Online (Sandbox Code Playgroud)

  • 在内部存储中存储内容的好处是它将在app uninstall上删除.这是我认为的一大优势.我不希望一个应用程序在SD卡上保存一堆垃圾,发现卸载后它们都会存在.只是一个麻烦. (2认同)