常见Android工具类之列表(未完待续)

常见Android工具类之列表(未完待续。。。)

  • 获取应用程序的版本名和版本号
  • 获取手机联系人的信息(电话号码和名字)
  • 意图开启一个Activity的几种方式
  • 应用程序的Log的控制
  • MD5加密一个字符串得到哈希值
  • 获取手机进程的相关信息(进程的总数、内存可用,总空间)
  • 判断系统的服务是否在后台运行
  • 功能是把一个流对象转换成字符串对象
  • 一个弹吐司的工具类
  • 拷贝资产目录下的数据库到Android系统下

获取应用程序的版本名和版本号

public class AppInfoUtils {
        /*
         *     获取版本名
         */
        public static String getAppInfoName(Context context){

            try {
                    //获取packageManager实例
                    PackageManager pm=context.getPackageManager();
                    //获取版本信息
                    PackageInfo packageinfo= pm.getPackageInfo(context.getPackageName(), 0);
                    String versionname=packageinfo.versionName;
                    return versionname;

                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            return "";

        }


        /*
         * 获取版本号
         */
        public static int getAppInfoNumber(Context context){

            try {
                    //获取packageManager实例
                    PackageManager pm=context.getPackageManager();
                    //获取版本信息
                    PackageInfo packageinfo= pm.getPackageInfo(context.getPackageName(), 0);
                    int versionnumber=packageinfo.versionCode;
                    return versionnumber;

                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
            return 0;

        }
    }

获取手机联系人的信息(电话号码和名字)

    public class ContactsInfoUtils {
        public static List<ContactsInfo> getContactsInfo(Context context){

        List<ContactsInfo> infocontacts=new ArrayList<ContactsInfo>();
            //获取内容提供者的解析器
            ContentResolver resolver=context.getContentResolver();
            Uri uri=Uri.parse("content://com.android.contacts/raw_contacts");
            Uri dataUri=Uri.parse("content://com.android.contacts/data");
            //游标
            Cursor cursor=resolver.query(uri, new String[]{"contact_id"}, null, null, null);
            //遍历游标集合
            while(cursor.moveToNext()){
                String id=cursor.getString(cursor.getColumnIndex("contact_id"));
                System.out.println("id"+id);

                if(id!=null){
                    ContactsInfo infos=new ContactsInfoUtils().new ContactsInfo();
                    Cursor datacursor=resolver.query(dataUri, new String[]{"data1","mimetype"}, "raw_contact_id=?", new String[]{id}, null);
                    while(datacursor.moveToNext()){
                        String data1=datacursor.getString(0);
                        String mimetype=datacursor.getString(1);
                        if("vnd.android.cursor.item/name".equals(mimetype)){
                            //姓名
                            infos.setName(data1);
                        }else if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
                        //电话
                            infos.setPhone(data1);
                        }else if("vnd.android.cursor.item/email_v2".equals(mimetype)){
                        //电话
                        infos.setEmail(data1);
                        }

                    }
                    infocontacts.add(infos);
                }
                return infocontacts;
              }
            return infocontacts;



        }
        public static List<ContactsInfo> getROMContacts(Context context){
               //联系人信息集合
            List<ContactsInfo> contactList  = new ArrayList<ContactsInfo>(); 
         // 获取手机通讯录信息  
         ContentResolver resolver = context.getContentResolver();  
         /** 所有的联系人信息 */  
            Cursor  personCur = resolver.query(ContactsContract.Contacts.CONTENT_URI, null,  
                 null, null, null);  
         // 循环遍历,获取每个联系人的姓名和电话号码  
         while (personCur.moveToNext()) {  
             // 新建联系人对象  
             ContactsInfo cInfor =new ContactsInfoUtils().new ContactsInfo();  
             // 联系人姓名  
             String cname = "";  
             // 联系人电话  
             String cnum = "";  
             // 联系人id号码  
             String ID;  
             ID = personCur.getString(personCur  
                     .getColumnIndex(ContactsContract.Contacts._ID));  
             // 联系人姓名  
             cname = personCur.getString(personCur  
                     .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));  
             // id的整型数据  
             int id = Integer.parseInt(ID);
             if (id > 0) {  
                 // 获取指定id号码的电话号码  
                 Cursor c = resolver.query(  
                         ContactsContract.CommonDataKinds.Phone.CONTENT_URI,  
                         null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID  
                                 + "=" + ID, null, null);  
                 // 遍历游标  
                 while (c.moveToNext()) {  
                     cnum = c.getString(c  
                             .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
                 }  
                 // 将对象加入到集合中  
                 cInfor.setName(cname);  
                 cInfor.setPhone(cnum);  
                 contactList.add(cInfor);  

             }
         }
         return contactList;
        }


        public class ContactsInfo{
            public String name;
            public String email;
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            public String getEmail() {
                return email;
            }
            public void setEmail(String email) {
                this.email = email;
            }
            public String getPhone() {
                return phone;
            }
            public void setPhone(String phone) {
                this.phone = phone;
            }
            public String phone;
        }
    }  

意图开启一个Activity的几种方式

