【问题标题】:How to automatically add saved files to directory without restarting - Android Application如何在不重启的情况下自动将保存的文件添加到目录 - Android 应用程序
【发布时间】:2014-04-20 19:10:45
【问题描述】:

我创建了一个Android应用程序并使用以下方法保存文件:

File created = new File(dir, time.format("%Y%m%d%H%M%S") + "." + suffix);

但是,即使设备连接到我的计算机,保存的文件也只会在重新启动设备后出现在指定目录中。如何在不重新启动的情况下强制显示文件?

【问题讨论】:

    标签: android restart file-manager application-restart


    【解决方案1】:

    使用媒体扫描仪。注意 mime 类型,您可能需要根据您正在创建的文件进行更改

    MediaScannerConnection.scanFile(this.getApplicationContext(), new String[] { filename }, new String[] { "image/jpeg" }, new OnScanCompletedListener()
    {
        @Override
        public void onScanCompleted(final String path, final Uri uri)
        {
            // Eureka, your file has been scanned!
        }
    });
    

    这里有更多广播新文件的方法:

    更新:

    void alternativeScan(final String filename)
    {
        final File file = new File(filename);
        final Uri fileUri = Uri.fromFile(file);
    
        // New way
    
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        {
            this.getApplicationContext().sendBroadcast(new Intent("android.hardware.action.NEW_PICTURE", fileUri));
        }
    
        // Keep compatibility
    
        this.getApplicationContext().sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", fileUri));
    
        // Usual way
    
        final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(fileUri);
        this.getApplicationContext().sendBroadcast(intent);
    }
    

    如果仍然不起作用,请使用下一个功能检查您的媒体存储状态

    public static int getMediaStorageState()
    {
        final String state = Environment.getExternalStorageState();
    
        if (Environment.MEDIA_MOUNTED.equals(state))
        {
            return 0; // All Ok, supported Read & Write
        }
        else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
        {
            return 1; // Media storage has Read Only state
        }
        else
        {
            return 2; // Something's wrong. No Read/Write access
        }
    }
    

    【讨论】:

    • 刚试过这个,直到重新启动它才会自动出现在我的目录中=\。
    • 我在答案中添加了一个用于替代扫描模式的新功能,基本上有了这个,你就有了在 Android 中广播新文件的所有可能方式。好吧,还有另一种方法是手动(最好以编程方式)通过 SQL 将记录插入到所需的媒体表中,但我认为这个问题过分了。还要确保您的 SD 存储已正确安装,使用答案中的最后一个函数来检查。
    【解决方案2】:

    假设dir 不在某个外部存储上,并且“仅出现”意味着“仅在我使用 USB 电缆将设备连接到我的开发机器时出现”,use MediaScannerConnection and scanFile() to update the MediaStore index

    请注意,如果开发机器的操作系统(例如 Windows)缓存 MTP 结果,您可能还需要在开发机器上执行某种刷新操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2019-12-15
      相关资源
      最近更新 更多