PhoneUtil工具类

原创 2016年05月30日 15:53:25

PhoneUtil

package com.example.androidutils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.TypedValue;
import android.view.WindowManager;

public class PhoneUtil {
	private static PhoneUtil phoneUtil;

	public static PhoneUtil getInstance() {
		if (phoneUtil == null) {
			synchronized (PhoneUtil.class) {
				if (phoneUtil == null) {
					phoneUtil = new PhoneUtil();
				}
			}
		}
		return phoneUtil;
	}

	/**
	 * 获取手机系统版本号
	 * 
	 * @return
	 */
	public int getSDKVersionNumber() {
		int sdkVersion;
		try {
			sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			sdkVersion = 0;
		}
		return sdkVersion;
	}

	/**
	 * 获取手机型号
	 */
	public String getPhoneModel() {
		return android.os.Build.MODEL;
	}

	/**
	 * 获取手机宽度
	 */
	@SuppressWarnings("deprecation")
	public int getPhoneWidth(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		return wm.getDefaultDisplay().getWidth();
	}

	/**
	 * 获取手机高度
	 * 
	 * @param context
	 */
	@SuppressWarnings("deprecation")
	public int getPhoneHeight(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		return wm.getDefaultDisplay().getHeight();
	}

	/**
	 * 获取手机imei串号 ,GSM手机的 IMEI 和 CDMA手机的 MEID.
	 * 
	 * @param context
	 */
	public String getPhoneImei(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null)
			return null;
		return tm.getDeviceId();
	}

	/**
	 * 获取手机sim卡号
	 * 
	 * @param context
	 */
	public String getPhoneSim(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null)
			return null;
		return tm.getSubscriberId();
	}

	/**
	 * 获取手机号
	 * 
	 * @param context
	 */
	public String getPhoneNum(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm == null)
			return null;
		return tm.getLine1Number();
	}

	/**
	 * 判断sd卡是否挂载
	 */
	public boolean isSDCardMount() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取sd卡剩余空间的大小
	 */
	@SuppressWarnings("deprecation")
	public long getSDFreeSize() {
		File path = Environment.getExternalStorageDirectory(); // 取得SD卡文件路径
		StatFs sf = new StatFs(path.getPath());
		long blockSize = sf.getBlockSize(); // 获取单个数据块的大小(Byte)
		long freeBlocks = sf.getAvailableBlocks();// 空闲的数据块的数量
		// 返回SD卡空闲大小
		return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
	}

	/**
	 * 获取sd卡空间的总大小
	 */
	@SuppressWarnings("deprecation")
	public long getSDAllSize() {
		File path = Environment.getExternalStorageDirectory(); // 取得SD卡文件路径
		StatFs sf = new StatFs(path.getPath());
		long blockSize = sf.getBlockSize(); // 获取单个数据块的大小(Byte)
		long allBlocks = sf.getBlockCount(); // 获取所有数据块数
		// 返回SD卡大小
		return (allBlocks * blockSize) / 1024 / 1024; // 单位MB
	}

	/**
	 * 判断是否是平板
	 */
	public boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	/**
	 * 判断一个apk是否安装
	 * 
	 * @param context
	 * @param packageName
	 */
	public boolean isApkInstalled(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		try {
			pm.getPackageInfo(packageName, 0);
		} catch (PackageManager.NameNotFoundException e) {
			return false;
		}
		return true;
	}

	/**
	 * 拨打电话
	 * 
	 * @param context
	 * @param phoneNum
	 */
	public void call(Context context, String phoneNum) throws Exception {
		if (phoneNum != null && !phoneNum.equals("")) {
			Uri uri = Uri.parse("tel:" + phoneNum);
			Intent intent = new Intent(Intent.ACTION_DIAL, uri);
			context.startActivity(intent);
		}
	}

	/**
	 * 打开网页
	 */
	public void openWeb(Context context, String url) {
		try {
			Uri uri = Uri.parse(url);
			context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取应用权限 名称列表
	 */
	public String[] getAppPermissions(Context context)
			throws NameNotFoundException {
		PackageManager pm = context.getPackageManager();
		PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),
				PackageManager.GET_PERMISSIONS);
		return getAppPermissions(packageInfo);
	}

	public String[] getAppPermissions(PackageInfo packageInfo)
			throws NameNotFoundException {
		return packageInfo.requestedPermissions;
	}

	/**
	 * 获取手机内安装的应用
	 */
	public List<PackageInfo> getInstalledApp(Context context) {
		PackageManager pm = context.getPackageManager();
		return pm.getInstalledPackages(0);
	}

	/**
	 * 获取手机安装非系统应用
	 */
	@SuppressWarnings("static-access")
	public List<PackageInfo> getUserInstalledApp(Context context) {
		List<PackageInfo> infos = getInstalledApp(context);
		List<PackageInfo> apps = new ArrayList<PackageInfo>();
		for (PackageInfo info : infos) {
			if ((info.applicationInfo.flags & info.applicationInfo.FLAG_SYSTEM) <= 0) {
				apps.add(info);
			}
		}
		infos.clear();
		infos = null;
		return apps;
	}

	/**
	 * 获取安装应用的信息
	 */
	public Map<String, Object> getInstalledAppInfo(Context context,
			PackageInfo info) {
		Map<String, Object> appInfos = new HashMap<String, Object>();
		PackageManager pm = context.getPackageManager();
		ApplicationInfo aif = info.applicationInfo;
		appInfos.put("icon", pm.getApplicationIcon(aif));
		appInfos.put("lable", pm.getApplicationLabel(aif));
		appInfos.put("packageName", aif.packageName);
		return appInfos;
	}

	/**
	 * 打开指定包名的应用
	 */
	public void startAppPkg(Context context, String pkg) {
		Intent startIntent = context.getPackageManager()
				.getLaunchIntentForPackage(pkg);
		startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(startIntent);
	}

	/**
	 * 卸载指定包名的应用
	 */
	public void unInstallApk(Context context, String packageName) {
		Uri uri = Uri.parse("package:" + packageName);
		Intent intent = new Intent(Intent.ACTION_DELETE);
		intent.setData(uri);
		context.startActivity(intent);
	}

	/**
	 * 手机号判断
	 */
	public static boolean isMobileNO(String mobile) {
		Pattern p = Pattern
				.compile("^((145|147)|(15[^4])|(17[0-9])|((13|18)[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobile);
		return m.matches();
	}

}

