android 获取手机信息

package com.osip; 

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

import android.app.Activity; 
import android.net.wifi.WifiInfo; 
import android.net.wifi.WifiManager; 
import android.os.Bundle; 
import android.widget.TextView; 

public class Osip extends Activity { 
    private TextView osVersion, clientIp, date; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
         
        osVersion = (TextView) findViewById(R.id.os_version); 
        clientIp = (TextView) findViewById(R.id.client_ip); 
        date = (TextView) findViewById(R.id.date); 

        String format = "yyyyMMdd.HHmmss.SSSZ";// 带毫秒和时区的时间格式 
        String version = getosVersion(); 
        String ip = getIp(); 
        String cDate = getDate(new Date(), format); 
         
        osVersion.setText(version); 
        clientIp.setText(ip); 
        date.setText(cDate.substring(0, 22)); 
    } 

    private String getDate(Date date, String format) { 
        DateFormat dateFormat = new SimpleDateFormat(format); 
        return dateFormat.format(date); 
    } 

    // 取得device的IP address 
    private String getIp() { 
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); 
        WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
        int ipAddress = wifiInfo.getIpAddress(); 
         
        // 格式化IP address,例如:格式化前:1828825280,格式化后:192.168.1.109 
        String ip = String.format("%d.%d.%d.%d", 
                (ipAddress & 0xff), 
                (ipAddress >> 8 & 0xff), 
                (ipAddress >> 16 & 0xff), 
                (ipAddress >> 24 & 0xff)); 
        return ip; 
         
    } 

    //获取device的os version 
    private String getosVersion() { 
        String version = android.os.Build.VERSION.RELEASE; 
        return version; 
    } 
}



在android开发中,有时候我们想获取手机的一些硬件信息,比如android手机的总内存和可用内存大小。这个该如何实现呢?
通过读取文件"/proc/meminfo"的信息能够获取手机Memory的总量,而通过ActivityManager.getMemoryInfo(ActivityManager.MemoryInfo)方法可以获取当前的可用Memory量。
      "/proc/meminfo"文件记录了android手机的一些内存信息,在命令行窗口里输入"adb shell",进入shell环境,输入"cat /proc/meminfo"即可在命令行里显示meminfo文件的内容,具体如下所示。 

C:\Users\Figo>adb shell
# cat /proc/meminfo
cat /proc/meminfo
MemTotal:          94096 kB
MemFree:            1684 kB
Buffers:              16 kB
Cached:            27160 kB
SwapCached:            0 kB
Active:            35392 kB
Inactive:          44180 kB
Active(anon):      26540 kB
Inactive(anon):    28244 kB
Active(file):       8852 kB
Inactive(file):    15936 kB
Unevictable:         280 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:         52688 kB
Mapped:            17960 kB
Slab:               3816 kB
SReclaimable:        936 kB
SUnreclaim:         2880 kB
PageTables:         5260 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:       47048 kB
Committed_AS:    1483784 kB
VmallocTotal:     876544 kB
VmallocUsed:       15456 kB
VmallocChunk:     829444 kB
#

下面先对"/proc/meminfo"文件里列出的字段进行粗略解释:

MemTotal: 所有可用RAM大小。

MemFree: LowFree与HighFree的总和,被系统留着未使用的内存。

Buffers: 用来给文件做缓冲大小。

Cached: 被高速缓冲存储器(cache memory)用的内存的大小(等于diskcache minus SwapCache)。

SwapCached:被高速缓冲存储器(cache memory)用的交换空间的大小。已经被交换出来的内存,仍然被存放在swapfile中,用来在需要的时候很快的被替换而不需要再次打开I/O端口。

Active: 在活跃使用中的缓冲或高速缓冲存储器页面文件的大小,除非非常必要,否则不会被移作他用。

Inactive: 在不经常使用中的缓冲或高速缓冲存储器页面文件的大小,可能被用于其他途径。

SwapTotal: 交换空间的总大小。

SwapFree: 未被使用交换空间的大小。

Dirty: 等待被写回到磁盘的内存大小。

Writeback: 正在被写回到磁盘的内存大小。

AnonPages:未映射页的内存大小。

Mapped: 设备和文件等映射的大小。

Slab: 内核数据结构缓存的大小,可以减少申请和释放内存带来的消耗。

SReclaimable:可收回Slab的大小。

