Android开发常用工具方法(CommonTools)

10 篇文章 0 订阅
7 篇文章 0 订阅

在发开Android应用过程中,我们往往添加一个Utils包放置一些帮助方法类(这也是很好的Android开发习惯),这样大大方便了开发时的调取操作、也使得软件维护、更新更为便捷,以下就是我常用的几个util类:有关于网络的、文件操作的等等! 

转载自:http://blog.csdn.net/zhangtengyuan23/article/details/19295055

public class CommonTools {

	
	
	/**
	 * 短暂显示Toast消息
	 * 
	 * @param context
	 * @param message
	 */
	public static void showShortToast(Context context, String message) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.custom_toast, null);
		TextView text = (TextView) view.findViewById(R.id.toast_message);
		text.setText(message);
		Toast toast = new Toast(context);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.BOTTOM, 0, 300);
		toast.setView(view);
		toast.show();
	}

	/**
	 * 根据手机分辨率从dp转成px
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f) - 15;
	}

	/**
	 * 获取手机状态栏高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusBarHeight(Context context) {
		Class<?> c = null;
		Object obj = null;
		java.lang.reflect.Field field = null;
		int x = 0;
		int statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = context.getResources().getDimensionPixelSize(x);
			return statusBarHeight;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return statusBarHeight;
	}

	
	/**
	 * 判断手机号码*/
	public static boolean isMobileNO(String mobiles){
		
		Pattern pattern = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
		Matcher matcher = pattern.matcher(mobiles);  
		
		return matcher.matches();
		
	}
	
	
}

关于网络判断的类NetworkUtils

public class NetworkUtils {

	/**
	 * 网络是否可用
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 网络连接提示
	 * 
	 * @param context
	 * @return
	 */
	public static void networkStateTips(Context context) {
		if (!isNetworkAvailable(context)) {
			CommonTools.showShortToast(context, "网络故障,请先检查网络连接");
		}
	}

	/**
	 * Gps是否打开
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isGpsEnabled(Context context) {
		LocationManager locationManager = ((LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE));
		List<String> accessibleProviders = locationManager.getProviders(true);
		return accessibleProviders != null && accessibleProviders.size() > 0;
	}

	/**
	 * wifi是否打开
	 */
	public static boolean isWifiEnabled(Context context) {
		ConnectivityManager mgrConn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		TelephonyManager mgrTel = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
				.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
				.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
	}

	/**
	 * 判断当前网络是否是wifi网络
	 * if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) { //判断3G网
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean isWifi(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 判断当前网络是否是3G网络
	 * 
	 * @param context
	 * @return boolean
	 */
	public static boolean is3G(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			return true;
		}
		return false;
	}
}

文件操作类FileUtils

public class FileUtils {
    private final static String t = "FileUtils";

    // Used to validate and display valid form names.
    public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";

    // Storage paths
    public static final String FORMS_PATH = Environment.getExternalStorageDirectory() + "/odk/forms/";
    public static final String INSTANCES_PATH = Environment.getExternalStorageDirectory() + "/odk/instances/";
    public static final String CACHE_PATH = Environment.getExternalStorageDirectory() + "/odk/.cache/";
    public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";

    
    public static ArrayList<String> getValidFormsAsArrayList(String path) {
        ArrayList<String> formPaths = new ArrayList<String>();
        File dir = new File(path);

        if (!storageReady()) {
            return null;
        }
        if (!dir.exists()) {
            if (!createFolder(path)) {
                return null;
            }
        }
        File[] dirs = dir.listFiles();
        for (int i = 0; i < dirs.length; i++) {
          // skip all the directories
          if (dirs[i].isDirectory())
            continue;
          
            String formName = dirs[i].getName();

          formPaths.add(dirs[i].getAbsolutePath());
        }
        return formPaths;
    }

    public static ArrayList<String> getFoldersAsArrayList(String path) {
        ArrayList<String> mFolderList = new ArrayList<String>();
        File root = new File(path);

        if (!storageReady()) {
            return null;
        }
        if (!root.exists()) {
            if (!createFolder(path)) {
                return null;
            }
        }
        if (root.isDirectory()) {
            File[] children = root.listFiles();
            for (File child : children) {
                boolean directory = child.isDirectory();
                if (directory) {
                    mFolderList.add(child.getAbsolutePath());
                }
            }
        }
        return mFolderList;
    }


    public static boolean deleteFolder(String path) {
        // not recursive
        if (path != null && storageReady()) {
            File dir = new File(path);
            if (dir.exists() && dir.isDirectory()) {
                File[] files = dir.listFiles();
                for (File file : files) {
                    if (!file.delete()) {
                        Log.i(t, "Failed to delete " + file);
                    }
                }
            }
            return dir.delete();
        } else {
            return false;
        }
    }


