android实用代码片段(二)

来源:互联网 发布:css 实战手册 知乎 编辑:程序博客网 时间:2024/06/05 05:22

android实用代码片段(二)

参考于: [代码片段] Android实用代码片段整合

多进程Preferences数据共享

  • SharedPreference: Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.
  • 用来获取与修改偏好数据的借口,所有的用户共享一个SharedPreference的实例。修改操作必须通过Editor进行以保证在提交时偏好值连续且在控制中。从get方法中返回的SharedPreference对象不能被改变
  • SharedPreferences.Editor: Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
  • 用来修改存储在SharedPreferece中得值。所有在editor的修改被暂时缓存,直到调用commit或apply才被存储到原先的SharedPreference对象中
public static void putStringProcess(Context ctx, String key, String value) {        SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);        Editor editor = sharedPreferences.edit();        editor.putString(key, value);        editor.commit();}    public static String getStringProcess(Context ctx, String key, String defValue) {        SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);        return sharedPreferences.getString(key, defValue);}

泛型ArrayList转数组

  • Array: Provides static methods to create and access arrays dynamically.
  • 提供动态创建与获取数组的静态方法
@SuppressWarnings("unchecked")    public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {        if (items == null || items.size() == 0) {            return (T[]) Array.newInstance(cls, 0);        }        return items.toArray((T[]) Array.newInstance(cls, items.size()));    }

保存恢复ListView当前位置

