草庐IT

安卓:安全异常: "destination must be on external storage"

coder 2023-12-10 原文

我在网上彻底搜索以找到答案,但没有结果。

我在我的 Android 应用程序中实现了一些“首选项”,包括将文件保存在您想要的任何位置的能力。

如果我在所谓的“集成sdcard”上选择一个路径,一切都OK。但我也有一个“真正的”外部 sdcard,它(在我的例子中)安装在 /storage/sdcard1 符号链接(symbolic link)到 /extSdCard/mnt/extSdCard (虽然“内部”sdcard 是 /storage/sdcard0,带有指向 /sdcard/mnt/sdcard 的符号链接(symbolic link))。

在 ICS 上,我在 /emmc 有外部链接,还有一些我不记得的链接。

问题是,如果我选择指向此 extSdCard 的路径,应用程序会创建文件夹结构,但不会写入下载的文件,以“SecurityException”结尾“目的地必须是在外部存储上”。

但是这个路径在外部存储上!更多:如果写权限有问题,为什么要创建文件夹? (android.permission.WRITE_EXTERNAL_STORAGE 存在于 list 中)。

很可能我做错了什么;或者可能是一些错误?

eclipse 日志:

11-30 11:58:29.143: D/ShareActivity(24752): doInBackground...
11-30 11:58:33.813: D/ShareActivity(24752): The response is: 200
11-30 11:58:50.283: D/ShareActivity(24752): location: Downloads
11-30 11:58:50.443: D/ShareActivity(24752): User defined folders created
11-30 11:58:50.443: D/ShareActivity(24752): path: /storage/sdcard1/temp
11-30 11:59:07.053: D/ShareActivity(24752): downloadUri: file:/storage/sdcard1/temp/test.3gpp
11-30 11:59:07.313: D/AndroidRuntime(24752): Shutting down VM
11-30 11:59:07.318: W/dalvikvm(24752): threadid=1: thread exiting with uncaught exception (group=0x41ce3300)
11-30 11:59:07.318: E/AndroidRuntime(24752): FATAL EXCEPTION: main
11-30 11:59:07.318: E/AndroidRuntime(24752): java.lang.SecurityException: Destination must be on external storage: file:/storage/sdcard1/temp/test.3gpp
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Parcel.readException(Parcel.java:1425)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.content.ContentResolver.insert(ContentResolver.java:864)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.app.DownloadManager.enqueue(DownloadManager.java:904)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at dentex.youtube.downloader.ShareActivity$AsyncDownload$1$1.onClick(ShareActivity.java:269)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.os.Looper.loop(Looper.java:137)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at android.app.ActivityThread.main(ActivityThread.java:4931)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at java.lang.reflect.Method.invokeNative(Native Method)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at java.lang.reflect.Method.invoke(Method.java:511)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
11-30 11:59:07.318: E/AndroidRuntime(24752):    at dalvik.system.NativeStart.main(Native Method)
11-30 11:59:09.248: I/Process(24752): Sending signal. PID: 24752 SIG: 9

相关代码:

lv.setOnItemClickListener(new OnItemClickListener() {

            private File userFolder;

                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String location = settings.getString("download_locations", "Downloads");
                Log.d(DEBUG_TAG, "location: " + location);

                boolean userLocationEnabled = settings.getBoolean("enable_user_location", false);

                if (userLocationEnabled == false) {
                    if (location.equals("DCIM") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    }
                    if (location.equals("Movies") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
                    } 
                    if (location.equals("Downloads") == true) {
                        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                    }
                    Log.d(DEBUG_TAG, "path: " + path);
                } else {
                        userFolder = new File(settings.getString("user_location", ""));
                        path = userFolder;
                }

                Log.d(DEBUG_TAG, "path: " + path.toString());

                pos = position;
                AlertDialog.Builder helpBuilder = new AlertDialog.Builder(ShareActivity.this);

                helpBuilder.setIcon(android.R.drawable.ic_dialog_info);
                helpBuilder.setTitle("Confirm Download for:");
                helpBuilder.setMessage(" *** msg *** ");

                helpBuilder.setPositiveButton("Download here", new DialogInterface.OnClickListener() {

                    @TargetApi(11)
                    public void onClick(DialogInterface dialog, int which) {
                        mLink = links[pos];
                        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

                        Request request = new Request(Uri.parse(mLink));
                        uri = Uri.parse(path.toURI() + title + "." + mExt);
                        Log.d(DEBUG_TAG, "downloadUri: " + uri);
                        request.setDestinationUri(uri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        }

                        if (isExternalStorageWritable() == true) {
                            enqueue = downloadManager.enqueue(request);
                        }
                    }
                });

                helpBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   //...
                });

                AlertDialog helpDialog = helpBuilder.create();
                helpDialog.show();

            }
});

最佳答案

根据 THIS ARTICLE作者:Jeremy Meiss (jerdog) 和 THIS LINK通过 Chainfire,目前这种行为应该是“正常的”。应该需要 WRITE_MEDIA_STORAGE 权限,但这仅授予系统应用程序。

作为一种解决方法,在我的 Activity 中,我像这样(在伪代码中)处理此 SecurityException:

Intent intent = new Intent(MyActivity.this, DownloadsService.class);

try {
    intent.putExtra("COPY", false);
    enqueue = dm.enqueue(request);
    Log.d(DEBUG_TAG, "_ID " + enqueue + " enqueued");
} catch (SecurityException e) {
    Log.w(DEBUG_TAG, e.getMessage());

    // handle the path on etxSdCard here:
    showSomeInfo();
    intent.putExtra("COPY", true);
    tempDownloadToSdcard(request);
}

startService(intent);

DownloadsService 中,我有一个 BroadcastReceiver,我在其中处理完成的下载; 在其 onStartCommand 中,我将 bool 值额外检索为:

doCopy = intent.getBooleanExtra("COPY", false);

然后在接收器内部:

if (doCopy) copyFileToExtSdCard();

希望这能澄清问题并有所帮助。

关于安卓:安全异常: "destination must be on external storage",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646669/

有关安卓:安全异常: "destination must be on external storage"的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  7. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