获得手机相关信息的实现方法

      本文介绍了如何通过android提供的service来获取手机的相关信息。比如:手机当前网络连接状态、运行内存使用情况、cpu型号、sd卡、ip等相关信息。
一、设置访问权限
在AndroidManifest.xml 文件中加入访问权限
  

<!-- 连接互联网Internet权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GPS -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- 获取ip权限 -->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!-- SD卡存储信息 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 网络是否连接 -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 手机imei -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

 
二、主页面layout布局,采用RelativeLayout方式布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/phone_gps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="GPS"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_gps_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:layout_toRightOf="@id/phone_gps"
        android:text="12321"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_network_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/phone_network"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/phone_network"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_network"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_gps"
        android:layout_marginTop="20dp"
        android:text="网络连接"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_memory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_network"
        android:layout_marginTop="20dp"
        android:text="手机内存"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_memory_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/phone_memory"
        android:layout_alignBottom="@+id/phone_memory"
        android:layout_alignLeft="@+id/phone_network_value"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_cpu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_memory"
        android:layout_marginTop="20dp"
        android:text="CPU"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_cpu_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/phone_cpu"
        android:layout_alignBottom="@+id/phone_cpu"
        android:layout_alignLeft="@+id/phone_memory_value"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_sdcard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_cpu"
        android:layout_marginTop="40dp"
        android:text="SD卡"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_sdcard_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/phone_sdcard"
        android:layout_alignBottom="@+id/phone_sdcard"
        android:layout_alignLeft="@+id/phone_cpu_value"
        android:layout_marginTop="40dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_dpi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_sdcard_value"
        android:layout_marginTop="20dp"
        android:text="分辨率"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_dpi_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/phone_dpi"
        android:layout_alignLeft="@+id/phone_sdcard_value"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_dpi"
        android:layout_marginTop="20dp"
        android:text="IP"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_ip_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/phone_ip"
        android:layout_alignLeft="@+id/phone_dpi_value"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_imei"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_ip"
        android:layout_marginTop="20dp"
        android:text="IMEI"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_imei_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/phone_ip_value"
        android:layout_alignTop="@+id/phone_imei"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_mac"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/phone_imei"
        android:text="MAC"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/phone_mac_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/phone_imei_value"
        android:layout_below="@+id/phone_imei_value"
        android:text="Medium Text"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

 
三、主程序实现
public class MainActivity extends Activity {

private TextView gpsText;
private TextView networkText;
private TextView memoryText;
private TextView cpuText;
private TextView sdcardText;
private TextView dpiText;
private TextView ipText;
private TextView macText;
private TextView imeiText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
protected void onResume() {
super.onResume();
initView();
setGps();
getSDCardInfo();
getDisplayMetrics();
isNetConnecting();
getSystemMemory();
getCpuInfo();
getImei();
getLocalIpAddress();
getLocalMacAddress();

}
private void initView() {
gpsText = (TextView)findViewById(R.id.phone_gps_value);
networkText = (TextView)findViewById(R.id.phone_network_value);
memoryText = (TextView)findViewById(R.id.phone_memory_value);
cpuText = (TextView)findViewById(R.id.phone_cpu_value);
sdcardText = (TextView)findViewById(R.id.phone_sdcard_value);
dpiText = (TextView)findViewById(R.id.phone_dpi_value);
ipText = (TextView)findViewById(R.id.phone_ip_value);
macText = (TextView)findViewById(R.id.phone_mac_value);
imeiText = (TextView)findViewById(R.id.phone_imei_value);
}

private void setGps() {
LocationManager locationManager;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// 设置精度
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);// 获取一个最符合查询条件的位置提供者

Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
}

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}

public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}

public void onProviderEnabled(String provider) {
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}
};

private void updateWithNewLocation(Location location) {
String latLongString;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = &quot;纬度:&quot; + lat + &quot;\n&quot; + &quot;经度:&quot; + lng;
} else {
latLongString = &quot;无法获取地理信息&quot;;
}
gpsText.setText(latLongString);
}