测试代码:

package com.example.androidutils;

import java.io.File;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
	Button openWeb,call,startAppPkg,unInstallApk;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initRes();
		Log.i("TAG", "获取手机系统版本号-->"
				+ PhoneUtil.getInstance().getSDKVersionNumber());
		Log.i("TAG", "获取手机型号-->" + PhoneUtil.getInstance().getPhoneModel());
		Log.i("TAG", "获取手机宽度-->" + PhoneUtil.getInstance().getPhoneWidth(this)
				+ "获取手机高度-->" + PhoneUtil.getInstance().getPhoneHeight(this));
		
		
		Log.i("TAG", "获取手机imei串号-->" + PhoneUtil.getInstance().getPhoneImei(this));
		Log.i("TAG", "获取手机sim卡号-->" + PhoneUtil.getInstance().getPhoneSim(this));
		Log.i("TAG", "获取手机号-->" + PhoneUtil.getInstance().getPhoneNum(this));
		Log.i("TAG", "判断sd卡是否挂载-->" + PhoneUtil.getInstance().isSDCardMount());
		Log.i("TAG", "获取sd卡剩余空间的大小-->" + PhoneUtil.getInstance().getSDFreeSize());
		Log.i("TAG", "获取sd卡空间的总大小-->" + PhoneUtil.getInstance().getSDAllSize());
		Log.i("TAG", "判断是否为平板-->" + PhoneUtil.getInstance().isTablet(this));
		Log.i("TAG", "判断是否安装某应用-->" + PhoneUtil.getInstance().isApkInstalled(this,"com.android.mms"));
		
		try {
			String[] appPermissions = PhoneUtil.getInstance().getAppPermissions(this);
			for (int i = 0; i < appPermissions.length; i++) {
				Log.i("TAG", "获取权限列表-->" +appPermissions[i] );
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		List<PackageInfo> installedApp = PhoneUtil.getInstance().getInstalledApp(this);
		for (int i = 0; i < installedApp.size(); i++) {
			Log.i("TAG", "获取手机内安装的应用-->" + installedApp.get(i).packageName);
			
		}
		
		List<PackageInfo> userInstalledApp = PhoneUtil.getInstance().getUserInstalledApp(this);
		for (int i = 0; i < userInstalledApp.size(); i++) {
			Log.i("TAG", "获取手机内安装非系统应用-->" + userInstalledApp.get(i).packageName);
			Map<String, Object> pakInfos = PhoneUtil.getInstance().getInstalledAppInfo(this,userInstalledApp.get(i));
			 for (String key : pakInfos.keySet()) {  
				 Log.i("TAG","获取手机内安装非系统应用的icon、包名、label--key = " + key + " and value = " + pakInfos.get(key));  
		        } 
			
		}
		
		Log.i("TAG","是否为电话号码:"+PhoneUtil.getInstance().isMobileNO("118"));
		
	}

	private void initRes() {
		openWeb = (Button) findViewById(R.id.openWeb);
		call = (Button) findViewById(R.id.call);
		startAppPkg = (Button) findViewById(R.id.startAppPkg);
		unInstallApk = (Button) findViewById(R.id.unInstallApk);
		openWeb.setOnClickListener(this);
		call.setOnClickListener(this);
		startAppPkg.setOnClickListener(this);
		unInstallApk.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.call:
			try {
				PhoneUtil.getInstance().call(MainActivity.this, "10086");
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.openWeb:
			PhoneUtil.getInstance().openWeb(this, "http://www.baidu.com");
			
			break;
		case R.id.startAppPkg:

			PhoneUtil.getInstance().startAppPkg(this, "com.android.mms");
			break;
		case R.id.unInstallApk:
			
			PhoneUtil.getInstance().unInstallApk(this, "com.android.mms");
			break;

		default:
			break;
		}
	}

}

权限如下:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>


手机号码段及归属地查询规则

手机号码段及归属地查询规则 转:http://dengo.org/archives/939?utm_source=tuicool&utm_medium=referral 今天用java...
  • pzasdq
  • pzasdq
  • 2016年01月26日 15:04
  • 2693

java 用webservice 获取国内手机号码归属地省份、地区和手机卡类型信息

提供一个web服务网址供大家学习: http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx 或者 http://ww...

DateUtil时间工具类

  • 2017年11月22日 09:22
  • 12KB
  • 下载

写ORC 格式文件,HIVE 工具类

  • 2017年11月16日 14:48
  • 9KB
  • 下载

Android6.0权限问题,并撰写常用权限工具类

在android6.0手机调用系统相机的时候,报如下错误: java.lang.RuntimeException: Unable to start activity ComponentInfo{cn....

php验证码工具类

  • 2017年11月22日 19:25
  • 19KB
  • 下载

java操作excel工具类

  • 2017年11月15日 17:12
  • 23.38MB
  • 下载

强大的Java Json工具类

import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:PhoneUtil工具类
举报原因:
原因补充:

(最多只允许输入30个字)