Android开发

Android常用工具类

2016-08-25  本文已影响303人  e3bdbe34140d

Android常用工具的封装
一、获取软件相关工具类public class AppInfoUtils { private AppInfoUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be in ...
一、获取软件相关工具类

public class AppInfoUtils {

        private AppInfoUtils() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");

        }

        /**
         * 获取应用程序名称
         * 
         * @param context
         * @return
         */
        public static String getAppName(Context context) {
                try {
                        PackageManager packageManager = context.getPackageManager();
                        PackageInfo packageInfo = packageManager.getPackageInfo(
                                        context.getPackageName(), 0);
                        int labelRes = packageInfo.applicationInfo.labelRes;
                        return context.getResources().getString(labelRes);
                } catch (NameNotFoundException e) {
                        e.printStackTrace();
                }
                return null;
        }

        /**
         * 获取应用程序版本名称信息
         * 
         * @param context
         * [url=home.php?mod=space&uid=309376]@return[/url] 当前应用的版本名称
         */
        public static String getVersionName(Context context) {
                try {
                        PackageManager packageManager = context.getPackageManager();
                        PackageInfo packageInfo = packageManager.getPackageInfo(
                                        context.getPackageName(), 0);
                        return packageInfo.versionName;

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

        /**
         * 获取application节点下的meta信息
         * 
         * @param context
         * @param params
         *            想要获取的参数
         * @return
         */
        public static String getMetaInfo(Context context, String params) {

                String packageName = context.getPackageName();
                // 获取application里面的meta信息
                try {
                        ApplicationInfo appInfo = context.getPackageManager()
                                        .getApplicationInfo(packageName,
                                                        PackageManager.GET_META_DATA);
                        return appInfo.metaData.getString(params);
                } catch (Exception e) {
                        System.out.println("获取渠道失败:" + e);
                        e.printStackTrace();
                }
                return null;
        }

        /**
         * 获取启动Activity的intent
         * 
         * @param context
         * @return
         */
        public static Intent getLaunchIntent(Context context) {
                String packageName = context.getPackageName();
                PackageManager pm = context.getPackageManager();
                Intent intent = pm.getLaunchIntentForPackage(packageName);
                return intent;
        }
}

二、向服务器提交请求的工具

public class HttpRequest {

        public static void httpGetRequest(final String urlPath) {
                new Thread() {
                        @Override
                        public void run() {
                                super.run();
                                try {
                                        URL url = new URL(urlPath);
                                        HttpURLConnection conn = (HttpURLConnection) url
                                                        .openConnection();
                                        conn.setRequestMethod("GET");
                                        conn.setConnectTimeout(5000);

                                        BufferedReader bufr = new BufferedReader(
                                                        new InputStreamReader(conn.getInputStream()));
                                        String line = null;
                                        while ((line = bufr.readLine()) != null) {
                                                System.out.println(line);
                                        }
                                        bufr.close();

                                } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }.start();
        }

        public static void httpPostRequest(final String urlPath) {
                new Thread() {
                        @Override
                        public void run() {
                                super.run();
                                try {
                                        URL url = new URL(urlPath);
                                        HttpURLConnection conn = (HttpURLConnection) url
                                                        .openConnection();
                                        conn.setRequestMethod("POST");
                                        conn.setConnectTimeout(5000);

                                        conn.setDoInput(true);
                                        conn.setDoOutput(true);
                                        conn.setUseCaches(false);

                                        BufferedReader bufr = new BufferedReader(
                                                        new InputStreamReader(conn.getInputStream()));
                                        String line = null;
                                        while ((line = bufr.readLine()) != null) {
                                                System.out.println(line);
                                        }
                                        bufr.close();

                                } catch (MalformedURLException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }.start();
        }

        public static void httpGetClient(final String urlPath) {

                new Thread() {
                        @Override
                        public void run() {
                                super.run();
                                HttpClient client = new DefaultHttpClient();
                                HttpGet request = new HttpGet(urlPath);
                                try {
                                        HttpResponse response = client.execute(request);
                                        InputStream is = response.getEntity().getContent();
                                        BufferedReader bufr = new BufferedReader(
                                                        new InputStreamReader(is));
                                        String line = null;
                                        while ((line = bufr.readLine()) != null) {
                                                System.out.println(line);
                                        }
                                        bufr.close();
                                } catch (ClientProtocolException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }.start();

        }

        public static void statichttpPostClient(String url) {
                new Thread() {
                        @Override
                        public void run() {
                                super.run();
                                HttpClient client = new DefaultHttpClient();
                                HttpPost request = new HttpPost();

                                List<NameValuePair> params = new ArrayList<NameValuePair>();
                                // 建立一个NameValuePair数组,用于存储欲传送的参数
                                params.add(new BasicNameValuePair("userName", "oppoe"));
                                params.add(new BasicNameValuePair("password", "123"));
                                try {
                                        request.setEntity(new UrlEncodedFormEntity(params,
                                                        HTTP.UTF_8));
                                        HttpResponse response = client.execute(request);
                                        InputStream is = response.getEntity().getContent();
                                        BufferedReader bufr = new BufferedReader(
                                                        new InputStreamReader(is));
                                        String line = null;
                                        while ((line = bufr.readLine()) != null) {
                                                System.out.println(line);
                                        }
                                        bufr.close();
                                } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                } catch (IllegalStateException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }.start();
        }
}

三、打开或关闭软键盘

public class KeyBoardUtils {
        /**
         * 打卡软键盘
         * 
         * @param mEditText
         *            输入框
         * @param mContext
         *            上下文
         */
        public static void openKeybord(EditText mEditText, Context mContext) {
                InputMethodManager imm = (InputMethodManager) mContext
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                                InputMethodManager.HIDE_IMPLICIT_ONLY);
        }

        /**
         * 关闭软键盘
         * 
         * @param mEditText
         *            输入框
         * @param mContext
         *            上下文
         */
        public static void closeKeybord(EditText mEditText, Context mContext) {
                InputMethodManager imm = (InputMethodManager) mContext
                                .getSystemService(Context.INPUT_METHOD_SERVICE);

                imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
        }
}

四、跟网络相关的工具类

public class NetworkUtils {
        private NetworkUtils() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");
        }

        /**
         * 判断网络是否连接
         * 
         * @param context
         * @return
         */
        public static boolean isConnected(Context context) {

                ConnectivityManager connectivity = (ConnectivityManager) context
                                .getSystemService(Context.CONNECTIVITY_SERVICE);

                if (null != connectivity) {

                        NetworkInfo info = connectivity.getActiveNetworkInfo();
                        if (null != info && info.isConnected()) {
                                if (info.getState() == NetworkInfo.State.CONNECTED) {
                                        return true;
                                }
                        }
                }
                return false;
        }

        /**
         * 判断是否是wifi连接
         */
        public static boolean isWifi(Context context) {
                ConnectivityManager cm = (ConnectivityManager) context
                                .getSystemService(Context.CONNECTIVITY_SERVICE);

                if (cm == null)
                        return false;
                return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

        }

        /**
         * 打开网络设置界面
         */
        public static void openSetting(Activity activity) {
                Intent intent = new Intent("/");
                ComponentName cm = new ComponentName("com.android.settings",
                                "com.android.settings.WirelessSettings");
                intent.setComponent(cm);
                intent.setAction("android.intent.action.VIEW");
                activity.startActivityForResult(intent, 0);
        }

}

五、获取手机信

public class PhoneInfoUtils {

        private Context context;

        private String deviceId;
        private String imei;
        private String imsi;
        private String manufacture;
        private String model;
        private int screenWidth;
        private int screenHeight;
        private String version_release;
        private String phoneNumber;

        public PhoneInfoUtils(Context context) {
                this.context = context;
        }

        public void getPhoneInfo() {
                TelephonyManager tm = (TelephonyManager) context
                                .getSystemService(Context.TELEPHONY_SERVICE);

                deviceId = Settings.Secure.getString(context.getContentResolver(),
                                Settings.Secure.ANDROID_ID);
                imsi = tm.getSubscriberId();
                imei = tm.getDeviceId();

                // 手机制造商
                manufacture = Build.MANUFACTURER;

                model = Build.MODEL; // 手机型号

                DisplayMetrics dm = context.getResources().getDisplayMetrics();
                screenWidth = dm.widthPixels;
                screenHeight = dm.heightPixels;

                version_release = Build.VERSION.RELEASE; // 系统版本号

                phoneNumber = tm.getLine1Number(); // 获取手机号码
        }

        @Override
        public String toString() {
                return "PhoneInfoUtils [deviceId=" + deviceId + ", imei=" + imei
                                + ", imsi=" + imsi + ", manufacture=" + manufacture
                                + ", model=" + model + ", screenWidth=" + screenWidth
                                + ", screenHeight=" + screenHeight + ", version_release="
                                + version_release + ", phoneNumber=" + phoneNumber + "]";
        }

}

六、获得屏幕相关的辅助类

public class ScreenUtils {
        private ScreenUtils() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");
        }

        /**
         * 获得屏幕高度
         * 
         * @param context
         * @return
         */
        public static int getScreenWidth(Context context) {
                WindowManager wm = (WindowManager) context
                                .getSystemService(Context.WINDOW_SERVICE);
                DisplayMetrics outMetrics = new DisplayMetrics();
                wm.getDefaultDisplay().getMetrics(outMetrics);
                return outMetrics.widthPixels;
        }

        /**
         * 获得屏幕宽度
         * 
         * @param context
         * @return
         */
        public static int getScreenHeight(Context context) {
                WindowManager wm = (WindowManager) context
                                .getSystemService(Context.WINDOW_SERVICE);
                DisplayMetrics outMetrics = new DisplayMetrics();
                wm.getDefaultDisplay().getMetrics(outMetrics);
                return outMetrics.heightPixels;
        }

        /**
         * 获得状态栏的高度
         * 
         * @param context
         * @return
         */
        public static int getStatusHeight(Context context) {

                int statusHeight = -1;
                try {
                        Class<?> clazz = Class.forName("com.android.internal.R$dimen");
                        Object object = clazz.newInstance();
                        int height = Integer.parseInt(clazz.getField("status_bar_height")
                                        .get(object).toString());
                        statusHeight = context.getResources().getDimensionPixelSize(height);
                } catch (Exception e) {
                        e.printStackTrace();
                }
                return statusHeight;
        }

        /**
         * 获取当前屏幕截图,包含状态栏
         * 
         * @param activity
         * @return
         */
        public static Bitmap snapShotWithStatusBar(Activity activity) {
                View view = activity.getWindow().getDecorView();
                view.setDrawingCacheEnabled(true);
                view.buildDrawingCache();
                Bitmap bmp = view.getDrawingCache();
                int width = getScreenWidth(activity);
                int height = getScreenHeight(activity);
                Bitmap bp = null;
                bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
                view.destroyDrawingCache();
                return bp;

        }

        /**
         * 获取当前屏幕截图,不包含状态栏
         * 
         * @param activity
         * @return
         */
        public static Bitmap snapShotWithoutStatusBar(Activity activity) {
                View view = activity.getWindow().getDecorView();
                view.setDrawingCacheEnabled(true);
                view.buildDrawingCache();
                Bitmap bmp = view.getDrawingCache();
                Rect frame = new Rect();
                activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                int statusBarHeight = frame.top;

                int width = getScreenWidth(activity);
                int height = getScreenHeight(activity);
                Bitmap bp = null;
                bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
                                - statusBarHeight);
                view.destroyDrawingCache();
                return bp;

        }

}

七、快速数据存储工具

public class SharedPerUtils {
        public SharedPerUtils() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");
        }

        /**
         * 保存在手机里面的文件名
         */
        public static final String FILE_NAME = "share_data";

        /**
         * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
         * 
         * @param context
         * @param key
         * @param object
         */
        public static void put(Context context, String key, Object object) {

                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();

                if (object instanceof String) {
                        editor.putString(key, (String) object);
                } else if (object instanceof Integer) {
                        editor.putInt(key, (Integer) object);
                } else if (object instanceof Boolean) {
                        editor.putBoolean(key, (Boolean) object);
                } else if (object instanceof Float) {
                        editor.putFloat(key, (Float) object);
                } else if (object instanceof Long) {
                        editor.putLong(key, (Long) object);
                } else {
                        editor.putString(key, object.toString());
                }

                SharedPreferencesCompat.apply(editor);
        }

        /**
         * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
         * 
         * @param context
         * @param key
         * @param defaultObject
         * @return
         */
        public static Object get(Context context, String key, Object defaultObject) {
                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);

                if (defaultObject instanceof String) {
                        return sp.getString(key, (String) defaultObject);
                } else if (defaultObject instanceof Integer) {
                        return sp.getInt(key, (Integer) defaultObject);
                } else if (defaultObject instanceof Boolean) {
                        return sp.getBoolean(key, (Boolean) defaultObject);
                } else if (defaultObject instanceof Float) {
                        return sp.getFloat(key, (Float) defaultObject);
                } else if (defaultObject instanceof Long) {
                        return sp.getLong(key, (Long) defaultObject);
                }

                return null;
        }

        /**
         * 移除某个key值已经对应的值
         * 
         * @param context
         * @param key
         */
        public static void remove(Context context, String key) {
                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.remove(key);
                SharedPreferencesCompat.apply(editor);
        }

        /**
         * 清除所有数据
         * 
         * @param context
         */
        public static void clear(Context context) {
                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear();
                SharedPreferencesCompat.apply(editor);
        }

        /**
         * 查询某个key是否已经存在
         * 
         * @param context
         * @param key
         * @return
         */
        public static boolean contains(Context context, String key) {
                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);
                return sp.contains(key);
        }

        /**
         * 返回所有的键值对
         * 
         * @param context
         * @return
         */
        public static Map<String, ?> getAll(Context context) {
                SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                                Context.MODE_PRIVATE);
                return sp.getAll();
        }

        /**
         * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
         * 
         * @author zhy
         * 
         */
        private static class SharedPreferencesCompat {
                private static final Method sApplyMethod = findApplyMethod();

                /**
                 * 反射查找apply的方法
                 * 
                 * @return
                 */
                @SuppressWarnings({ "unchecked", "rawtypes" })
                private static Method findApplyMethod() {
                        try {
                                Class clz = SharedPreferences.Editor.class;
                                return clz.getMethod("apply");
                        } catch (NoSuchMethodException e) {
                        }

                        return null;
                }

                /**
                 * 如果找到则使用apply执行,否则使用commit
                 * 
                 * @param editor
                 */
                public static void apply(SharedPreferences.Editor editor) {
                        try {
                                if (sApplyMethod != null) {
                                        sApplyMethod.invoke(editor);
                                        return;
                                }
                        } catch (IllegalArgumentException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                        editor.commit();
                }
        }

}

八、私钥解码工具类

public class EncodeUtils {

        private final static String KEY = "123456789"; // 公钥(只能是数字)
        private final static int MODE = 17; // 模数(整数)

        // 私钥加密
        @SuppressWarnings("unused")
        private static String encode(String password) {
                if (password != null && !password.trim().equals("")) {
                        BigInteger bi_value = new BigInteger(password.getBytes());
                        BigInteger bi_r0 = new BigInteger(KEY);
                        BigInteger bi_r1 = bi_r0.xor(bi_value);
                        return bi_r1.toString(MODE);
                }
                return password;
        }

        // 私钥解密
        public static String decode(String decodeString) {
                BigInteger bi_confuse = new BigInteger(KEY);
                BigInteger bi_r1 = new BigInteger(decodeString, MODE);
                BigInteger bi_r0 = bi_r1.xor(bi_confuse);
                return new String(bi_r0.toByteArray());
        }
}

九、Toast统一管理类

public class MyToast {

        private MyToast() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");
        }

        public static boolean isShow = true;

        /**
         * 短时间显示Toast
         * 
         * @param context
         * @param message
         */
        public static void showShort(Context context, CharSequence message) {
                if (isShow)
                        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

        /**
         * 短时间显示Toast
         * 
         * @param context
         * @param message
         */
        public static void showShort(Context context, int message) {
                if (isShow)
                        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

        /**
         * 长时间显示Toast
         * 
         * @param context
         * @param message
         */
        public static void showLong(Context context, CharSequence message) {
                if (isShow)
                        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }

        /**
         * 长时间显示Toast
         * 
         * @param context
         * @param message
         */
        public static void showLong(Context context, int message) {
                if (isShow)
                        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }

        /**
         * 自定义显示Toast时间
         * 
         * @param context
         * @param message
         * @param duration
         */
        public static void show(Context context, CharSequence message, int duration) {
                if (isShow)
                        Toast.makeText(context, message, duration).show();
        }

        /**
         * 自定义显示Toast时间
         * 
         * @param context
         * @param message
         * @param duration
         */
        public static void show(Context context, int message, int duration) {
                if (isShow)
                        Toast.makeText(context, message, duration).show();
        }

}

十、Log统一管理类

public class MyLog {

        private MyLog() {
                /* cannot be instantiated */
                throw new UnsupportedOperationException("cannot be instantiated");
        }

        public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化

        // 下面是传入自定义tag的函数
        public static void i(String tag, String msg) {
                if (isDebug)
                        Log.i(tag, msg);
        }

        public static void d(String tag, String msg) {
                if (isDebug)
                        Log.d(tag, msg);
        }

        public static void e(String tag, String msg) {
                if (isDebug)
                        Log.e(tag, msg);
        }

        public static void v(String tag, String msg) {
                if (isDebug)
                        Log.v(tag, msg);
        }
}
上一篇 下一篇

猜你喜欢

热点阅读