启动时找不到目录

发布于 2025-01-04 00:52:32 字数 686 浏览 0 评论 0原文

在我的应用程序中,我创建了一项旨在从 SD 卡读取内容的服务。

该服务在引导时创建并启动。

问题是,虽然我很确定该目录存在,但在启动时,该服务找不到该目录。

public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    Context context=getBaseContext();
    File sdDir = new File(Environment.getExternalStorageDirectory()+"/temp/Data/");
    if(!sdDir.exists()){
        sdDir.mkdir();
        Toast.makeText(this, "CAN'T FIND!", Toast.LENGTH_LONG).show();
    }
 }

上面的这段输出

  1. Service Started
  2. CAN'T FIND!

起初,我认为SD卡可能在启动时没有安装,这就是服务找不到该目录的原因。我对此仍然不确定。

有人有主意吗?可能是什么问题?

In my application, I create a service that aims to read something from sd card.

The service is created and started at boot time.

The problem is that although I am pretty sure that the directory exists, at the boot time, the service cannot find the directory.

public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    Context context=getBaseContext();
    File sdDir = new File(Environment.getExternalStorageDirectory()+"/temp/Data/");
    if(!sdDir.exists()){
        sdDir.mkdir();
        Toast.makeText(this, "CAN'T FIND!", Toast.LENGTH_LONG).show();
    }
 }

This snippet above outputs

  1. Service Started
  2. CAN'T FIND!

At first, I thought that sd card might not be mounted at boot time and that's why the service can't find the directory. I am still not sure about that.

Anybody has an idea? What might be the problem?

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

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

发布评论

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

评论(1

梦途 2025-01-11 00:52:32

有些设备需要一些时间来安装 SD 卡。它可能无法在启动后立即可用。

只需每隔几秒轮询一次,直到它可用。

另请尝试以下操作:

public static boolean hasStorage(boolean requireWriteAccess) {  
    String state = Environment.getExternalStorageState();  

    if (Environment.MEDIA_MOUNTED.equals(state)) {  
        return true;  
    } else if (!requireWriteAccess  && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {  
        return true;  
    }  
    return false;  
}

从这里

Some devices take time to mount the SD card. It may not be available immediately after Boot time.

Just poll every few seconds until it becomes available.

Also try this:

public static boolean hasStorage(boolean requireWriteAccess) {  
    String state = Environment.getExternalStorageState();  

    if (Environment.MEDIA_MOUNTED.equals(state)) {  
        return true;  
    } else if (!requireWriteAccess  && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {  
        return true;  
    }  
    return false;  
}

From Here

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