private void saveCurrentPosition() {        if (mListView != null) {        int position = mListView.getFirstVisiblePosition();        View v = mListView.getChildAt(0);        int top = (v == null) ? 0 : v.getTop();        //保存position和top    }}private void restorePosition() {    if (mFolder != null && mListView != null) {       int position = 0;//取出保存的数据       int top = 0;//取出保存的数据       mListView.setSelectionFromTop(position, top);   }}

调用 便携式热点和数据共享 设置

  • ComponentName: Identifier for a specific application component (Activity, Service, BroadcastReceiver, or ContentProvider) that is available. Two pieces of information, encapsulated here, are required to identify a component: the package (a String) it exists in, and the class (a String) name inside of that package.
  • 可用应用组件的标识符。包装了两种用于识别组件的信息:组件存在的包与它在这个包中的类名
public static Intent getHotspotSetting() {        Intent intent = new Intent();        intent.setAction(Intent.ACTION_MAIN);        ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");        intent.setComponent(com);        return intent;}

格式化输出IP地址

  • Formatter: Utility class to aid in formatting common values that are not covered by the Formatter class in java.util
  • 用于格式化java.util中Formatter不涉及范围的工具类
public static String getIp(Context ctx) {        return Formatter.formatIpAddress((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE).getConnectionInfo().getIpAddress());}

文件夹排序(先文件夹排序,后文件排序)

  • A Comparator is used to compare two objects to determine their ordering with respect to each other. On a given Collection, a Comparator can be used to obtain a sorted Collection which is totally ordered. For a Comparator to be consistent with equals, its {code #compare(Object, Object)} method has to return zero for each pair of elements (a,b) where a.equals(b) holds true. It is recommended that a Comparator implements Serializable.
public static void sortFiles(File[] files) {        Arrays.sort(files, new Comparator<File>() {            @Override            public int compare(File lhs, File rhs) {                //返回负数表示o1 小于o2,返回0 表示o1和o2相等,返回正数表示o1大于o2。                 boolean l1 = lhs.isDirectory();                boolean l2 = rhs.isDirectory();                if (l1 && !l2)                    return -1;                else if (!l1 && l2)                    return 1;                else {                    return lhs.getName().compareTo(rhs.getName());                }            }        });    }

发送不重复的通知(Notification)

  • Notification: A class that represents how a persistent notification is to be presented to the user using the NotificationManager. The Notification.Builder has been added to make it easier to construct Notifications.
  • 使用NotificationManager展示给用户的类。Builder使建立Notification更加容易。
  • Notification.Builder: Builder class for Notification objects. Provides a convenient way to set the various fields of a Notification and generate content views using the platform’s notification layout template.
  • Notification的建造类。提供设定Notification值与产生使徒模板的简单方法。
public static void sendNotification(Context context, String title,            String message, Bundle extras) {        Intent mIntent = new Intent(context, FragmentTabsActivity.class);        mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);        mIntent.putExtras(extras);        int requestCode = (int) System.currentTimeMillis();        PendingIntent mContentIntent = PendingIntent.getActivity(context,                requestCode, mIntent, 0);        Notification mNotification = new NotificationCompat.Builder(context)                .setContentTitle(title).setSmallIcon(R.drawable.app_icon)                .setContentIntent(mContentIntent).setContentText(message)                .build();        mNotification.flags |= Notification.FLAG_AUTO_CANCEL;        mNotification.defaults = Notification.DEFAULT_ALL;        NotificationManager mNotificationManager = (NotificationManager) context                .getSystemService(Context.NOTIFICATION_SERVICE);        mNotificationManager.notify(requestCode, mNotification);}

代码设置TextView的样式

  • A ContextWrapper that allows you to modify the theme from what is in the wrapped context.
  • ContextWrapper 允许修改被包裹的context的主题
 TextView textView = new TextView(new ContextThemeWrapper(this, R.style.text_style));

ip地址转成8位十六进制串

  • StringTokenizer: Breaks a string into tokens; new code should probably use split(String).
  • 将字符串分解成块,进一步分解可能会用到split方法
 /** ip转16进制 */    public static String ipToHex(String ips) {        StringBuffer result = new StringBuffer();        if (ips != null) {            StringTokenizer st = new StringTokenizer(ips, ".");            while (st.hasMoreTokens()) {                String token = Integer.toHexString(Integer.parseInt(st.nextToken()));                if (token.length() == 1)                    token = "0" + token;                result.append(token);            }        }        return result.toString();}    /** 16进制转ip */    public static String texToIp(String ips) {        try {            StringBuffer result = new StringBuffer();            if (ips != null && ips.length() == 8) {                for (int i = 0; i < 8; i += 2) {                    if (i != 0)                        result.append('.');                    result.append(Integer.parseInt(ips.substring(i, i + 2), 16));                }            }            return result.toString();        } catch (NumberFormatException ex) {            Logger.e(ex);        }        return "";}

获取网络类型名称

 public static String getNetworkTypeName(Context context) {        if (context != null) {            ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            if (connectMgr != null) {                NetworkInfo info = connectMgr.getActiveNetworkInfo();                if (info != null) {                    switch (info.getType()) {                    case ConnectivityManager.TYPE_WIFI:                        return "WIFI";                    case ConnectivityManager.TYPE_MOBILE:                        return getNetworkTypeName(info.getSubtype());                    }                }            }        }        return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN);}    public static String getNetworkTypeName(int type) {        switch (type) {        case TelephonyManager.NETWORK_TYPE_GPRS:            return "GPRS";        case TelephonyManager.NETWORK_TYPE_EDGE:            return "EDGE";        case TelephonyManager.NETWORK_TYPE_UMTS:            return "UMTS";        case TelephonyManager.NETWORK_TYPE_HSDPA:            return "HSDPA";        case TelephonyManager.NETWORK_TYPE_HSUPA:            return "HSUPA";        case TelephonyManager.NETWORK_TYPE_HSPA:            return "HSPA";        case TelephonyManager.NETWORK_TYPE_CDMA:            return "CDMA";        case TelephonyManager.NETWORK_TYPE_EVDO_0:            return "CDMA - EvDo rev. 0";        case TelephonyManager.NETWORK_TYPE_EVDO_A:            return "CDMA - EvDo rev. A";        case TelephonyManager.NETWORK_TYPE_EVDO_B:            return "CDMA - EvDo rev. B";        case TelephonyManager.NETWORK_TYPE_1xRTT:            return "CDMA - 1xRTT";        case TelephonyManager.NETWORK_TYPE_LTE:            return "LTE";        case TelephonyManager.NETWORK_TYPE_EHRPD:            return "CDMA - eHRPD";        case TelephonyManager.NETWORK_TYPE_IDEN:            return "iDEN";        case TelephonyManager.NETWORK_TYPE_HSPAP:            return "HSPA+";        default:            return "UNKNOWN";        }}

Android解压Zip包

/**     * 解压一个压缩文档 到指定位置     *      * @param zipFileString 压缩包的名字     * @param outPathString 指定的路径     * [url=home.php?mod=space&uid=2643633]@throws[/url] Exception     */    public static void UnZipFolder(String zipFileString, String outPathString) throws Exception {        java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString));        java.util.zip.ZipEntry zipEntry;        String szName = "";        while ((zipEntry = inZip.getNextEntry()) != null) {            szName = zipEntry.getName();            if (zipEntry.isDirectory()) {                // get the folder name of the widget                szName = szName.substring(0, szName.length() - 1);                java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);                folder.mkdirs();            } else {                java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);                file.createNewFile();                // get the output stream of the file                java.io.FileOutputStream out = new java.io.FileOutputStream(file);                int len;                byte[] buffer = new byte[1024];                // read (len) bytes into buffer                while ((len = inZip.read(buffer)) != -1) {                    // write (len) byte from buffer at the position 0                    out.write(buffer, 0, len);                    out.flush();                }                out.close();            }        }//end of while        inZip.close();    }//end of func

从assets中读取文本和图片资源

  • AssetManager: Provides access to an application’s raw asset files; see Resources for the way most applications will want to retrieve their resource data. This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.
  • 提供获取asset文件数据流的方法。这个类从低API中就已存在,允许你打开和读取绑定在运用程序的文件。
  • Resources: Class for accessing an application’s resources. This sits on top of the asset manager of the application (accessible through getAssets()) and provides a high-level API for getting typed data from the assets.
  • 获取应用资源的类。这个类在AssetManager管理的文件等级之上,提供了高水平API来获取assets中得文件流。
 /** 从assets 文件夹中读取文本数据 */    public static String getTextFromAssets(final Context context, String fileName) {        String result = "";        try {            InputStream in = context.getResources().getAssets().open(fileName);            // 获取文件的字节数            int lenght = in.available();            // 创建byte数组            byte[] buffer = new byte[lenght];            // 将文件中的数据读到byte数组中            in.read(buffer);            result = EncodingUtils.getString(buffer, "UTF-8");            in.close();        } catch (Exception e) {            e.printStackTrace();        }        return result;}    /** 从assets 文件夹中读取图片 */    public static Drawable loadImageFromAsserts(final Context ctx, String fileName) {        try {            InputStream is = ctx.getResources().getAssets().open(fileName);            return Drawable.createFromStream(is, null);        } catch (IOException e) {            if (e != null) {                e.printStackTrace();            }        } catch (OutOfMemoryError e) {            if (e != null) {                e.printStackTrace();            }        } catch (Exception e) {            if (e != null) {                e.printStackTrace();            }        }        return null;}

展开、收起状态栏

public static final void collapseStatusBar(Context ctx) {        Object sbservice = ctx.getSystemService("statusbar");        try {            Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");            Method collapse;            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {                collapse = statusBarManager.getMethod("collapsePanels");            } else {                collapse = statusBarManager.getMethod("collapse");            }            collapse.invoke(sbservice);        } catch (Exception e) {            e.printStackTrace();        }}    public static final void expandStatusBar(Context ctx) {        Object sbservice = ctx.getSystemService("statusbar");        try {            Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");            Method expand;            if (Build.VERSION.SDK_INT >= 17) {                expand = statusBarManager.getMethod("expandNotificationsPanel");            } else {                expand = statusBarManager.getMethod("expand");            }            expand.invoke(sbservice);        } catch (Exception e) {            e.printStackTrace();        }}

获取状态栏高度

public static int getStatusBarHeight(Context context){        Class<?> c = null;        Object obj = null;        Field field = null;        int x = 0, 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);        } catch (Exception e1) {            e1.printStackTrace();        }        return statusBarHeight;}
0 0
原创粉丝点击