Toast 工具類:
SmartToastUtils.java
import android.content.Context; import android.widget.Toast; /** * Toast 彈出資訊工具類,簡化程式碼編寫 * @author fairy * */ public class SmartToastUtils { public static void showLong(Context context, String info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void showShort(Context context,String info) { Toast.makeText(context, info,Toast.LENGTH_SHORT).show(); } }
列印日誌工具類:
SmartLogUtils.java
import android.util.Log; public class SmartLogUtils { private final static String DEBUG_TAG="xingyun"; /*** * 封裝日誌列印方法 * @param message 列印的訊息 * @param showMessage 是否顯示列印的訊息 * **/ public static void showInfo(String message,Boolean showMessage){ if(showMessage){ int max_str_length = 2001 - DEBUG_TAG.length(); //大於4000時 while (message.length() > max_str_length) { Log.i(DEBUG_TAG, message.substring(0, max_str_length)); message = message.substring(max_str_length); } //剩餘部分 Log.i(DEBUG_TAG,message); } } /*** * 封裝日誌列印方法 * @param message 列印的訊息 * @param showMessage 是否顯示列印的訊息 * **/ public static void showDebug(String message,Boolean showMessage){ if(showMessage){ int max_str_length = 2001 - DEBUG_TAG.length(); //大於4000時 while (message.length() > max_str_length) { Log.d(DEBUG_TAG, message.substring(0, max_str_length)); message = message.substring(max_str_length); } //剩餘部分 Log.d(DEBUG_TAG,message); } } public static void showError(String message,Boolean showMessage){ if(showMessage){ int max_str_length = 2001 - DEBUG_TAG.length(); //大於4000時 while (message.length() > max_str_length) { Log.e(DEBUG_TAG, message.substring(0, max_str_length)); message = message.substring(max_str_length); } //剩餘部分 Log.e(DEBUG_TAG,message); } } }
Uri 轉BitMap工具類:
private Bitmap getBitmapFromUri(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; }
開啟系統內容提供器獲取所有圖片:
//開啟搜尋到的所有裝置圖片頁面 private static final int READ_REQUEST_CODE = 42; public void performFileSearch() { // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file // browser. Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); // Filter to only show results that can be "opened", such as a // file (as opposed to a list of contacts or timezones) intent.addCategory(Intent.CATEGORY_OPENABLE); // Filter to show only images, using the image MIME data type. // If one wanted to search for ogg vorbis files, the type would be "audio/ogg". // To search for all documents available via installed storage providers, // it would be "*/*". intent.setType("image/*"); startActivityForResult(intent, READ_REQUEST_CODE); }
@Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { // The ACTION_OPEN_DOCUMENT intent was sent with the request code // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the // response to some other intent, and the code below shouldn't run at all. if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). Uri uri = null; if (resultData != null) { uri = resultData.getData(); SmartToastUtils.showShort(MainActivity.this, "URI=" + uri.toString()); showURITextView.setText(uri.toString()); dumpImageMetaData(uri); try { saveBitMapToPhoneDevice(getBitmapFromUri(uri)); checkedPicFileImageView.setImageURI(uri); } catch (IOException e) { SmartToastUtils.showShort(MainActivity.this, "圖片解析失敗" + e.toString()); } } } } //將BitMap儲存到手機上 private void saveBitMapToPhoneDevice(Bitmap bitmap) { //將儲存到SDCard /xingyun_test_create 資料夾下 File appDir = new File(Environment.getExternalStorageDirectory(), "xingyun_test_create"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + "AAA.jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } SmartToastUtils.showShort(MainActivity.this,"save success"); }
Uri 解析圖片資訊
//解析URI 讀取圖片資訊 實際大小和實際名稱 public void dumpImageMetaData(Uri uri) { // The query, since it only applies to a single document, will only return // one row. There's no need to filter, sort, or select fields, since we want // all fields for one document. Cursor cursor = MainActivity.this.getContentResolver() .query(uri, null, null, null, null, null); try { // moveToFirst() returns false if the cursor has 0 rows. Very handy for // "if there's anything to look at, look at it" conditionals. if (cursor != null && cursor.moveToFirst()) { // Note it's called "Display Name". This is // provider-specific, and might not necessarily be the file name. String displayName = cursor.getString( cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); SmartToastUtils.showShort(MainActivity.this, "Display Name: " + displayName); int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE); // If the size is unknown, the value stored is null. But since an // int can't be null in Java, the behavior is implementation-specific, // which is just a fancy term for "unpredictable". So as // a rule, check if it's null before assigning to an int. This will // happen often: The storage API allows for remote files, whose // size might not be locally known. String size = null; if (!cursor.isNull(sizeIndex)) { // Technically the column stores an int, but cursor.getString() // will do the conversion automatically. size = cursor.getString(sizeIndex); } else { size = "Unknown"; } // Log.i(TAG, "Size: " + size); SmartToastUtils.showShort(MainActivity.this, "Size=" + size); } } finally { cursor.close(); } }
網路狀態監聽廣播類:
public final static String LISTENING_NETWORK_STATUS="android.net.conn.CONNECTIVITY_CHANGE";
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.xingyun.smartusbdeviceapp.util.SmartToastUtils; /******* * 網路狀態監聽改變需要這個許可權 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> * */ public class NetworkChangeReceiver 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 && networkInfo.isConnected()){ SmartToastUtils.showShort(context,"network is connected"); }else{ SmartToastUtils.showShort(context,"network is disconnected"); } //攔截掉廣播 //abortBroadcast(); } }
檔案工具類:
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; /** * Created by apple on 2018/7/13. */ public class FileUtils { /** * 把位元組陣列儲存為一個檔案 * @param */ public static File bytes2File(byte[] b, String outputFile) { BufferedOutputStream stream = null; File file = null; try { file = new File(outputFile); if(!file.getParentFile().exists()){ boolean mkdirs = file.getParentFile().mkdirs(); } boolean newFile = file.createNewFile(); FileOutputStream fstream = new FileOutputStream(file); stream = new BufferedOutputStream(fstream); stream.write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; } // 用於遍歷sdcard卡上所有檔案的類 public static void DirAll(File dirFile) throws Exception { // 用於存放sdcard卡上的所有圖片路徑 ArrayList<String> dirAllStrArr = new ArrayList<String>(); if (dirFile.exists()) { File files[] = dirFile.listFiles(); for (File file : files) { if (file.isDirectory()) { String fileName = file.getName(); // 除sdcard上Android這個資料夾以外。 if (!fileName.endsWith("Android")) { // 如果遇到資料夾則遞迴呼叫。 DirAll(file); } } else { // 如果是圖片檔案壓入陣列 String fileName = file.getName(); if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".bmp") || fileName.endsWith(".gif") || fileName.endsWith(".png")) { // 如果遇到檔案則放入陣列 if (dirFile.getPath().endsWith(File.separator)) { dirAllStrArr .add(dirFile.getPath() + file.getName()); } else { dirAllStrArr.add(dirFile.getPath() + File.separator + file.getName()); } } } } } } }
public class NetworkReceiverConstant {
public final static String LISTENING_NETWORK_STATUS="android.net.conn.CONNECTIVITY_CHANGE";
}