    public static boolean createFolder(String path) {
        if (storageReady()) {
            boolean made = true;
            File dir = new File(path);
            if (!dir.exists()) {
                made = dir.mkdirs();
            }
            return made;
        } else {
            return false;
        }
    }


    public static boolean deleteFile(String path) {
        if (storageReady()) {
            File f = new File(path);
            return f.delete();
        } else {
            return false;
        }
    }


    public static byte[] getFileAsBytes(File file) {
        byte[] bytes = null;
        InputStream is = null;
        try {
            is = new FileInputStream(file);

            // Get the size of the file
            long length = file.length();
            if (length > Integer.MAX_VALUE) {
                Log.e(t, "File " + file.getName() + "is too large");
                return null;
            }

            // Create the byte array to hold the data
            bytes = new byte[(int) length];

            // Read in the bytes
            int offset = 0;
            int read = 0;
            try {
                while (offset < bytes.length && read >= 0) {
                    read = is.read(bytes, offset, bytes.length - offset);
                    offset += read;
                }
            } catch (IOException e) {
                Log.e(t, "Cannot read " + file.getName());
                e.printStackTrace();
                return null;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                try {
                    throw new IOException("Could not completely read file " + file.getName());
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            return bytes;

        } catch (FileNotFoundException e) {
            Log.e(t, "Cannot find " + file.getName());
            e.printStackTrace();
            return null;

        } finally {
            // Close the input stream
            try {
                is.close();
            } catch (IOException e) {
                Log.e(t, "Cannot close input stream for " + file.getName());
                e.printStackTrace();
                return null;
            }
        }
    }


    public static boolean storageReady() {
        String cardstatus = Environment.getExternalStorageState();
        if (cardstatus.equals(Environment.MEDIA_REMOVED)
                || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
                || cardstatus.equals(Environment.MEDIA_UNMOUNTED)
                || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return false;
        } else {
            return true;
        }
    }


    public static String getMd5Hash(File file) {
        try {
            // CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
            MessageDigest md = MessageDigest.getInstance("MD5");
            int chunkSize = 256;

            byte[] chunk = new byte[chunkSize];

            // Get the size of the file
            long lLength = file.length();

            if (lLength > Integer.MAX_VALUE) {
                Log.e(t, "File " + file.getName() + "is too large");
                return null;
            }

            int length = (int) lLength;

            InputStream is = null;
            is = new FileInputStream(file);

            int l = 0;
            for (l = 0; l + chunkSize < length; l += chunkSize) {
                is.read(chunk, 0, chunkSize);
                md.update(chunk, 0, chunkSize);
            }

            int remaining = length - l;
            if (remaining > 0) {
                is.read(chunk, 0, remaining);
                md.update(chunk, 0, remaining);
            }
            byte[] messageDigest = md.digest();

            BigInteger number = new BigInteger(1, messageDigest);
            String md5 = number.toString(16);
            while (md5.length() < 32)
                md5 = "0" + md5;
            is.close();
            return md5;

        } catch (NoSuchAlgorithmException e) {
            Log.e("MD5", e.getMessage());
            return null;

        } catch (FileNotFoundException e) {
            Log.e("No Cache File", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Problem reading from file", e.getMessage());
            return null;
        } 
        

    }

}

数据库操作

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zz.zzdbase;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

@SuppressWarnings({"unused" })
public class citybase {

	private SQLiteDatabase dbase;
	private Cursor cursor;
	private Cursor exeCheckCursor;
	private Cursor _cursor;

	public boolean open(String dbPath) {
		
		
		if(dbase!=null)
			return true;
		
		try
		{
			dbase = SQLiteDatabase.openDatabase(dbPath, null,
			SQLiteDatabase.OPEN_READWRITE);
            if(dbase==null)
            {
            	 dbase = SQLiteDatabase.openOrCreateDatabase(dbPath, null);
            }
            return true;
		}catch (Exception e) {
			
			 return false;
		}
		    
               
	}

	public void close() {
		if(cursor!=null)
			cursor.close();
		if(_cursor!=null)
			_cursor.close();
		if(dbase!=null)
			dbase.close();
		dbase = null;
	}
     
	
	public Cursor GetCursor()
	{
		return cursor;
	}
	
	public void cursorClose()
    {
		cursor.close();
    }

	public boolean exeNoQuery(String sql) 
	{
		Boolean b = true;
		try 
		{
			dbase.execSQL(sql);
		} catch (Exception e) {
			b = false;
		}
		return b;
	}

	public boolean exeQuery(String sql) 
    {
		Boolean b = true;
		try 
		{
			cursor = dbase.rawQuery(sql, null);
            if(cursor==null)
               return false;
		} catch (Exception e)
        {
            String s=e.getMessage();
            b = false;
		}
		return b;
	}
	
	
	public SQLiteDatabase GetDB()
	{
		return dbase;
	}
	
	
	public boolean exeCheckQuery(String sql) 
    {
		Boolean b = true;
		try 
		{
			exeCheckCursor = dbase.rawQuery(sql, null);
            if(exeCheckCursor==null)
               return false;
		} catch (Exception e)
        {
            String s=e.getMessage();
            b = false;
		}
		return b;
	}
	
	public Boolean nextExeRecorCheck()
	{
		return exeCheckCursor.moveToNext();
	} 
	
	public void cursorExeCloseCheck()
    {
		exeCheckCursor.close();
    }
	
	
	public Boolean exeQueryTemp(String sql)
	{
		Boolean b = true;
		try 
		{
			_cursor = dbase.rawQuery(sql, null);
            if(_cursor==null)
               return false;
		} catch (Exception e)
        {
            String s=e.getMessage();
            b = false;
		}
		return b;
	}
	
	private Cursor checkCursor;
	public Boolean exeQueryCheck(String sql)
	{
		Boolean b = true;
		try 
		{
			checkCursor = dbase.rawQuery(sql, null);
            if(checkCursor==null)
               return false;
		} catch (Exception e)
        {
            String s=e.getMessage();
            b = false;
		}
		return b;
	}
	
	public Boolean eQueryCheck(String sql)
	{
		Boolean b = true;
		try 
		{
			checkCursor = dbase.rawQuery(sql, null);
            if(checkCursor==null)
               return false;
		} catch (Exception e)
        {
            String s=e.getMessage();
            b = false;
		}
		return b;
	}
	
	
	public Boolean nextRecorCheck()
	{
		return checkCursor.moveToNext();
	} 
	
	public void cursorCloseCheck()
    {
		checkCursor.close();
    }

	
	
	public Boolean nextRecordTemp()
	{
		Boolean flag = _cursor.moveToNext();
		return flag;
	}
	
	public void cursorCloseTemp()
    {
		_cursor.close();
    }

	
	
	public boolean nextRecord() 
	{
		if(cursor==null)
			return false;
		
		return cursor.moveToNext();
    }
	
	
	
	
    public boolean moveToFirst()
    {
        return cursor.moveToFirst();
    }

	public int GetInteger(int colm) {
		return cursor.getInt(colm);
	}

	public String GetString(int colm) {
		return cursor.getString(colm);
	}
	
	public String GetCheckString(int colm)
	{
		return checkCursor.getString(colm);
	}
	
	public String GetStringTmp(int colm) {
		return _cursor.getString(colm);
	}
	
	public double GetDouble(int colm) {
		return cursor.getDouble(colm);
	}

	public int GetColumnType(int colm) 
    {
		//return cursor.getType(colm);
            return 1;
	}

	public int GetColumnCount() {
		return cursor.getColumnCount();
	}

	public String GetFieldName(int colm) {
		return cursor.getColumnName(colm);
	}

	public int GetRecordNum() {
		
		
		return cursor.getCount();
	}

	public byte[] GetBolb(int colm) {
		return cursor.getBlob(colm);
	}
        
        public boolean checkDataBase(String databaseFilename) 
        {

            SQLiteDatabase checkDB = null;

            try
            {

			//String databaseFilename = DATABASE_PATH + DATABASE_FILENAME;

			checkDB = SQLiteDatabase.openDatabase(databaseFilename, null,
					SQLiteDatabase.OPEN_READONLY);

            } 
            catch (SQLiteException e)
            {
			// database does't exist yet.
            }

            if (checkDB != null)
            {
			checkDB.close();
            }
            return checkDB != null ? true : false;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
此工具我不再更新,里面大多数方法我迁移到了hutool工具包中,而其中一些不常用的功能被遗弃,项目暂留做为以后参考。 common-tools 一、数据库工具类 1、com.baijob.commonTools.db.ds C3p0Ds 和 DruidDs分别是两种连接池的实现,依赖于数据库配置文件,配置文件的样例参考config/db-example.setting 使用时将db-example.setting复制于${classpath}/config/db.setting,按照配置文件中的说明替换相应值 如果使用Druid,则需参考druid-example.setting创建${classpath}/config/druid.setting文件,详情请参考官方文档 使用C3P0则需要参考c3p0-config-example.xml创建${classpath}/c3p0-config.xml来调节C3P0参数 此时即可调用C3p0Ds.getDataSource()或DruidDs.getDataSource()方法获得默认的数据源 如果要自定义数据库配置文件的参数,请调用相应的init(),传入相关参数 注:Setting对象请参考与之对应的章节 2、com.baijob.commonTools.db.DbUtil 数据库工具类,提供了关闭方法:关闭可以传入多个参数,关闭的顺序是按照参数的顺序来的,用于一次性关闭Connnection、Statement、ResultSet等 newSqlRunner方法用于快速新建一个SqlRunner(此类介绍参考下问) 3、com.baijob.commonTools.db.DsSetting,用于读取db.setting文件辅助类,内部使用 4、com.baijob.commonTools.db.SqlRunner类参考Apache的DbUtils工具包,封装了常用的增删改查方法,与com.baijob.commonTools.db.RsHandler配合使用 com.baijob.commonTools.db.RsHandler接口与Apache的DbUtils的ResultSetHandler等价,抽象结果集处理。 二、邮件工具类 1、com.baijob.commonTools.mail.MailAccount 邮件账户类。 可以调用MailAccount(String accountSettingFileBaseClassLoader)读取相对路径的Setting文件,配置参考mailAccount-example.setting 2、com.baijob.commonTools.mail.MailUtil邮件发送工具类,方法请参考注释 此工具类依赖javax.mail,请参考pom.xml添加依赖或手动下载 三、网络相关工具类 1、com.baijob.commonTools.net.AccessControl访问控制,基于配置文件,可以设定IP白名单或黑名单,可以通过配置文件实现简单的账户验证。 配置文件请参考access-example.xml 2、com.baijob.commonTools.net.Connector 连接对象实体类,有host、端口、用户名、密码等属性 3、com.baijob.commonTools.net.HtmlUtil HTML工具类,暂时只提供特殊字符转义 4、com.baijob.commonTools.net.SocketUtil socket工具类。 isUsableLocalPort() 检测本地某个端口是否可用(可用是指没有被其他程序占用) isValidPort()是否是符合规范的端口号 longToIpv4()将long转换为ipv4地址,反方法是ipv4ToLong() netCat()简易的数据发送方法 5、com.baijob.commonTools.net.SSHUtil SSH相关工具类 getSession()获得一个SSH会话 bindPort()将远程主机的端口映射到本地某个端口 6、com.baijob.commonTools.net.URLUtil 将相对、绝对路径转换为URL对象,用于网络或文件流的读写,Setting的配置依赖此工具包 四、线程相关工具类 1、com.baijob.commonTools.thread.BaseRunnable 此类实现了Runnable接口,扩展了功能。 增加名称、ID,调用次数和时间统计、线程停止接口等,并且在线程运行时,不允许此线程第二次启动。 2、com.baijob.commonTools.thread.Executor 线程池工具类 调用静态方法execute()启动线程,此线程在公共的线程池中执行 若想自定义线程池大小或独立控制,可调用newExecutor()实例化一个线程池 excAsync()执行一个异步方法 3、com.baijob.commonTools.thread.SyncQueue 阻塞队列,简化了JDK的BlockingQueue
常用的Android Studio工具类有以下几个: 1. AndroidUniqueID: 这是一个用于获取Android设备唯一标识符的工具类,可以通过GitHub链接(https://github.com/appdevzhang/AndroidUniqueID)找到详细使用方法。 2. Lazy android: 这是一个方便快捷的Android工具类,通过GitHub链接(https://github.com/l123456789jy/Lazy android)可以了解它的具体功能和用法。 3. Utils-Everywhere: 这是一个Android各种工具类的集合,通过GitHub链接(https://github.com/SenhLinsh/Utils-Everywhere)可以查看所有可用的工具类和使用方法。 这些工具类都是为了方便开发者在Android Studio中进行开发而设计的,可以提高开发效率和代码质量。同时,还可以使用Lint工具来进行静态代码检查,找出代码结构和质量问题,并提供解决方案。通过Android Studio自带的Lint功能,可以进行一些常见的代码优化,去除多余的资源等。 可以通过这个(https://blog.csdn.net/ouyang_peng/article/details/80374867)链接来了解更多关于Lint工具的配置和使用方法。 除了Lint工具,还有其他的静态代码检查框架,如FindBugs、PMD和Checkstyle等,它们可以检查Java源文件或class文件的代码质量和代码风格。但在Android开发中,我们通常会选择使用Lint框架,因为它提供了强大的功能、扩展性和与Android Studio、Android Gradle插件的原生支持。此外,Lint框架还提供了许多有用的Android相关检查规则,而且有Google官方的支持,在Android开发工具的升级中也会得到完善。 你可以通过这个链接(https://blog.csdn.net/MeituanTech/article/details/79922364)了解更多关于Lint框架的使用和优势。 总结来说,Android Studio常用的工具类包括AndroidUniqueID、Lazy android和Utils-Everywhere等,而Lint工具则可以帮助我们进行静态代码检查和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值