In order to make it works you need to add user library classes-full-debug.jar
(from an aosp or cm build) BEFORE android.jar
(there is a panel in the build path to sort jars) or StorageManager
will not resolve registerListener()
You also need android.permission.MOUNT_UNMOUNT_FILESYSTEMS
package x.y.z;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.storage.IMountService;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.os.ServiceManager;
import android.widget.TextView;
public class MyActivity extends Activity
{
private static final String MOUNTPOINT = "/mnt/sdcard";
private IMountService mMountService;
private StorageManager mStorageManager;
private TextView mText;
private final StorageEventListener mStorageListener = new StorageEventListener()
{
@Override
public void onStorageStateChanged(String path, String oldState, String newState)
{
String text = mText.getText() + "\n";
text += "state changed notification that " + path + " changed state from " + oldState + " to " + newState;
mText.setText(text);
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) findViewById(R.id.textView);
if (mMountService == null)
{
IBinder service = ServiceManager.getService("mount");
mMountService = IMountService.Stub.asInterface(service);
}
if (mStorageManager == null)
{
mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
mStorageManager.registerListener(mStorageListener);
}
try
{
String state = mMountService.getVolumeState(MOUNTPOINT);
mText.setText("Media state " + state);
if (state.equals(Environment.MEDIA_MOUNTED))
mMountService.unmountVolume(MOUNTPOINT, false);
else if (state.equals(Environment.MEDIA_UNMOUNTED))
mMountService.mountVolume(MOUNTPOINT);
} catch (RemoteException e)
{
e.printStackTrace();
}
}
@Override
protected void onDestroy()
{
if (mStorageManager != null && mStorageListener != null)
mStorageManager.unregisterListener(mStorageListener);
super.onDestroy();
}
}