关闭

PhoneUtil工具类

733人阅读 评论(0) 收藏 举报
分类:

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"/>


0
0
查看评论

Android开发几种常用工具类

本人只是简单列举几种常用工具类,如果各位看客有更好的,请留下你们的足迹共同分享,在此先谢谢了! AppUtil工具类: import java.io.File; import java.util.ArrayList; import java.util.List; import android.ap...
  • dimudan2015
  • dimudan2015
  • 2017-05-04 09:54
  • 1533

终于整理好了,安卓日常开发工具大合集

2.1 httpUtils https://github.com/Trinea/android-common/blob/master/src/cn/trinea/android/common/util/HttpUtils.java 2.2 DownLoadUtils htt...
  • slandkiss
  • slandkiss
  • 2016-01-20 10:37
  • 835

PhoneUtil工具类

PhoneUtil package com.example.androidutils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; impo...
  • u013210620
  • u013210620
  • 2016-05-30 15:53
  • 733

工具类-- PhoneUtil 获取手机版本号

public class PhoneUtil { private static final TelephonyManager tm = (TelephonyManager) BmacNfc.getInstance( ) .getSystemService(Context.TE...
  • jackron2014
  • jackron2014
  • 2016-08-22 14:03
  • 314

工具类(一)-----微信工具类

前些天做微信授权登录用到了一些关于调用微信接口的东西,写了个工具类分享给大家,如有问题欢迎大家批评指正!!!
  • u012999796
  • u012999796
  • 2017-06-19 14:43
  • 3019

android studio android 测试

android studio 2.1.1 一、安卓单元测试 1.直接在软件提供的测试类中写测试方法或者参考现成的类自己写测试类 public class ApplicationTest extends ApplicationTestCase { public ApplicationTest...
  • daqi1983
  • daqi1983
  • 2016-08-26 16:33
  • 293

android开发一个定位和轨迹播放的程序

最近很多的跑步app,大概功能就是点击“开始”就自动定位,然后记录位置,上传到服务端(也有不上传的),最后将运动的轨迹在地图上显示出来。因为开启gps一般是每3、5秒就记录一下当前的gps,为此需要一个本地数据库支持,可以将位置信息每隔3秒记录一次并保存到本地数据库,然后设置一个消息服务,定时10分...
  • cctcc
  • cctcc
  • 2015-11-27 17:54
  • 5338

Mybatis工具类

import java.io.IOException; import java.io.Reader; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session...
  • flysun3344
  • flysun3344
  • 2016-05-07 00:08
  • 3019

java流工具类使用很方便

package com.auto.generate.utils ; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.File...
  • hfmbook
  • hfmbook
  • 2014-05-14 11:55
  • 3029

iOS 工具类

工具类声明#import <Foundation/Foundation.h>@interface DzcDES : NSObject + (NSString *)encryptWithText:(NSString *)sText encryptWithKey:(NSString *)ke...
  • water_know_cool
  • water_know_cool
  • 2016-05-27 11:49
  • 569