我目前正在开发一个从外部存储中读取的动态壁纸。 当设备启动时,我认为可以在存储准备好之前启动动态壁纸。特别是如果它进行定期错误检查。其他人正在报告问题,我认为这就是原因。我似乎无法测试这个,因为外部存储似乎立即挂载在我的设备上,我不知道如何强制它进行错误检查。所以我的第一个问题是,在启动动态壁纸之前,系统是否真正实现了BOOT_COMPLETED意图。
如果没有,等待外部存储准备就绪的正确方法是什么。我想在应用程序的开头调用类似的东西
public void waitForExternalStorage()
{
while(Environment.getExternalStorageState().equals(Environment.MEDIA_CHECKING))
{
try { Thread.sleep(1000L); }
catch(InterruptedException e) { e.printStackTrace(); }
}
}
我是否必须检查其他情况,以防它进入MEDIA_REMOVED - > MEDIA_UNMOUNTED - > MEDIA_CHECKING(可选) - > MEDIA_READY开机了吗?
答案 0 :(得分:6)
您可以注册BroadcastReceiver
以收听外部存储状态的更改:
BroadcastReceiver externalStorageStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateExternalStorageState();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
registerReceiver(mExternalStorageReceiver, filter);
updateExternalStorageState(); // You can initialize the state here, before any change happens
在updateExternalStorageState()
中,您可以检查更改后的实际状态:
protected void updateExternalStorageState() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// SD card is mounted and ready for use
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// SD card is mounted, but it is read only
} else {
// SD card is unavailable
}
}
答案 1 :(得分:2)
使用广播接收器,侦听Intent.ACTION_MEDIA_MOUNTED
:广播操作:外部媒体存在并安装在其挂载点。
答案 2 :(得分:0)
我非常需要。我正在从SD卡读取配置文件,而我的启动运行应用程序根本无法在不读取的情况下运行。一个简单的解决方案是等待最多15-30秒,以便Android OS自动安装SD卡。如果没有,抛出异常。这是代码。只需增加最大计数限制即可增加等待时间。 ExternalStorageNotReadyException是一个自定义异常。
public void awaitExternalStorageInitialization()
throws ExternalStorageNotReadyException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
int count = 0;
do {
String state = Environment.getExternalStorageState();
if(count > 0) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(Constants.LOG_TAG, e.getMessage(), e);
}
}
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states,
// but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
count++;
} while ((!mExternalStorageAvailable) && (!mExternalStorageWriteable) && (count < 5));
if(!mExternalStorageWriteable)
throw new ExternalStorageNotReadyException("External storage device (SD Card) not yet ready");
}