SUnreclaim:不可收回Slab的大小(SUnreclaim+SReclaimable=Slab)。

PageTables:管理内存分页页面的索引表的大小。

NFS_Unstable:不稳定页表的大小。

 要获取android手机总内存大小,只需读取"/proc/meminfo"文件的第1行,并进行简单的字符串处理即可。

===========================================================================

下面直接给出详细步骤,大家可以根据实际情况进行相应扩展。

1.新建项目,修改main.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:textStyle="bold"  
    android:id="@+id/system_memory" />  
</LinearLayout>  

package com.figo.readsyememory;  
  
import android.app.Activity;  
import android.os.Bundle;  
import java.io.BufferedReader;  
import java.io.FileReader;  
import java.io.IOException;  
import android.app.ActivityManager;  
import android.app.ActivityManager.MemoryInfo;  
import android.content.Context;  
import android.text.format.Formatter;  
import android.util.Log;  
import android.widget.TextView;  
  
public class ReadSystemMemory extends Activity {  
  
    TextView tv = null;  
  
    private String getAvailMemory() {// 获取android当前可用内存大小  
  
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);  
        MemoryInfo mi = new MemoryInfo();  
        am.getMemoryInfo(mi);  
        //mi.availMem; 当前系统的可用内存  
  
        return Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化  
    }  
  
    private String getTotalMemory() {  
        String str1 = "/proc/meminfo";// 系统内存信息文件  
        String str2;  
        String[] arrayOfString;  
        long initial_memory = 0;  
  
        try {  
            FileReader localFileReader = new FileReader(str1);  
            BufferedReader localBufferedReader = new BufferedReader(  
                    localFileReader, 8192);  
            str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小  
  
            arrayOfString = str2.split("\\s+");  
            for (String num : arrayOfString) {  
                Log.i(str2, num + "\t");  
            }  
  
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存,单位是KB,乘以1024转换为Byte  
            localBufferedReader.close();  
  
        } catch (IOException e) {  
        }  
        return Formatter.formatFileSize(getBaseContext(), initial_memory);// Byte转换为KB或者MB,内存大小规格化  
    }  
  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
  
        tv = (TextView) findViewById(R.id.system_memory);  
        tv.setText("手机总内存: " + this.getTotalMemory() + ", " + "可用内存: "  
                + this.getAvailMemory());  
    }  
}  

大功告成,顺利读取android手机的总内存和当前的可用内存。这里只是抛砖引玉,大家可以举一反三,进行扩展。当然我们还可以通过读取"/proc/cupinfo"来获取android手机的CPU参数,通过读取"/proc/stat"文件来计算CPU的使用率,这里不再赘述。

转载至:http://blog.csdn.net/sxwyf248/archive/2010/11/02/5981251.aspx


public class GetFreeMem extends Activity {  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        Method _readProclines = null;  
        try {  
            Class procClass;  
            procClass = Class.forName("android.os.Process");  
            Class parameterTypes[]= new Class[] {String.class, String[].class, long[].class };  
            _readProclines = procClass.getMethod("readProcLines", parameterTypes);  
            Object arglist[] = new Object[3];  
            final String[] mMemInfoFields = new String[] {"MemTotal:",  
                    "MemFree:", "Buffers:", "Cached:"};  
            long[] mMemInfoSizes = new long[mMemInfoFields.length];  
            mMemInfoSizes[0] = 30;  
            mMemInfoSizes[1] = -30;  
            arglist[0] = new String("/proc/meminfo");  
            arglist[1] = mMemInfoFields;  
            arglist[2] = mMemInfoSizes;  
            if(_readProclines!=null){  
                _readProclines.invoke(null, arglist);  
                for (int i=0; i<mMemInfoSizes.length; i++) {  
                    Log.d("GetFreeMem", mMemInfoFields[i]+" : "+mMemInfoSizes[i]/1024);  
                }  
            }  
        } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
        } catch (SecurityException e) {  
            e.printStackTrace();  
        } catch (IllegalArgumentException e) {  
            e.printStackTrace();  
        } catch (IllegalAccessException e) {  
            e.printStackTrace();  
        } catch (InvocationTargetException e) {  
            e.printStackTrace();  
        } catch (NoSuchMethodException e) {  
            e.printStackTrace();  
        }  
    }  
}  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值