public void getLocalIpAddress() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
ipText.setText(ip);
}

private String intToIp(int i) {
return (i &amp; 0xFF) + &quot;.&quot; + ((i &gt;&gt;[img]/images/smiles/icon_cool.gif&quot; alt=&quot;[/img] &amp; 0xFF) + &quot;.&quot; + ((i &gt;&gt; 16) &amp; 0xFF)
+ &quot;.&quot; + (i &gt;&gt; 24 &amp; 0xFF);
}

/**
* 获得mac地址信息
*/
public void getLocalMacAddress() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
macText.setText(info.getMacAddress());
}

/**
* 获取Android手机中SD卡存储信息 获取剩余空间
*/
public void getSDCardInfo() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File path = Environment.getExternalStorageDirectory();
StatFs statfs = new StatFs(path.getPath());
long blocSize = statfs.getBlockSize();
long totalBlocks = statfs.getBlockCount();
long availaBlock = statfs.getAvailableBlocks();
long availableSize = blocSize * availaBlock;
long allSize = blocSize * totalBlocks;
sdcardText.setText(&quot;可用:&quot; + availableSize / 1024 / 1024 / 1024 + &quot;GB&quot; + &quot;  总共:&quot;
+ allSize / 1024 / 1024 / 1024 + &quot;GB&quot;);
} else {
sdcardText.setText(&quot;不可用&quot;);
}

}

public void getDisplayMetrics() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
dpiText.setText(displayMetrics.widthPixels + &quot;x&quot;
+ displayMetrics.heightPixels);
}


public void isNetConnecting() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected()) {
networkText.setText(&quot;当前无网络&quot;);
} else {
networkText.setText(&quot;当前网络正常&quot;);
}

}

/**
* 获取手机可用内存和总内存
*
*/
private void getSystemMemory() {
String availMemory = getAvailMemory();
String totalMemory = getTotalMemory();
memoryText.setText(&quot;可用内存:&quot; + availMemory + &quot;\n&quot; + &quot;总内存:&quot; + totalMemory);
}


private String getAvailMemory() {
//已使用内存
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 sysMemInfo = &quot;/proc/meminfo&quot;;// 系统内存信息文件
String sysTotalMem;
String[] arrayOfString;
long initial_memory = 0;
try {
FileReader localFileReader = new FileReader(sysMemInfo);
BufferedReader localBufferedReader = new BufferedReader(
localFileReader, 8192);
//读取系统总内存
sysTotalMem = localBufferedReader.readLine();

arrayOfString = sysTotalMem.split(&quot;\\s+&quot;);
for (String num : arrayOfString) {
Log.i(sysTotalMem, num + &quot;\t&quot;);
}
initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
localBufferedReader.close();

} catch (IOException e) {
}
return Formatter.formatFileSize(getBaseContext(), initial_memory);
}

private void getCpuInfo() {
String str1 = &quot;/proc/cpuinfo&quot;;
String str2 = &quot;&quot;;
//1-cpu型号
//2-cpu频率
String[] cpuInfo = { &quot;&quot;, &quot;&quot; };
String[] arrayOfString;
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split(&quot;\\s+&quot;);
for (int i = 2; i &lt; arrayOfString.length; i++) {
cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + &quot; &quot;;
}
str2 = localBufferedReader.readLine();
arrayOfString = str2.split(&quot;\\s+&quot;);
cpuInfo[1] += arrayOfString[2];
localBufferedReader.close();
} catch (IOException e) {
}
cpuText.setText(&quot;cpu型号:&quot; + cpuInfo[0] + &quot;\n&quot; + &quot;cpu频率:&quot; + cpuInfo[1]);
}

private void getImei() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTelephonyMgr.getDeviceId();
imeiText.setText(imei);
}

}

最后附上源代码以供参考

执行效果图如下

获得手机相关信息的实现方法

相关推荐