您的位置:首页 > 移动开发 > Android开发

android N 获取手机内存信息方案

2016-12-29 16:19 381 查看
       在工作时添加一项关于device System分区使用信息的功能,自己总结了一下读取device中相关Storage使用信息的方法,话不多说,代码逻辑比较明了

实现方法:

//导包
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import com.android.internal.app.IMediaContainerService;
import android.os.RemoteException;

private long mSystemStorage=0; //初始赋值system used为0

@override
onCreate(){

final Intent containerIntent = new Intent().setComponent(
StorageMeasurement.DEFAULT_CONTAINER_COMPONENT);
//绑定service
getActivity().bindService(containerIntent, mContainerConnection, Context.BIND_AUTO_CREATE);

}

//通过绑定ServiceConnection获取手机内存信息
private final ServiceConnection mContainerConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
IMediaContainerService containerService = IMediaContainerService.Stub.asInterface(service); //aidl
if (containerService != null)
getSystemStorage(containerService);
}

@Override
public void onServiceDisconnected(ComponentName name) {
}
};

//得到系统中system已用的信息
private void getSystemStorage(IMediaContainerService containerService){
try{
final long[] systemStats = containerService.getFileSystemStats(
Environment.getRootDirectory().getPath());
mSystemStorage  = systemStats[0] - systemStats[1]; //[0]是system总大小 ,[1]是system可使用大小
}catch (RemoteException e){
Log.w(TAG, "Problem in container service", e);
}
}

//注销绑定
@verride
onDestory(){
getActivity().unbindService(mContainerConnection);
}


从以上代码可以看到最后 system 分区使用了多少

以下代码中 system是systme 分区使用的信息,Data是除去系统占用后,剩余的总内存的大小信息 ,Internal SD

扩展代码:

// Mounted
long totalStorage = 0;//总内存
long freeStorage = 0; //可用内存

try {
// System
final long[] systemStats = containerService.getFileSystemStats(
Environment.getRootDirectory().getPath());
totalStorage += systemStats[0];
Log.d(LOG_TAG, "System: TotoalSize = " + systemStats[0]
+ " FreeSize = " + systemStats[1]);

// Data
final long[] dataStats = containerService.getFileSystemStats(
Environment.getDataDirectory().getPath());
totalStorage += dataStats[0];
Log.d(LOG_TAG, "Data: TotoalSize = " + dataStats[0]
+ " FreeSize = " + dataStats[1]);
freeStorage = dataStats[1];
} catch (RemoteException e) {
Log.w(LOG_TAG, "Problem in container service", e);
}

注意:这个方法我在N的Settings中得到的,置于M 或者L上是否适合后面会继续发布..

源码总是能给你新的思路和快捷的方法~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息