Run a service when device starts after sd finishes loading

≯℡__Kan透↙ 提交于 2019-12-06 04:40:41

You can wait for the SD card to load. One way is to use the android.intent.action.MEDIA_MOUNTED action.

Another way is to poll up to some maximum and give up if not mounted:

String mountState = Environment.getExternalStorageState();
int tries = 15;
do {
    if (!mountState.equals(Environment.MEDIA_MOUNTED)) {
        Log.i(LOG_TAG, "External media present but not mounted. Waiting 15 seconds for mount...");
        try {
            Thread.sleep(1000); // sleep for a second
        } catch (InterruptedException e) {
            Log.w(LOG_TAG, "Interrupted!");
            break;
        }
        mountState = Environment.getExternalStorageState();
    } else {
        Log.i(LOG_TAG, "External media mounted");
        break;
    }
} while (--tries > 0);
if (tries == 0) // give up

Hope this helps.

There's an intent broadcast for after media (SD card) is mounted with the action set to MEDIA_MOUNTED.

Bobbake4

Edit: I didn't know there was a intent for MEDIA_MOUNTED, I would use the answer posted below instead.

What I would do is launch the service how you have it and inside of the service keep checking to see when the sdcard is mounted, maybe every 300ms or something. This question shows how to detect if the sdcard has been mounted or not.

The MEDIA_MOUNTED action will work here, but you must include an intent filter for it in the manifest file, and you must also change the data scheme for the receiver's intent filter to "file" as well.

    <receiver android:name="YourReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_MOUNTED"></action>
            <data android:scheme="file"/>
        </intent-filter>
    </receiver>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!