Run a service when device starts after sd finishes

2019-05-24 07:53发布

问题:

I run a service when the device boots and that service just loads an image from sd card and makes it wallpaper. When the device starts i get an error. But after the sd card finishes the loading the service sets the image as wallpaper fine.

<action android:name="android.intent.action.BOOT_COMPLETED" /> 

I start the service like this ^ and i want to ask if there is a way to start the service after sd card finishes loading.

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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>