    public class IntentUtils {

        /**
         * 进入一个界面
         */
        public static void startActivityInfo(Activity context,Class<?>cls){
            Intent intent=new Intent(context,cls);
            context.startActivity(intent);
        }

        /**
         * 进入一个界面并结束自己
         */
        public static void startActivityAndFinish(Activity context,Class<?>cls){
            Intent intent=new Intent(context,cls);
            context.startActivity(intent);
            context.finish();
        }
        /**
         * 延迟进入进入一个界面
         * 
         */
        public static void startActivityDelay(final Activity context,final Class<?>cls,final long time){

            new Thread(){
                @Override
                public void run() {
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent=new Intent(context,cls);
                    context.startActivity(intent);
                }
            }.start();
        }

        /**
         * 延迟进入进入另一个界面并销毁这个界面
         * 
         */
        public static void startActivityDelayAndFinish(final Activity context,final Class<?>cls,final long time){

            new Thread(){
                @Override
                public void run() {
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent=new Intent(context,cls);
                    context.startActivity(intent);
                    context.finish();
                }
            }.start();
        }
    }

应用程序的Log的控制

    public class Logger {

        private static final int  VERBOSE=1;
        private static final int  DEBUG=2;
        private static final int  INFO=3;
        private static final int  WARN=4;
        private static final int  ERROR=5;
        private static  int  LOGLEVEL=4;

        public static void v(String tag,String msg){
            if(VERBOSE>LOGLEVEL){
                Log.v(tag, msg);
            }
        }
        public static void d(String tag,String msg){
            if(DEBUG>LOGLEVEL){
                Log.d(tag, msg);
            }
        }
        public static void i(String tag,String msg){
            if(INFO>LOGLEVEL){
                Log.i(tag, msg);
            }
        }
        public static void w(String tag,String msg){
            if(WARN>LOGLEVEL){
                Log.w(tag, msg);
            }
        }
        public static void e(String tag,String msg){
            if(ERROR>LOGLEVEL){
                Log.e(tag, msg);
            }
        }
    }

MD5加密一个字符串得到哈希值

    public class MD5Utils {
        /**
         * 采用md5加密算法,不可逆
         * @param text
         * @return
         */
        public static String encode(String text){

            try {
                MessageDigest digest=MessageDigest.getInstance("md5");

                byte[] result=digest.digest(text.getBytes());
                StringBuffer sb=new StringBuffer();
                for(byte b:result){
                    String hex=Integer.toHexString(b&0xff)+2;
                    if(hex.length()==1){
                        sb.append("0");
                    }
                    sb.append(hex);
                }
                return sb.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return "";
            }
        }
    }

获取手机进程的相关信息(进程的总数、内存可用,总空间)

