android开发中经常用到的关于手机的一些属性总结如下:
一、手机型号和系统版本号:(手机型号:HTC SDK版本:18 系统版本:4.3.1)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView = (TextView) findViewById(R.id.text);
textView.setText("手机型号: " + android.os.Build.MODEL + ",\nSDK版本:"
+ android.os.Build.VERSION.SDK + ",\n系统版本:"
+ android.os.Build.VERSION.RELEASE);
}
二、手机屏幕分辨率:(1080*1920)
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
float density = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = metric.densityDpi; // 屏幕密度DPI(120 / 160 / 240)
String.valueOf(width) + "*" + String.valueOf(height)//(1080*1920)
三、检测手机运营商:
/**
* 获取SIM卡运营商
*
* @param context
* @return
*/
public static String getOperators(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String operator = null;
String IMSI = tm.getSubscriberId();
if (IMSI == null || IMSI.equals("")) {
return operator;
}
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
operator = "中国移动";
} else if (IMSI.startsWith("46001")) {
operator = "中国联通";
} else if (IMSI.startsWith("46003")) {
operator = "中国电信";
}else {
operator= "未知类型";
}
return operator;
}
四、检测手机网络状态及网络类型
/**
* 检测网络是否可用
* @return
*/
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
public static String GetNetworkType()
{
String strNetworkType = "";
NetworkInfo networkInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
{
strNetworkType = "WIFI";
}
else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
{
String _strSubTypeName = networkInfo.getSubtypeName();
Log.e("test", "Network getSubtypeName : " + _strSubTypeName);
// TD-SCDMA networkType is 17
int networkType = networkInfo.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
strNetworkType = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
strNetworkType = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
strNetworkType = "4G";
break;
default:
// http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
{
strNetworkType = "3G";
}
else
{
strNetworkType = _strSubTypeName;
}
break;
}
Log.e("test", "Network getSubtype : " + Integer.valueOf(networkType).toString());
}
}
return strNetworkType;
}
五、手机SD卡操作:
<!-- SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在使用SDcard进行读写的时候 会用到Environment类下面的几个静态方法 :
1: getDataDirectory() 获取到Android中的data数据目录(sd卡中的data文件夹)
2:getDownloadCacheDirectory() 获取到下载的缓存目录(sd卡中的download文件夹)
3:getExternalStorageDirectory() 获取到外部存储的目录 一般指SDcard(/storage/sdcard0)
4:getExternalStorageState() 获取外部设置的当前状态 一般指SDcard,比较常用的应该是 MEDIA_MOUNTED(SDcard存在并且可以进行读写)还有其他的一些状态,可以在文档中进行查找。
5:getRootDirectory() 获取到Android Root路径
好,以下是具体操作,直接看代码:
1,判断SD卡是否存在
/**
* 判断SDCard是否存在 [当没有外挂SD卡时,内置ROM也被识别为存在sd卡]
*
* @return
*/
public static boolean isSdCardExist() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
2,获取SD卡根目录
/**
* 获取SD卡根目录路径
*
* @return
*/
public static String getSdCardPath() {
boolean exist = isSdCardExist();
String sdpath = "";
if (exist) {
sdpath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
} else {
sdpath = "不适用";
}
return sdpath;
}
3,获取默认的文件存放路径
/**
* 获取默认的文件路径
*
* @return
*/
public static String getDefaultFilePath() {
String filepath = "";
File file = new File(Environment.getExternalStorageDirectory(),
"abc.txt");
if (file.exists()) {
filepath = file.getAbsolutePath();
} else {
filepath = "不适用";
}
return filepath;
}
4-1,使用FileInputStream读取文件
try {
le file = new File(Environment.getExternalStorageDirectory(),
"test.txt");
FileInputStream is = new FileInputStream(file);
byte[] b = new byte[inputStream.available()];
is.read(b);
String result = new String(b);
System.out.println("读取成功:"+result);
} catch (Exception e) {
e.printStackTrace();
}
4-2,使用BufferReader读取文件(httpurlconnection中经常使用)
URL url = new URL(getForwardUrl("/queryUserByUNorIP"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String readline = null;
while ((readline = br.readLine()) != null) {
sb.append(readline);
}
System.out.println("result"+sb.toString());
等效于使用ByteArrayOutputStream
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len =-1 ;
while ((len=is.read(buffer))!=-1) {
bos.write(buffer, 0, len);
}
is.close();
bos.close();
String result = new String(bos.toByteArray());
System.out.println("result"+result);
5-1,使用FileOutputStream写入文件
try {
File file = new File(Environment.getExternalStorageDirectory(),
DEFAULT_FILENAME);
FileOutputStream fos = new FileOutputStream(file);
String info = "I am a chinanese!";
fos.write(info.getBytes());
fos.close();
System.out.println("写入成功:");
} catch (Exception e) {
e.printStackTrace();
}
5-2,使用BufferedWriter写入文件
try {
File file = new File(Environment.getExternalStorageDirectory(),
DEFAULT_FILENAME);
//第二个参数意义是说是否以append方式添加内容
BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
String info = " hey, yoo,bitch";
bw.write(info);
bw.flush();
System.out.println("写入成功");
} catch (Exception e) {
e.printStackTrace();
}
六、手机是否安装某应用
/**
* 检测本地手机是否安装APP
* @param context 上下文
* @param packageName 包名
* @return
*/
public static boolean isAvilible( Context context, String packageName ){
final PackageManager packageManager = context.getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
for ( int i = 0; i < pinfo.size(); i++ )
{
if(pinfo.get(i).packageName.equalsIgnoreCase(packageName))
return true;
}
return false;
}
七、手机IMEI
/**
* 获取IMEI
*
* @param context
* @return
*/
public static String getIMEI(Context context) {
String imei;
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
imei = tm.getDeviceId();
return TextUtils.isEmpty(imei) ? "@@@@@@@@@" : imei;
}
八、获取手机Mac地址
/**
* 设备Mac地址
*
* @return
*/
public static String getMac() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str;) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (IOException ex) {
// 赋予默认值
ex.printStackTrace();
}
return macSerial;
}
九、获取手机IMSI
/**
* 获取IMSI
*
* @param context
* @return
*/
public static String getIMSI(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
十、获取手机序列号
/**
* 获取设备序列号
*
* @return
*/
public static String getSerialNumber() {
String serial = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class);
serial = (String) get.invoke(c, "ro.serialno");
} catch (Exception e) {
e.printStackTrace();
}
return serial;
}