Android項目開發常用的簡單工具類

一:介紹

     這篇博客主要內容是我在項目開發過程中常用的簡單的工具類,包括檢查網絡工具類,Bitmap處理工具類,Toast工具類等,在這裏分享給大家,多謝支持!

二:工具類

1.檢查網絡工具類

(1)檢查網絡是否連接

public class CheckNetUtils {
    /**
     * 檢查手機網絡連接狀況
     *
     * @param context 上下文
     * @return true 網絡正常 false 網絡異常
     */
    public static boolean testNetWork(Context context) {
        // 用上下文得到系統的連接管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // 用連接管理器得到手機當前網絡信息
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        // 當網絡信息不爲空且爲連接狀態時,返回true
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 打開網絡設置界面
     */
    public static void openSetting(Context context) {
        if (android.os.Build.VERSION.SDK_INT > 10) {
            //3.0以上打開設置界面,也可以直接用ACTION_WIRELESS_SETTINGS打開到wifi界面
            context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
        } else {
            context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
        }
    }
}


(1)監聽手機當前網絡是何種網絡,是一個廣播

public class NetworkBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            ToastUtils.showToast(context, "網絡異常");
        } else {
            if (networkInfo.isConnected()) {
                ToastUtil.showToast(context, "網絡正常", Toast.LENGTH_SHORT);
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    ToastUtils.showToast(context, "WIFI網絡連接");             
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    ToastUtils.showToast(context, "移動網絡連接");            
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    ToastUtils.showToast(context, "有線網絡連接");                
                }
            }
        }
    }
}
需要在清單文件裏面註冊此廣播

<!-- 監聽網絡的廣播 -->
        <receiver android:name=".broadcast.NetworkBroadcast">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

2.Bitmap工具類

public class BitmapUtils {
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    // 如果是放大圖片,filter決定是否平滑,如果是縮小圖片,filter無影響
    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight) {
        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);
        if (src != dst) { // 如果沒有縮放,那麼不回收
            src.recycle(); // 釋放Bitmap的native像素數組
        }
        return dst;
    }

    // 從Resources中加載圖片
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options); // 讀取圖片長寬
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 計算inSampleSize
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeResource(res, resId, options); // 載入一個稍大的縮略圖
        return createScaleBitmap(src, reqWidth, reqHeight); // 進一步得到目標大小的縮略圖
    }

    // 從sd卡上加載圖片
    public static Bitmap decodeSampledBitmapFromSd(String pathName, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(pathName, options);
        return createScaleBitmap(src, reqWidth, reqHeight);
    }
}

在這裏貼一下Bitmap加載縮略圖代碼片段,這個縮略圖是按比例壓縮,從而保持圖片的寬高比,效果就是圖片不變形


//加載縮略圖,參數p是圖片路徑
Bitmap bitmap = BitmapFactory.decodeFile(p);
Matrix matrix = new Matrix();
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int t = w > h ? w : h;
float bi = 500.f / t;
matrix.postScale(bi, bi); //長和寬放大縮小的比例
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

3.Toast工具類

(1).Toast全部自定義

public class ToastUtils {
    private static Toast mToast;

    /**
     * 顯示吐司
     *
     * @param context 上下文
     * @param text    吐司文本
     */
    public static void showToast(Context context, String text) {
        //Toast要加載的view
        View view = view = View.inflate(context, R.layout.toast, null);
        TextView txt = ((TextView) view.findViewById(R.id.txt_toast));
        if (mToast == null) {
            //自定義Toast
            mToast = new Toast(context);
            txt.setText(text);
            //給Toast設置佈局
            mToast.setView(view);
            mToast.setDuration(Toast.LENGTH_SHORT);
            //Toast在屏幕中間顯示
            mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            txt.setText(text);
            mToast.setView(view);
        }
        mToast.show();
    }
}

下面是佈局文件,只有一個TextView,可以自定義shape

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/shape_txt_toast"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="10dp"
        android:text="吐司"
        android:textColor="@color/bleak"
        android:textSize="16sp"
        android:textStyle="bold" />

</LinearLayout>

(2).簡單的Toast封裝,可以避免多次點擊重複出現Toast

public class ToastUtils {

    private static Toast mToast = null;

    /**
     * 顯示Toast
     *
     * @param context 上下文
     * @param text    Toast文本
     */
    public static void showToast(Context context, String text) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }
}


3.SharedPreferences共享偏好工具類

共享偏好的名稱都定義在工具類中,然後定義一個拿到共享偏好的方法,方便統一管理

package com.zidiv.medicine.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 共享偏好工具類
 * Created by Administrator on 2016/2/29.
 */
public class SPUtils {
    //是否是第一次打開的共享偏好名稱
    public static final String FIRSTSP = "firstSP";
    //是否檢查網絡
    public static final String NETSP = "netSP";
    //是否啓用緩存
    public static final String CACHESP = "cacheSP";


    /**
     * 得到一個共享偏好
     *
     * @param context 上下文
     * @param spName  共享偏好名稱
     * @return
     */
    public static SharedPreferences getSP(Context context, String spName) {
        SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        return sp;
    }
}<strong>
</strong>
然後這樣使用就可以了

sp = SPUtils.getSP(context, SPUtils.FIRSTSP);


先和大家分享到這,這篇博客會一直更新,加入和完善工具類.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章