1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.compatibility.common.util; 18 19 import android.app.ActivityManager; 20 import android.app.ActivityManager.MemoryInfo; 21 import android.app.Instrumentation; 22 import android.content.Context; 23 import android.os.ParcelFileDescriptor; 24 import android.os.StatFs; 25 26 import java.io.FileInputStream; 27 import java.io.IOException; 28 29 public class SystemUtil { getFreeDiskSize(Context context)30 public static long getFreeDiskSize(Context context) { 31 final StatFs statFs = new StatFs(context.getFilesDir().getAbsolutePath()); 32 return (long)statFs.getAvailableBlocks() * statFs.getBlockSize(); 33 } 34 getFreeMemory(Context context)35 public static long getFreeMemory(Context context) { 36 final MemoryInfo info = new MemoryInfo(); 37 ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(info); 38 return info.availMem; 39 } 40 getTotalMemory(Context context)41 public static long getTotalMemory(Context context) { 42 final MemoryInfo info = new MemoryInfo(); 43 ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(info); 44 return info.totalMem; 45 } 46 47 /** 48 * Executes a shell command using shell user identity, and return the standard output in string 49 * <p>Note: calling this function requires API level 21 or above 50 * @param instrumentation {@link Instrumentation} instance, obtained from a test running in 51 * instrumentation framework 52 * @param cmd the command to run 53 * @return the standard output of the command 54 * @throws Exception 55 */ runShellCommand(Instrumentation instrumentation, String cmd)56 public static String runShellCommand(Instrumentation instrumentation, String cmd) 57 throws IOException { 58 ParcelFileDescriptor pfd = instrumentation.getUiAutomation().executeShellCommand(cmd); 59 byte[] buf = new byte[512]; 60 int bytesRead; 61 FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd); 62 StringBuffer stdout = new StringBuffer(); 63 while ((bytesRead = fis.read(buf)) != -1) { 64 stdout.append(new String(buf, 0, bytesRead)); 65 } 66 fis.close(); 67 return stdout.toString(); 68 } 69 } 70