星云 Android 开发工具箱
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";
}
*********************
交流即分享,分享才能进步!
不对之处,还请各位前辈多多指教。
by 星云
********************