Android使用SD卡媒体扫描仪

发布于 2024-10-31 14:55:02 字数 3363 浏览 9 评论 0原文

大家好 我正在尝试将图像保存到 SD 卡,但在使用媒体扫描仪扫描新保存的文件以使其立即可用时遇到问题,

错误在以下几行中,

new String[] { file.toString() }, null, // error: file cannot be resolved

new MediaScannerConnection.OnScanCompletedListener() { 
// error: MediaScannerConnection.OnScanCompletedListener cannot be resolved to a type

这是我的代码:

public void saveToSDCard(Bitmap bitmap, String name) {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mExternalStorageAvailable = mExternalStorageWriteable = true;
            Log.v(TAG, "SD Card is available for read and write "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
            saveFile(bitmap, name);
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
            Log.v(TAG, "SD Card is available for read "
                    + mExternalStorageAvailable);
        } else {
            mExternalStorageAvailable = mExternalStorageWriteable = false;
            Log.v(TAG, "Please insert a SD Card to save your Ad "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
        }
    }

    private void saveFile(Bitmap bitmap, String name) {

        String filename = name;
        ContentValues values = new ContentValues();
        File sdImageMainDirectory = new File(Environment
                .getExternalStorageDirectory(), getResources().getString(
                R.string.directory));
        sdImageMainDirectory.mkdirs();
        File outputFile = new File(sdImageMainDirectory, filename);
        values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
        values.put(MediaStore.MediaColumns.TITLE, filename);
        values.put(MediaStore.MediaColumns.DATE_ADDED, System
                .currentTimeMillis());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        Uri uri = this.getContentResolver().insert(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

                values);
        try {
            OutputStream outStream = this.getContentResolver()
                    .openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);

            outStream.flush();
            outStream.close();
        // this is where im having the problem  
        // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.v("ExternalStorage", "Scanned " + path + ":");
                    Log.v("ExternalStorage", "-> uri=" + uri);
                }
            });
        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.v("ExternalStorage", "Error writing " + file, e);
        }
    }

hi to all
im trying to save an image to an SDcard and im having a problem using the media scanner to scan the new saved file so that it is immediately available

the errors are in the following lines

new String[] { file.toString() }, null, // error: file cannot be resolved

new MediaScannerConnection.OnScanCompletedListener() { 
// error: MediaScannerConnection.OnScanCompletedListener cannot be resolved to a type

this is my code:

public void saveToSDCard(Bitmap bitmap, String name) {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mExternalStorageAvailable = mExternalStorageWriteable = true;
            Log.v(TAG, "SD Card is available for read and write "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
            saveFile(bitmap, name);
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
            Log.v(TAG, "SD Card is available for read "
                    + mExternalStorageAvailable);
        } else {
            mExternalStorageAvailable = mExternalStorageWriteable = false;
            Log.v(TAG, "Please insert a SD Card to save your Ad "
                    + mExternalStorageAvailable + mExternalStorageWriteable);
        }
    }

    private void saveFile(Bitmap bitmap, String name) {

        String filename = name;
        ContentValues values = new ContentValues();
        File sdImageMainDirectory = new File(Environment
                .getExternalStorageDirectory(), getResources().getString(
                R.string.directory));
        sdImageMainDirectory.mkdirs();
        File outputFile = new File(sdImageMainDirectory, filename);
        values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
        values.put(MediaStore.MediaColumns.TITLE, filename);
        values.put(MediaStore.MediaColumns.DATE_ADDED, System
                .currentTimeMillis());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        Uri uri = this.getContentResolver().insert(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

                values);
        try {
            OutputStream outStream = this.getContentResolver()
                    .openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);

            outStream.flush();
            outStream.close();
        // this is where im having the problem  
        // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.v("ExternalStorage", "Scanned " + path + ":");
                    Log.v("ExternalStorage", "-> uri=" + uri);
                }
            });
        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.v("ExternalStorage", "Error writing " + file, e);
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

×纯※雪 2024-11-07 14:55:02

我用静态方法 scanFile

这是我的代码:

String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + fileName;    
MediaScannerConnection.scanFile(this, new String[] { filePath }, null, null);

希望有帮助...

I got this working nicely with the static method scanFile

And here is my code:

String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + fileName;    
MediaScannerConnection.scanFile(this, new String[] { filePath }, null, null);

Hope that helps...

破晓 2024-11-07 14:55:02

或者可以通过 Intent 使用:

//Sends a broadcast to have the media scanner scan a file

private void scanMedia(String path) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
    sendBroadcast(scanFileIntent);
}

请参阅:文件具有 Intent 的媒体扫描仪

Or can use via Intent:

//Sends a broadcast to have the media scanner scan a file

private void scanMedia(String path) {
    File file = new File(path);
    Uri uri = Uri.fromFile(file);
    Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
    sendBroadcast(scanFileIntent);
}

See: Files Media Scanner with Intent

丑丑阿 2024-11-07 14:55:02

MediaScannerConnection.OnScanCompletedListener 仅自 API 级别 8 起可用。同样的事情对于您尝试使用的 scanFile() 变体。检查清单中的 minSdkVersion (和 targetSdkVersion)。

如果您需要您的应用程序与 Froyo 之前的 Android 版本兼容,那么您应该使用 scanFile(String path, String mimeType) 变体。它不是静态的,因此您需要实例化并缓存连接,例如在 onResume() 中:

scanner = new MediaScannerConnection(this, null);
scanner.connect();

然后,每当保存文件时:

if (scanner.isConnected())
    scanner.scanFile(someFile, null);

不要忘记在 onPause() 中调用scanner.disconnect()。

MediaScannerConnection.OnScanCompletedListener is only available since API level 8. Same thing for the scanFile() variant that you are trying to use. Check your minSdkVersion (and targetSdkVersion) in the manifest.

If you need your app to be compatible with versions of Android before Froyo, then you should use the scanFile(String path, String mimeType) variant. It is not static, so you need to instantiate and cache the connection, eg in onResume():

scanner = new MediaScannerConnection(this, null);
scanner.connect();

Then, whenever a file is being saved:

if (scanner.isConnected())
    scanner.scanFile(someFile, null);

Don't forget to call scanner.disconnect() in onPause().

岁月蹉跎了容颜 2024-11-07 14:55:02

您在代码中使用 File file; ,但没有此对象,而是在代码的其他部分使用 File outputFile 。因此,您需要在 MediaScannerConnection.scanFile(...) 中使用 outputFile.getAbsolutePath()

You use File file; in your code, but you don't have this object Instead you use File outputFile in other part of code. So you need to use outputFile.getAbsolutePath() in your MediaScannerConnection.scanFile(...).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文