When developing a company project, you need to determine whether the SD card or USB flash drive of the external storage equipment room inserted in the box is not found on the Internet. When I saw a different prompt in the status bar during the process of plugging the SD card and USB flash drive, I wanted to find a method from systemui. Later I found it and used it in the project. Here I will briefly summarize it:
Private Static final string ext_storage_path = environment. getexternalstoragedirectory (). tostring (); // obtain the path of the SD card
Private Static final string ext2_storage_path = environment. getexternalstorage2directory (). tostring (); // obtain other external storage methods
Storagemanager mstoragemanager = (storagemanager) getsystemservice (context. storage_service); // obtain the storagemanager object
Private storageeventlistener mstoragelistener = new storageeventlistener (){
@ Override
Public void onstoragestatechanged (string path, string oldstate, string newstate ){
If (newstate. Equals (environment. media_mounted) | newstate. Equals (environment. media_removed )){
If (path. Equals (ext_storage_path) {// unplug the SD card
} Else if (path. Equals (ext2_storage_path) {// unplug other external storage devices
}
}
}
};
Here, newstate is used to determine the plugging status of the external device, and the path is used to determine the different devices.
@ Override
Public void onresume (){
Super. onresume ();
Mstoragemanager. registerlistener (mstoragelistener );
};
@ Override
Protected void onpause (){
If (mstoragemanager! = NULL & mstoragelistener! = NULL ){
Mstoragemanager. unregisterlistener (mstoragelistener );
}
Super. onpause ();
}
Then, register the listener and unregister the listener at different lifecycles.
Do not forget to add permissions in manifest. xml.