获得手机相关信息的实现方法
本文介绍了如何通过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 = "纬度:" + lat + "\n" + "经度:" + lng;
} else {
latLongString = "无法获取地理信息";
}
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 & 0xFF) + "." + ((i >>[img]/images/smiles/icon_cool.gif" alt="[/img] & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 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("可用:" + availableSize / 1024 / 1024 / 1024 + "GB" + " 总共:"
+ allSize / 1024 / 1024 / 1024 + "GB");
} else {
sdcardText.setText("不可用");
}
}
public void getDisplayMetrics() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
dpiText.setText(displayMetrics.widthPixels + "x"
+ displayMetrics.heightPixels);
}
public void isNetConnecting() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected()) {
networkText.setText("当前无网络");
} else {
networkText.setText("当前网络正常");
}
}
/**
* 获取手机可用内存和总内存
*
*/
private void getSystemMemory() {
String availMemory = getAvailMemory();
String totalMemory = getTotalMemory();
memoryText.setText("可用内存:" + availMemory + "\n" + "总内存:" + 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 = "/proc/meminfo";// 系统内存信息文件
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("\\s+");
for (String num : arrayOfString) {
Log.i(sysTotalMem, num + "\t");
}
initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
localBufferedReader.close();
} catch (IOException e) {
}
return Formatter.formatFileSize(getBaseContext(), initial_memory);
}
private void getCpuInfo() {
String str1 = "/proc/cpuinfo";
String str2 = "";
//1-cpu型号
//2-cpu频率
String[] cpuInfo = { "", "" };
String[] arrayOfString;
try {
FileReader fr = new FileReader(str1);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
for (int i = 2; i < arrayOfString.length; i++) {
cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
}
str2 = localBufferedReader.readLine();
arrayOfString = str2.split("\\s+");
cpuInfo[1] += arrayOfString[2];
localBufferedReader.close();
} catch (IOException e) {
}
cpuText.setText("cpu型号:" + cpuInfo[0] + "\n" + "cpu频率:" + cpuInfo[1]);
}
private void getImei() {
TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei = mTelephonyMgr.getDeviceId();
imeiText.setText(imei);
}
}
最后附上源代码以供参考
执行效果图如下