        public class ProcessInfoUtils {
            /**
             * 获取系统进程的总数
             * @return
             */
            public static int getRunningProcessCount(Context context){
                /*
                 * 获取进程管理器
                 */
                ActivityManager am=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                //返回正在运行进程的集合
                List<RunningAppProcessInfo>infos= am.getRunningAppProcesses();
                return infos.size();

            }
            /**
             * 获取系统进程内存的可用空间
             * @return
             * @param context 上下文,获得可用内存
             */
            public static long getAvialRam(Context context){
                /*
                 * 获取进程管理器
                 */
                ActivityManager am=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                MemoryInfo outInfo=new MemoryInfo();
                am.getMemoryInfo(outInfo);
                return outInfo.availMem;

            }
    /**
     * 获取系统进程内存的总空间
     * @return
     * @param context 上下文,获得总空间
     */
    public static long getTotalRam(Context context){
        /*
         * 获取进程管理器
         */
        /*ActivityManager am=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo outInfo=new MemoryInfo();
        am.getMemoryInfo(outInfo);*/


        try {
            File file=new File("/proc/meminfo");
            FileInputStream fis=new FileInputStream(file);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis));
            String line=br.readLine();
            StringBuffer sb=new StringBuffer();
            for(char c :line.toCharArray()){
                if(c>='0' && c<='9'){
                    sb.append(c);
                }
            }
            //返回的是字节
            return Long.parseLong(sb.toString())*1024;
        } catch (Exception e) {
            e.printStackTrace();

            return 0;
        }
    }
}  

判断系统的服务是否在后台运行

public class ServicerUtils {
        /**
         * 判断系统的服务是否在后台运行
         */
        public static boolean isServiceRunning(Context context,String StringName){
            //获取进程和服务的管理器
            ActivityManager am=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningServiceInfo> infos=am.getRunningServices(1000);
            for(ActivityManager.RunningServiceInfo info:infos){
                    String className=info.service.getClassName();
                    //System.out.println(className);
                    if(StringName.equals(className)){
                        return true;
                    }
            }
            return false;
        }
    }

功能是把一个流对象转换成字符串对象解析成功则返回值为字符串,不成功则为null

    public class StreamUtils {
        public static String readStream(InputStream is){

            try {
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                byte []buffer=new byte[1024];
                int len=0;
                while((len=is.read(buffer))!=-1){
                    baos.write(buffer, 0, len);

                }
                is.close();
                return baos.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }    
        } 

    }

一个任意线程弹吐司的工具类

    public class ToastUtils {

      /*
        *可以在任意线程(包括主线程和子线程)中更新Ui     
         * @param activity 上下文
         * @param text 文本
         * 
         */
                public static void show(final Activity activity,final String text){
                    if("main".equals(Thread.currentThread().getName())){
                        Toast.makeText(activity, text, 0).show();
                    }else{
                        activity.runOnUiThread(new Runnable(){
                            public void run() {
                                Toast.makeText(activity, text, 0).show();
                            };
                        });    
                    }
                }

        /**

        * 可以在任意线程(包括主线程和子线程)中更新UI
         * 
         * @param activity 上下文
         * @param text 文本
         * @param len 时长
         */
            public static void show(final Activity activity,final String text,final int len){
                if("main".equals(Thread.currentThread().getName())){
                    Toast.makeText(activity, text, len).show();
                }else{
                    activity.runOnUiThread(new Runnable(){
                        public void run() {
                            Toast.makeText(activity, text, len).show();
                        };
                    });    
                }
            }
        }

拷贝资产目录下的数据库到Android系统下

    private void copyDB(final String name) {
        /*
         * 数据库多时可能耗时
         */
        new Thread(){
            public void run() {
                File file=new File(getFilesDir(),name);
                if(file.exists()&&file.length()>0){
                System.out.println("数据库已经加载过,无需在加载!");
                }else{

                try {
                    InputStream is=getAssets().open(name);
                    FileOutputStream fos=new FileOutputStream(file);
                    byte[] buffer=new byte[1024];
                    int len=-1;
                    while((len=is.read(buffer))!=-1){
                        fos.write(buffer, 0, len);
                    }
                    is.close();
                    fos.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                }
            };
        }.start();
    }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值