repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/CoordinateUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/CoordinateUtils.java
package com.blankj.subutil.util; import static java.lang.Math.PI; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/03/21 * desc : 坐标相关工具类 * </pre> */ public final class CoordinateUtils { private final static double X_PI = 3.14159265358979324 * 3000.0 / 180.0; private final static double A = 6378245.0; private final static double EE = 0.00669342162296594323; /** * BD09 坐标转 GCJ02 坐标 * * @param lng BD09 坐标纬度 * @param lat BD09 坐标经度 * @return GCJ02 坐标:[经度,纬度] */ public static double[] bd09ToGcj02(double lng, double lat) { double x = lng - 0.0065; double y = lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI); double gg_lng = z * Math.cos(theta); double gg_lat = z * Math.sin(theta); return new double[]{gg_lng, gg_lat}; } /** * GCJ02 坐标转 BD09 坐标 * * @param lng GCJ02 坐标经度 * @param lat GCJ02 坐标纬度 * @return BD09 坐标:[经度,纬度] */ public static double[] gcj02ToBd09(double lng, double lat) { double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * X_PI); double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * X_PI); double bd_lng = z * Math.cos(theta) + 0.0065; double bd_lat = z * Math.sin(theta) + 0.006; return new double[]{bd_lng, bd_lat}; } /** * GCJ02 坐标转 WGS84 坐标 * * @param lng GCJ02 坐标经度 * @param lat GCJ02 坐标纬度 * @return WGS84 坐标:[经度,纬度] */ public static double[] gcj02ToWGS84(double lng, double lat) { if (outOfChina(lng, lat)) { return new double[]{lng, lat}; } double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLng(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * PI; double magic = Math.sin(radlat); magic = 1 - EE * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * PI); double mglat = lat + dlat; double mglng = lng + dlng; return new double[]{lng * 2 - mglng, lat * 2 - mglat}; } /** * WGS84 坐标转 GCJ02 坐标 * * @param lng WGS84 坐标经度 * @param lat WGS84 坐标纬度 * @return GCJ02 坐标:[经度,纬度] */ public static double[] wgs84ToGcj02(double lng, double lat) { if (outOfChina(lng, lat)) { return new double[]{lng, lat}; } double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLng(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * PI; double magic = Math.sin(radlat); magic = 1 - EE * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * PI); double mglat = lat + dlat; double mglng = lng + dlng; return new double[]{mglng, mglat}; } /** * BD09 坐标转 WGS84 坐标 * * @param lng BD09 坐标经度 * @param lat BD09 坐标纬度 * @return WGS84 坐标:[经度,纬度] */ public static double[] bd09ToWGS84(double lng, double lat) { double[] gcj = bd09ToGcj02(lng, lat); return gcj02ToWGS84(gcj[0], gcj[1]); } /** * WGS84 坐标转 BD09 坐标 * * @param lng WGS84 坐标经度 * @param lat WGS84 坐标纬度 * @return BD09 坐标:[经度,纬度] */ public static double[] wgs84ToBd09(double lng, double lat) { double[] gcj = wgs84ToGcj02(lng, lat); return gcj02ToBd09(gcj[0], gcj[1]); } /** * Mercator 坐标转 WGS84 坐标 * * @param lng Mercator 坐标经度 * @param lat Mercator 坐标纬度 * @return WGS84 坐标:[经度,纬度] */ public static double[] mercatorToWGS84(double lng, double lat) { double x = lng / 20037508.34d * 180.; double y = lat / 20037508.34d * 180.; y = 180 / PI * (2 * Math.atan(Math.exp(y * PI / 180.0)) - PI / 2); return new double[]{x, y}; } /** * WGS84 坐标转 Mercator 坐标 * * @param lng WGS84 坐标经度 * @param lat WGS84 坐标纬度 * @return Mercator 坐标:[经度,纬度] */ public static double[] wgs84ToMercator(double lng, double lat) { double x = lng * 20037508.34D / 180.0; double y = Math.log(Math.tan((90.0 + lat) * PI / 360.0)) / (PI / 180.); y = y * 20037508.34D / 180.0; return new double[]{x, y}; } private static double transformLat(double lng, double lat) { double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLng(double lng, double lat) { double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; return ret; } private static boolean outOfChina(double lng, double lat) { return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/TemperatureUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/TemperatureUtils.java
package com.blankj.subutil.util; /** * <pre> * author: Faramarz Afzali * time : 2020/09/05 * desc : This class is intended for converting temperatures into different units. * C refers to the Celsius unit * F refers to the Fahrenheit unit * K refers to the Kelvin unit * </pre> */ public final class TemperatureUtils { public static float cToF(float temp) { return (temp * 9) / 5 + 32; } public static float cToK(float temp) { return temp + 273.15f; } public static float fToC(float temp) { return (temp - 32) * 5 / 9; } public static float fToK(float temp) { return temp + 255.3722222222f; } public static float kToC(float temp) { return temp - 273.15f; } public static float kToF(float temp) { return temp - 459.67f; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/GlideUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/GlideUtils.java
//package com.blankj.subutil.util; // //import android.content.Context; //import android.graphics.drawable.PictureDrawable; //import android.widget.ImageView; // //import com.blankj.subutil.R; //import com.blankj.subutil.util.image.GlideApp; //import com.bumptech.glide.Glide; //import com.bumptech.glide.load.engine.DiskCacheStrategy; //import com.bumptech.glide.request.RequestOptions; // ///** // * <pre> // * author: Blankj // * blog : http://blankj.com // * time : 2018/05/16 // * desc : // * </pre> // */ //public final class GlideUtils { // // // // public static void setCircleImage(Context context, String url, ImageView view) { // RequestOptions requestOptions = new RequestOptions() // .placeholder(R.drawable.def_img_round_holder) // .error(R.drawable.def_img_round_error) // .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC) // .circleCrop().dontAnimate(); // Glide.with(context).load(url).apply(requestOptions).into(view); // } // // public static void setImage(Context context, String url, ImageView view) { // if (url.endsWith(".svg") || url.endsWith(".SVG")) { // setSvgImage(context, url, view); // return; // } // // RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.def_img) // .error(R.drawable.def_img).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).dontAnimate(); // Glide.with(context).load(url).apply(requestOptions).into(view); // } // // private static void setSvgImage(Context context, String url, ImageView view) { // GlideApp.with(context) // .as(PictureDrawable.class) // .error(R.drawable.def_img).load(url).into(view); // } //}
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/Utils.java
lib/subutil/src/main/java/com/blankj/subutil/util/Utils.java
package com.blankj.subutil.util; import android.annotation.SuppressLint; import android.app.Application; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.reflect.InvocationTargetException; /** * <pre> * author: * ___ ___ ___ ___ * _____ / /\ /__/\ /__/| / /\ * / /::\ / /::\ \ \:\ | |:| / /:/ * / /:/\:\ ___ ___ / /:/\:\ \ \:\ | |:| /__/::\ * / /:/~/::\ /__/\ / /\ / /:/~/::\ _____\__\:\ __| |:| \__\/\:\ * /__/:/ /:/\:| \ \:\ / /:/ /__/:/ /:/\:\ /__/::::::::\ /__/\_|:|____ \ \:\ * \ \:\/:/~/:/ \ \:\ /:/ \ \:\/:/__\/ \ \:\~~\~~\/ \ \:\/:::::/ \__\:\ * \ \::/ /:/ \ \:\/:/ \ \::/ \ \:\ ~~~ \ \::/~~~~ / /:/ * \ \:\/:/ \ \::/ \ \:\ \ \:\ \ \:\ /__/:/ * \ \::/ \__\/ \ \:\ \ \:\ \ \:\ \__\/ * \__\/ \__\/ \__\/ \__\/ * blog : http://blankj.com * time : 16/12/08 * desc : utils about initialization * </pre> */ public final class Utils { @SuppressLint("StaticFieldLeak") private static Application sApplication; private Utils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Init utils. * <p>Init it in the class of Application.</p> * * @param context context */ public static void init(final Context context) { if (context == null) { init(getApplicationByReflect()); return; } init((Application) context.getApplicationContext()); } /** * Init utils. * <p>Init it in the class of Application.</p> * * @param app application */ public static void init(final Application app) { if (sApplication == null) { if (app == null) { Utils.sApplication = getApplicationByReflect(); } else { Utils.sApplication = app; } } } /** * Return the context of Application object. * * @return the context of Application object */ public static Application getApp() { if (sApplication != null) return sApplication; return getApplicationByReflect(); } private static Application getApplicationByReflect() { try { @SuppressLint("PrivateApi") Class<?> activityThread = Class.forName("android.app.ActivityThread"); Object at = activityThread.getMethod("currentActivityThread").invoke(null); Object app = activityThread.getMethod("getApplication").invoke(at); if (app == null) { throw new NullPointerException("u should init first"); } init((Application) app); return sApplication; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } throw new NullPointerException("u should init first"); } public static final class ContentProvider4SubUtil extends ContentProvider { @Override public boolean onCreate() { Utils.init(getContext()); return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { return null; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/CountryUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/CountryUtils.java
package com.blankj.subutil.util; import android.content.Context; import android.content.res.Resources; import android.telephony.TelephonyManager; import com.blankj.utilcode.util.Utils; import java.util.HashMap; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/06/11 * desc : utils about country code * </pre> */ public class CountryUtils { private static HashMap<String, String> countryCodeMap; /** * Return the country code by sim card. * * @param defaultValue The default value. * @return the country code */ public static String getCountryCodeBySim(String defaultValue) { String code = getCountryCodeFromMap().get(getCountryBySim()); if (code == null) { return defaultValue; } return code; } /** * Return the country code by system language. * * @param defaultValue The default value. * @return the country code */ public static String getCountryCodeByLanguage(String defaultValue) { String code = getCountryCodeFromMap().get(getCountryByLanguage()); if (code == null) { return defaultValue; } return code; } /** * Return the country by sim card. * * @return the country */ public static String getCountryBySim() { TelephonyManager manager = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE); if (manager != null) { return manager.getSimCountryIso().toUpperCase(); } return ""; } /** * Return the country by system language. * * @return the country */ public static String getCountryByLanguage() { return Resources.getSystem().getConfiguration().locale.getCountry(); } private static HashMap<String, String> getCountryCodeFromMap() { if (countryCodeMap == null) { countryCodeMap = new HashMap<>(256); countryCodeMap.put("AL", "+355"); countryCodeMap.put("DZ", "+213"); countryCodeMap.put("AF", "+93"); countryCodeMap.put("AR", "+54"); countryCodeMap.put("AE", "+971"); countryCodeMap.put("AW", "+297"); countryCodeMap.put("OM", "+968"); countryCodeMap.put("AZ", "+994"); countryCodeMap.put("AC", "+247"); countryCodeMap.put("EG", "+20"); countryCodeMap.put("ET", "+251"); countryCodeMap.put("IE", "+353"); countryCodeMap.put("EE", "+372"); countryCodeMap.put("AD", "+376"); countryCodeMap.put("AO", "+244"); countryCodeMap.put("AI", "+1"); countryCodeMap.put("AG", "+1"); countryCodeMap.put("AT", "+43"); countryCodeMap.put("AX", "+358"); countryCodeMap.put("AU", "+61"); countryCodeMap.put("BB", "+1"); countryCodeMap.put("PG", "+675"); countryCodeMap.put("BS", "+1"); countryCodeMap.put("PK", "+92"); countryCodeMap.put("PY", "+595"); countryCodeMap.put("PS", "+970"); countryCodeMap.put("BH", "+973"); countryCodeMap.put("PA", "+507"); countryCodeMap.put("BR", "+55"); countryCodeMap.put("BY", "+375"); countryCodeMap.put("BM", "+1"); countryCodeMap.put("BG", "+359"); countryCodeMap.put("MP", "+1"); countryCodeMap.put("BJ", "+229"); countryCodeMap.put("BE", "+32"); countryCodeMap.put("IS", "+354"); countryCodeMap.put("PR", "+1"); countryCodeMap.put("PL", "+48"); countryCodeMap.put("BA", "+387"); countryCodeMap.put("BO", "+591"); countryCodeMap.put("BZ", "+501"); countryCodeMap.put("BW", "+267"); countryCodeMap.put("BT", "+975"); countryCodeMap.put("BF", "+226"); countryCodeMap.put("BI", "+257"); countryCodeMap.put("KP", "+850"); countryCodeMap.put("GQ", "+240"); countryCodeMap.put("DK", "+45"); countryCodeMap.put("DE", "+49"); countryCodeMap.put("TL", "+670"); countryCodeMap.put("TG", "+228"); countryCodeMap.put("DO", "+1"); countryCodeMap.put("DM", "+1"); countryCodeMap.put("RU", "+7"); countryCodeMap.put("EC", "+593"); countryCodeMap.put("ER", "+291"); countryCodeMap.put("FR", "+33"); countryCodeMap.put("FO", "+298"); countryCodeMap.put("PF", "+689"); countryCodeMap.put("GF", "+594"); countryCodeMap.put("VA", "+39"); countryCodeMap.put("PH", "+63"); countryCodeMap.put("FJ", "+679"); countryCodeMap.put("FI", "+358"); countryCodeMap.put("CV", "+238"); countryCodeMap.put("FK", "+500"); countryCodeMap.put("GM", "+220"); countryCodeMap.put("CG", "+242"); countryCodeMap.put("CD", "+243"); countryCodeMap.put("CO", "+57"); countryCodeMap.put("CR", "+506"); countryCodeMap.put("GG", "+44"); countryCodeMap.put("GD", "+1"); countryCodeMap.put("GL", "+299"); countryCodeMap.put("GE", "+995"); countryCodeMap.put("CU", "+53"); countryCodeMap.put("GP", "+590"); countryCodeMap.put("GU", "+1"); countryCodeMap.put("GY", "+592"); countryCodeMap.put("KZ", "+7"); countryCodeMap.put("HT", "+509"); countryCodeMap.put("KR", "+82"); countryCodeMap.put("NL", "+31"); countryCodeMap.put("BQ", "+599"); countryCodeMap.put("SX", "+1"); countryCodeMap.put("ME", "+382"); countryCodeMap.put("HN", "+504"); countryCodeMap.put("KI", "+686"); countryCodeMap.put("DJ", "+253"); countryCodeMap.put("KG", "+996"); countryCodeMap.put("GN", "+224"); countryCodeMap.put("GW", "+245"); countryCodeMap.put("CA", "+1"); countryCodeMap.put("GH", "+233"); countryCodeMap.put("GA", "+241"); countryCodeMap.put("KH", "+855"); countryCodeMap.put("CZ", "+420"); countryCodeMap.put("ZW", "+263"); countryCodeMap.put("CM", "+237"); countryCodeMap.put("QA", "+974"); countryCodeMap.put("KY", "+1"); countryCodeMap.put("CC", "+61"); countryCodeMap.put("KM", "+269"); countryCodeMap.put("XK", "+383"); countryCodeMap.put("CI", "+225"); countryCodeMap.put("KW", "+965"); countryCodeMap.put("HR", "+385"); countryCodeMap.put("KE", "+254"); countryCodeMap.put("CK", "+682"); countryCodeMap.put("CW", "+599"); countryCodeMap.put("LV", "+371"); countryCodeMap.put("LS", "+266"); countryCodeMap.put("LA", "+856"); countryCodeMap.put("LB", "+961"); countryCodeMap.put("LT", "+370"); countryCodeMap.put("LR", "+231"); countryCodeMap.put("LY", "+218"); countryCodeMap.put("LI", "+423"); countryCodeMap.put("RE", "+262"); countryCodeMap.put("LU", "+352"); countryCodeMap.put("RW", "+250"); countryCodeMap.put("RO", "+40"); countryCodeMap.put("MG", "+261"); countryCodeMap.put("IM", "+44"); countryCodeMap.put("MV", "+960"); countryCodeMap.put("MT", "+356"); countryCodeMap.put("MW", "+265"); countryCodeMap.put("MY", "+60"); countryCodeMap.put("ML", "+223"); countryCodeMap.put("MK", "+389"); countryCodeMap.put("MH", "+692"); countryCodeMap.put("MQ", "+596"); countryCodeMap.put("YT", "+262"); countryCodeMap.put("MU", "+230"); countryCodeMap.put("MR", "+222"); countryCodeMap.put("US", "+1"); countryCodeMap.put("AS", "+1"); countryCodeMap.put("VI", "+1"); countryCodeMap.put("MN", "+976"); countryCodeMap.put("MS", "+1"); countryCodeMap.put("BD", "+880"); countryCodeMap.put("PE", "+51"); countryCodeMap.put("FM", "+691"); countryCodeMap.put("MM", "+95"); countryCodeMap.put("MD", "+373"); countryCodeMap.put("MA", "+212"); countryCodeMap.put("MC", "+377"); countryCodeMap.put("MZ", "+258"); countryCodeMap.put("MX", "+52"); countryCodeMap.put("NA", "+264"); countryCodeMap.put("ZA", "+27"); countryCodeMap.put("SS", "+211"); countryCodeMap.put("NR", "+674"); countryCodeMap.put("NI", "+505"); countryCodeMap.put("NP", "+977"); countryCodeMap.put("NE", "+227"); countryCodeMap.put("NG", "+234"); countryCodeMap.put("NU", "+683"); countryCodeMap.put("NO", "+47"); countryCodeMap.put("NF", "+672"); countryCodeMap.put("PW", "+680"); countryCodeMap.put("PT", "+351"); countryCodeMap.put("JP", "+81"); countryCodeMap.put("SE", "+46"); countryCodeMap.put("CH", "+41"); countryCodeMap.put("SV", "+503"); countryCodeMap.put("WS", "+685"); countryCodeMap.put("RS", "+381"); countryCodeMap.put("SL", "+232"); countryCodeMap.put("SN", "+221"); countryCodeMap.put("CY", "+357"); countryCodeMap.put("SC", "+248"); countryCodeMap.put("SA", "+966"); countryCodeMap.put("BL", "+590"); countryCodeMap.put("CX", "+61"); countryCodeMap.put("ST", "+239"); countryCodeMap.put("SH", "+290"); countryCodeMap.put("PN", "+870"); countryCodeMap.put("KN", "+1"); countryCodeMap.put("LC", "+1"); countryCodeMap.put("MF", "+590"); countryCodeMap.put("SM", "+378"); countryCodeMap.put("PM", "+508"); countryCodeMap.put("VC", "+1"); countryCodeMap.put("LK", "+94"); countryCodeMap.put("SK", "+421"); countryCodeMap.put("SI", "+386"); countryCodeMap.put("SJ", "+47"); countryCodeMap.put("SZ", "+268"); countryCodeMap.put("SD", "+249"); countryCodeMap.put("SR", "+597"); countryCodeMap.put("SB", "+677"); countryCodeMap.put("SO", "+252"); countryCodeMap.put("TJ", "+992"); countryCodeMap.put("TH", "+66"); countryCodeMap.put("TZ", "+255"); countryCodeMap.put("TO", "+676"); countryCodeMap.put("TC", "+1"); countryCodeMap.put("TA", "+290"); countryCodeMap.put("TT", "+1"); countryCodeMap.put("TN", "+216"); countryCodeMap.put("TV", "+688"); countryCodeMap.put("TR", "+90"); countryCodeMap.put("TM", "+993"); countryCodeMap.put("TK", "+690"); countryCodeMap.put("WF", "+681"); countryCodeMap.put("VU", "+678"); countryCodeMap.put("GT", "+502"); countryCodeMap.put("VE", "+58"); countryCodeMap.put("BN", "+673"); countryCodeMap.put("UG", "+256"); countryCodeMap.put("UA", "+380"); countryCodeMap.put("UY", "+598"); countryCodeMap.put("UZ", "+998"); countryCodeMap.put("GR", "+30"); countryCodeMap.put("ES", "+34"); countryCodeMap.put("EH", "+212"); countryCodeMap.put("SG", "+65"); countryCodeMap.put("NC", "+687"); countryCodeMap.put("NZ", "+64"); countryCodeMap.put("HU", "+36"); countryCodeMap.put("SY", "+963"); countryCodeMap.put("JM", "+1"); countryCodeMap.put("AM", "+374"); countryCodeMap.put("YE", "+967"); countryCodeMap.put("IQ", "+964"); countryCodeMap.put("UM", "+1"); countryCodeMap.put("IR", "+98"); countryCodeMap.put("IL", "+972"); countryCodeMap.put("IT", "+39"); countryCodeMap.put("IN", "+91"); countryCodeMap.put("ID", "+62"); countryCodeMap.put("GB", "+44"); countryCodeMap.put("VG", "+1"); countryCodeMap.put("IO", "+246"); countryCodeMap.put("JO", "+962"); countryCodeMap.put("VN", "+84"); countryCodeMap.put("ZM", "+260"); countryCodeMap.put("JE", "+44"); countryCodeMap.put("TD", "+235"); countryCodeMap.put("GI", "+350"); countryCodeMap.put("CL", "+56"); countryCodeMap.put("CF", "+236"); countryCodeMap.put("CN", "+86"); countryCodeMap.put("MO", "+853"); countryCodeMap.put("TW", "+886"); countryCodeMap.put("HK", "+852"); } return countryCodeMap; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/BatteryUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/BatteryUtils.java
package com.blankj.subutil.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Build; import android.os.PowerManager; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utilcode.util.Utils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.HashSet; import java.util.Set; import androidx.annotation.IntDef; import androidx.annotation.RequiresApi; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2020/03/31 * desc : * </pre> */ public final class BatteryUtils { @IntDef({BatteryStatus.UNKNOWN, BatteryStatus.DISCHARGING, BatteryStatus.CHARGING, BatteryStatus.NOT_CHARGING, BatteryStatus.FULL}) @Retention(RetentionPolicy.SOURCE) public @interface BatteryStatus { int UNKNOWN = BatteryManager.BATTERY_STATUS_UNKNOWN; int DISCHARGING = BatteryManager.BATTERY_STATUS_DISCHARGING; int CHARGING = BatteryManager.BATTERY_STATUS_CHARGING; int NOT_CHARGING = BatteryManager.BATTERY_STATUS_NOT_CHARGING; int FULL = BatteryManager.BATTERY_STATUS_FULL; } /** * Return whether the app is on the device's power whitelist. * * @return {@code true}: yes<br>{@code false}: no */ @RequiresApi(api = Build.VERSION_CODES.M) public static boolean isIgnoringBatteryOptimizations() { return isIgnoringBatteryOptimizations(Utils.getApp().getPackageName()); } /** * Return whether the app is on the device's power whitelist. * * @return {@code true}: yes<br>{@code false}: no */ @RequiresApi(api = Build.VERSION_CODES.M) public static boolean isIgnoringBatteryOptimizations(String pkgName) { try { PowerManager pm = (PowerManager) Utils.getApp().getSystemService(Context.POWER_SERVICE); //noinspection ConstantConditions return pm.isIgnoringBatteryOptimizations(pkgName); } catch (Exception e) { return true; } } /** * Register the status of battery changed listener. * * @param listener The status of battery changed listener. */ public static void registerBatteryStatusChangedListener(final OnBatteryStatusChangedListener listener) { BatteryChangedReceiver.getInstance().registerListener(listener); } /** * Return whether the status of battery changed listener has been registered. * * @param listener The status of battery changed listener. * @return true to registered, false otherwise. */ public static boolean isRegistered(final OnBatteryStatusChangedListener listener) { return BatteryChangedReceiver.getInstance().isRegistered(listener); } /** * Unregister the status of battery changed listener. * * @param listener The status of battery changed listener. */ public static void unregisterBatteryStatusChangedListener(final OnBatteryStatusChangedListener listener) { BatteryChangedReceiver.getInstance().unregisterListener(listener); } public static final class BatteryChangedReceiver extends BroadcastReceiver { private static BatteryChangedReceiver getInstance() { return BatteryChangedReceiver.LazyHolder.INSTANCE; } private Set<OnBatteryStatusChangedListener> mListeners = new HashSet<>(); void registerListener(final OnBatteryStatusChangedListener listener) { if (listener == null) return; ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { int preSize = mListeners.size(); mListeners.add(listener); if (preSize == 0 && mListeners.size() == 1) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); Utils.getApp().registerReceiver(BatteryChangedReceiver.getInstance(), intentFilter); } } }); } boolean isRegistered(final OnBatteryStatusChangedListener listener) { if (listener == null) return false; return mListeners.contains(listener); } void unregisterListener(final OnBatteryStatusChangedListener listener) { if (listener == null) return; ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { int preSize = mListeners.size(); mListeners.remove(listener); if (preSize == 1 && mListeners.size() == 0) { Utils.getApp().unregisterReceiver(BatteryChangedReceiver.getInstance()); } } }); } @Override public void onReceive(Context context, final Intent intent) { if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryStatus.UNKNOWN); for (OnBatteryStatusChangedListener listener : mListeners) { listener.onBatteryStatusChanged(new Status(level, status)); } } }); } } private static class LazyHolder { private static final BatteryChangedReceiver INSTANCE = new BatteryChangedReceiver(); } } public interface OnBatteryStatusChangedListener { void onBatteryStatusChanged(Status status); } public static final class Status { private int level; @BatteryStatus private int status; Status(int level, int status) { this.level = level; this.status = status; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } @BatteryStatus public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return batteryStatus2String(status) + ": " + level + "%"; } public static String batteryStatus2String(@BatteryStatus int status) { if (status == BatteryStatus.DISCHARGING) { return "discharging"; } if (status == BatteryStatus.CHARGING) { return "charging"; } if (status == BatteryStatus.NOT_CHARGING) { return "not_charging"; } if (status == BatteryStatus.FULL) { return "full"; } return "unknown"; } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/PinyinUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/PinyinUtils.java
package com.blankj.subutil.util; import androidx.collection.SimpleArrayMap; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/16 * desc : 拼音相关工具类 * </pre> */ public final class PinyinUtils { private PinyinUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs) { return ccs2Pinyin(ccs, ""); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @param split 汉字拼音之间的分隔符 * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; StringBuilder sb = new StringBuilder(); for (int i = 0, len = ccs.length(); i < len; i++) { char ch = ccs.charAt(i); if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; sb.append(pinyinTable.substring(sp, sp + 6).trim()); } else { sb.append(ch); } sb.append(split); } return sb.toString(); } /** * 获取第一个汉字首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String getPinyinFirstLetter(final CharSequence ccs) { if (ccs == null || ccs.length() == 0) return null; return ccs2Pinyin(String.valueOf(ccs.charAt(0))).substring(0, 1); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs) { return getPinyinFirstLetters(ccs, ""); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @param split 首字母之间的分隔符 * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; int len = ccs.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append(ccs2Pinyin(String.valueOf(ccs.charAt(i))).substring(0, 1)).append(split); } return sb.toString(); } /** * 根据名字获取姓氏的拼音 * * @param name 名字 * @return 姓氏的拼音 */ public static String getSurnamePinyin(final CharSequence name) { if (name == null || name.length() == 0) return null; if (name.length() >= 2) { CharSequence str = name.subSequence(0, 2); if (str.equals("澹台")) return "tantai"; else if (str.equals("尉迟")) return "yuchi"; else if (str.equals("万俟")) return "moqi"; else if (str.equals("单于")) return "chanyu"; } char ch = name.charAt(0); if (SURNAMES.containsKey(ch)) { return SURNAMES.get(ch); } if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; return pinyinTable.substring(sp, sp + 6).trim(); } else { return String.valueOf(ch); } } /** * 根据名字获取姓氏的首字母 * * @param name 名字 * @return 姓氏的首字母 */ public static String getSurnameFirstLetter(final CharSequence name) { String surname = getSurnamePinyin(name); if (surname == null || surname.length() == 0) return null; return String.valueOf(surname.charAt(0)); } // 多音字姓氏映射表 private static final SimpleArrayMap<Character, String> SURNAMES; /** * 获取拼音对照表,对比过pinyin4j和其他方式,这样查表设计的好处就是读取快 * <p>当该类加载后会一直占有123KB的内存</p> * <p>如果你想存进文件,然后读取操作的话也是可以,但速度肯定没有这样空间换时间快,毕竟现在设备内存都很大</p> * <p>如需更多用法可以用pinyin4j开源库</p> */ private static final String pinyinTable; static { SURNAMES = new SimpleArrayMap<>(35); SURNAMES.put('乐', "yue"); SURNAMES.put('乘', "sheng"); SURNAMES.put('乜', "nie"); SURNAMES.put('仇', "qiu"); SURNAMES.put('会', "gui"); SURNAMES.put('便', "pian"); SURNAMES.put('区', "ou"); SURNAMES.put('单', "shan"); SURNAMES.put('参', "shen"); SURNAMES.put('句', "gou"); SURNAMES.put('召', "shao"); SURNAMES.put('员', "yun"); SURNAMES.put('宓', "fu"); SURNAMES.put('弗', "fei"); SURNAMES.put('折', "she"); SURNAMES.put('曾', "zeng"); SURNAMES.put('朴', "piao"); SURNAMES.put('查', "zha"); SURNAMES.put('洗', "xian"); SURNAMES.put('盖', "ge"); SURNAMES.put('祭', "zhai"); SURNAMES.put('种', "chong"); SURNAMES.put('秘', "bi"); SURNAMES.put('繁', "po"); SURNAMES.put('缪', "miao"); SURNAMES.put('能', "nai"); SURNAMES.put('蕃', "pi"); SURNAMES.put('覃', "qin"); SURNAMES.put('解', "xie"); SURNAMES.put('谌', "shan"); SURNAMES.put('适', "kuo"); SURNAMES.put('都', "du"); SURNAMES.put('阿', "e"); SURNAMES.put('难', "ning"); SURNAMES.put('黑', "he"); //noinspection StringBufferReplaceableByString pinyinTable = new StringBuilder(125412) .append("yi ding kao qi shang xia none wan zhang san shang xia ji bu yu mian gai chou chou zhuan qie pi shi shi qiu bing ye cong dong si cheng diu qiu liang diu you liang yan bing sang shu jiu ge ya qiang zhong ji jie feng guan chuan chan lin zhuo zhu none wan dan wei zhu jing li ju pie fu yi yi nai none jiu jiu tuo me yi none zhi wu zha hu fa le zhong ping pang qiao hu guai cheng cheng yi yin none mie jiu qi ye xi xiang gai diu none none shu none shi ji nang jia none shi none none mai luan none ru xi yan fu sha na gan none none none none qian zhi gui gan luan lin yi jue le none yu zheng shi shi er chu yu kui yu yun hu qi wu jing si sui gen gen ya xie ya qi ya ji tou wang kang ta jiao hai yi chan heng mu none xiang jing ting liang heng jing ye qin bo you xie dan lian duo wei ren ren ji none wang yi shen ren le ding ze jin pu chou ba zhang jin jie bing reng cong fo san lun none cang zi shi ta zhang fu xian xian cha hong tong ren qian gan ge di dai ling yi chao chang sa shang yi mu men ren jia chao yang qian zhong pi wan wu jian jia yao feng cang ren wang fen di fang zhong qi pei yu diao dun wen yi xin kang yi ji ai wu ji fu fa xiu jin bei chen fu tang zhong you huo hui yu cui yun san wei chuan che ya xian shang chang lun cang xun xin wei zhu chi xuan nao bo gu ni ni xie ban xu ling zhou shen qu si beng si jia pi yi si ai zheng dian han mai dan zhu bu qu bi shao ci wei di zhu zuo you yang ti zhan he bi tuo she yu yi fo zuo gou ning tong ni xuan ju yong wa qian none ka none pei huai he lao xiang ge yang bai fa ming jia nai bing ji heng huo gui quan tiao jiao ci yi shi xing shen tuo kan zhi gai lai yi chi kua guang li yin shi mi zhu xu you an lu mou er lun dong cha chi xun gong zhou yi ru jian xia jia zai lu: none jiao zhen ce qiao kuai chai ning nong jin wu hou jiong cheng zhen cuo chou qin lu: ju shu ting shen tuo bo nan hao bian tui yu xi cu e qiu xu kuang ku wu jun yi fu lang zu qiao li yong hun jing xian san pai su fu xi li mian ping bao yu si xia xin xiu yu ti che chou none yan liang li lai si jian xiu fu he ju xiao pai jian biao ti fei feng ya an bei yu xin bi chi chang zhi bing zan yao cui lia wan lai cang zong ge guan bei tian shu shu men dao tan jue chui xing peng tang hou yi qi ti gan jing jie xu chang jie fang zhi kong juan zong ju qian ni lun zhuo wo luo song leng hun dong zi ben wu ju nai cai jian zhai ye zhi sha qing none ying cheng qian yan nuan zhong chun jia jie wei yu bing ruo ti wei pian yan feng tang wo e xie che sheng kan di zuo cha ting bei ye huang yao zhan qiu yan you jian xu zha chai fu bi zhi zong mian ji yi xie xun si duan ce zhen ou tou tou bei za lou jie wei fen chang kui sou chi su xia fu yuan rong li ru yun gou ma bang dian tang hao jie xi shan qian jue cang chu san bei xiao yong yao ta suo wang fa bing jia dai zai tang none bin chu nuo zan lei cui yong zao zong peng song ao chuan yu zhai zu shang qian") .append("g qiang chi sha han zhang qing yan di xi lou bei piao jin lian lu man qian xian qiu ying dong zhuan xiang shan qiao jiong tui zun pu xi lao chang guang liao qi deng chan wei zhang fan hui chuan tie dan jiao jiu seng fen xian jue e jiao jian tong lin bo gu xian su xian jiang min ye jin jia qiao pi feng zhou ai sai yi jun nong shan yi dang jing xuan kuai jian chu dan jiao sha zai none bin an ru tai chou chai lan ni jin qian meng wu neng qiong ni chang lie lei lu: kuang bao du biao zan zhi si you hao qin chen li teng wei long chu chan rang shu hui li luo zan nuo tang yan lei nang er wu yun zan yuan xiong chong zhao xiong xian guang dui ke dui mian tu chang er dui er jin tu si yan yan shi shi dang qian dou fen mao xin dou bai jing li kuang ru wang nei quan liang yu ba gong liu xi none lan gong tian guan xing bing qi ju dian zi none yang jian shou ji yi ji chan jiong mao ran nei yuan mao gang ran ce jiong ce zai gua jiong mao zhou mao gou xu mian mi rong yin xie kan jun nong yi mi shi guan meng zhong zui yuan ming kou none fu xie mi bing dong tai gang feng bing hu chong jue hu kuang ye leng pan fu min dong xian lie xia jian jing shu mei shang qi gu zhun song jing liang qing diao ling dong gan jian yin cou ai li cang ming zhun cui si duo jin lin lin ning xi du ji fan fan fan feng ju chu none feng none none fu feng ping feng kai huang kai gan deng ping qu xiong kuai tu ao chu ji dang han han zao dao diao dao ren ren chuangfen qie yi ji kan qian cun chu wen ji dan xing hua wan jue li yue lie liu ze gang chuangfu chu qu ju shan min ling zhong pan bie jie jie bao li shan bie chan jing gua gen dao chuangkui ku duo er zhi shua quan cha ci ke jie gui ci gui kai duo ji ti jing lou luo ze yuan cuo xue ke la qian cha chuan gua jian cuo li ti fei pou chan qi chuangzi gang wan bo ji duo qing yan zhuo jian ji bo yan ju huo sheng jian duo duan wu gua fu sheng jian ge zha kai chuangjuan chan tuan lu li fou shan piao kou jiao gua qiao jue hua zha zhuo lian ju pi liu gui jiao gui jian jian tang huo ji jian yi jian zhi chan cuan mo li zhu li ya quan ban gong jia wu mai lie jing keng xie zhi dong zhu nu jie qu shao yi zhu mo li jing lao lao juan kou yang wa xiao mou kuang jie lie he shi ke jing hao bo min chi lang yong yong mian ke xun juan qing lu bu meng lai le kai mian dong xu xu kan wu yi xun weng sheng lao mu lu piao shi ji qin qiang jiao quan xiang yi qiao fan juan tong ju dan xie mai xun xun lu: li che rang quan bao shao yun jiu bao gou wu yun none none gai gai bao cong none xiong peng ju tao ge pu an pao fu gong da jiu qiong bi hua bei nao chi fang jiu yi za jiang kang jiang kuang hu xia qu fan gui qie cang kuang fei hu yu gui kui hui dan kui lian lian suan du jiu qu xi pi qu yi an yan bian ni qu shi xin qian nian sa zu sheng wu hui ban shi xi wan hua xie wan bei zu zhuo xie dan mai nan dan ji bo shuai bu kuang bian bu zhan ka lu you lu xi gua wo xie jie jie wei ang qiong zhi mao yin we") .append("i shao ji que luan shi juan xie xu jin que wu ji e qing xi none chang han e ting li zhe an li ya ya yan she zhi zha pang none ke ya zhi ce pang ti li she hou ting zui cuo fei yuan ce yuan xiang yan li jue sha dian chu jiu qin ao gui yan si li chang lan li yan yan yuan si si lin qiu qu qu none lei du xian zhuan san can can san can ai dai you cha ji you shuangfan shou guai ba fa ruo shi shu zhui qu shou bian xu jia pan sou ji yu sou die rui cong kou gu ju ling gua tao kou zhi jiao zhao ba ding ke tai chi shi you qiu po ye hao si tan chi le diao ji none hong mie yu mang chi ge xuan yao zi he ji diao cun tong ming hou li tu xiang zha he ye lu: a ma ou xue yi jun chou lin tun yin fei bi qin qin jie pou fou ba dun fen e han ting hang shun qi hu zhi yin wu wu chao na chuo xi chui dou wen hou ou wu gao ya jun lu: e ge mei dai qi cheng wu gao fu jiao hong chi sheng na tun m yi dai ou li bei yuan guo none qiang wu e shi quan pen wen ni mou ling ran you di zhou shi zhou zhan ling yi qi ping zi gua ci wei xu he nao xia pei yi xiao shen hu ming da qu ju gan za tuo duo pou pao bie fu bi he za he hai jiu yong fu da zhou wa ka gu ka zuo bu long dong ning zha si xian huo qi er e guang zha xi yi lie zi mie mi zhi yao ji zhou ge shuai zan xiao ke hui kua huai tao xian e xuan xiu guo yan lao yi ai pin shen tong hong xiong duo wa ha zai you di pai xiang ai gen kuang ya da xiao bi hui none hua none kuai duo none ji nong mou yo hao yuan long pou mang ge e chi shao li na zu he ku xiao xian lao bei zhe zha liang ba mi le sui fou bu han heng geng shuo ge you yan gu gu bai han suo chun yi ai jia tu xian guan li xi tang zuo miu che wu zao ya dou qi di qin ma none gong dou none lao liang suo zao huan none gou ji zuo wo feng yin hu qi shou wei shua chang er li qiang an jie yo nian yu tian lai sha xi tuo hu ai zhou nou ken zhuo zhuo shang di heng lin a xiao xiang tun wu wen cui jie hu qi qi tao dan dan wan zi bi cui chuo he ya qi zhe fei liang xian pi sha la ze qing gua pa zhe se zhuan nie guo luo yan di quan tan bo ding lang xiao none tang chi ti an jiu dan ka yong wei nan shan yu zhe la jie hou han die zhou chai kuai re yu yin zan yao wo mian hu yun chuan hui huan huan xi he ji kui zhong wei sha xu huang du nie xuan liang yu sang chi qiao yan dan pen shi li yo zha wei miao ying pen none kui xi yu jie lou ku cao huo ti yao he a xiu qiang se yong su hong xie ai suo ma cha hai ke da sang chen ru sou gong ji pang wu qian shi ge zi jie luo weng wa si chi hao suo jia hai suo qin nie he none sai ng ge na dia ai none tong bi ao ao lian cui zhe mo sou sou tan di qi jiao chong jiao kai tan san cao jia none xiao piao lou ga gu xiao hu hui guo ou xian ze chang xu po de ma ma hu lei du ga tang ye beng ying none jiao mi xiao hua ") .append("mai ran zuo peng lao xiao ji zhu chao kui zui xiao si hao fu liao qiao xi xu chan dan hei xun wu zun pan chi kui can zan cu dan yu tun cheng jiao ye xi qi hao lian xu deng hui yin pu jue qin xun nie lu si yan ying da zhan o zhou jin nong hui hui qi e zao yi shi jiao yuan ai yong xue kuai yu pen dao ga xin dun dang none sai pi pi yin zui ning di han ta huo ru hao xia yan duo pi chou ji jin hao ti chang none none ca ti lu hui bao you nie yin hu mo huang zhe li liu none nang xiao mo yan li lu long mo dan chen pin pi xiang huo mo xi duo ku yan chan ying rang dian la ta xiao jiao chuo huan huo zhuan nie xiao ca li chan chai li yi luo nang zan su xi none jian za zhu lan nie nang none none wei hui yin qiu si nin jian hui xin yin nan tuan tuan dun kang yuan jiong pian yun cong hu hui yuan e guo kun cong wei tu wei lun guo jun ri ling gu guo tai guo tu you guo yin hun pu yu han yuan lun quan yu qing guo chui wei yuan quan ku pu yuan yuan e tu tu tu tuan lu:e hui yi yuan luan luan tu ya tu ting sheng yan lu none ya zai wei ge yu wu gui pi yi di qian qian zhen zhuo dang qia none none kuang chang qi nie mo ji jia zhi zhi ban xun tou qin fen jun keng dun fang fen ben tan kan huai zuo keng bi xing di jing ji kuai di jing jian tan li ba wu fen zhui po pan tang kun qu tan zhi tuo gan ping dian wa ni tai pi jiong yang fo ao liu qiu mu ke gou xue ba chi che ling zhu fu hu zhi chui la long long lu ao none pao none xing tong ji ke lu ci chi lei gai yin hou dui zhao fu guang yao duo duo gui cha yang yin fa gou yuan die xie ken shang shou e none dian hong ya kua da none dang kai none nao an xing xian huan bang pei ba yi yin han xu chui cen geng ai peng fang que yong jun jia di mai lang xuan cheng shan jin zhe lie lie pu cheng none bu shi xun guo jiong ye nian di yu bu wu juan sui pi cheng wan ju lun zheng kong zhong dong dai tan an cai shu beng kan zhi duo yi zhi yi pei ji zhun qi sao ju ni ku ke tang kun ni jian dui jin gang yu e peng gu tu leng none ya qian none an chen duo nao tu cheng yin hun bi lian guo die zhuan hou bao bao yu di mao jie ruan e geng kan zong yu huang e yao yan bao ji mei chang du tuo an feng zhong jie zhen heng gang chuan jian none lei gang huang leng duan wan xuan ji ji kuai ying ta cheng yong kai su su shi mi ta weng cheng tu tang qiao zhong li peng bang sai zang dui tian wu cheng xun ge zhen ai gong yan kan tian yuan wen xie liu none lang chang peng beng chen lu lu ou qian mei mo zhuan shuangshu lou chi man biao jing ce shu di zhang kan yong dian chen zhi ji guo qiang jin di shang mu cui yan ta zeng qi qiang liang none zhui qiao zeng xu shan shan ba pu kuai dong fan que mo dun dun zun zui sheng duo duo tan deng mu fen huang tan da ye chu none ao qiang ji qiao ken yi pi bi dian jiang ye yong xue tan lan ju huai dang rang qian xuan lan mi he kai ya dao hao ruan none lei kuang lu yan tan wei huai long long rui li ") .append(" lin rang chan xun yan lei ba none shi ren none zhuangzhuangsheng yi mai qiao zhu zhuanghu hu kun yi hu xu kun shou mang zun shou yi zhi gu chu xiang feng bei none bian sui qun ling fu zuo xia xiong none nao xia kui xi wai yuan mao su duo duo ye qing none gou gou qi meng meng yin huo chen da ze tian tai fu guai yao yang hang gao shi ben tai tou yan bi yi kua jia duo none kuang yun jia ba en lian huan di yan pao juan qi nai feng xie fen dian none kui zou huan qi kai she ben yi jiang tao zhuangben xi huang fei diao sui beng dian ao she weng pan ao wu ao jiang lian duo yun jiang shi fen huo bei lian che nu: nu ding nai qian jian ta jiu nan cha hao xian fan ji shuo ru fei wang hong zhuangfu ma dan ren fu jing yan xie wen zhong pa du ji keng zhong yao jin yun miao pei chi yue zhuangniu yan na xin fen bi yu tuo feng yuan fang wu yu gui du ba ni zhou zhou zhao da nai yuan tou xuan zhi e mei mo qi bi shen qie e he xu fa zheng ni ban mu fu ling zi zi shi ran shan yang qian jie gu si xing wei zi ju shan pin ren yao tong jiang shu ji gai shang kuo juan jiao gou lao jian jian yi nian zhi ji ji xian heng guang jun kua yan ming lie pei yan you yan cha xian yin chi gui quan zi song wei hong wa lou ya rao jiao luan ping xian shao li cheng xie mang none suo mu wei ke lai chuo ding niang keng nan yu na pei sui juan shen zhi han di zhuange pin tui xian mian wu yan wu xi yan yu si yu wa li xian ju qu chui qi xian zhui dong chang lu ai e e lou mian cong pou ju po cai ling wan biao xiao shu qi hui fu wo rui tan fei none jie tian ni quan jing hun jing qian dian xing hu wan lai bi yin chou chuo fu jing lun yan lan kun yin ya none li dian xian none hua ying chan shen ting yang yao wu nan chuo jia tou xu yu wei ti rou mei dan ruan qin none wu qian chun mao fu jie duan xi zhong mei huang mian an ying xuan none wei mei yuan zhen qiu ti xie tuo lian mao ran si pian wei wa jiu hu ao none bao xu tou gui zou yao pi xi yuan ying rong ru chi liu mei pan ao ma gou kui qin jia sao zhen yuan cha yong ming ying ji su niao xian tao pang lang niao bao ai pi pin yi piao yu lei xuan man yi zhang kang yong ni li di gui yan jin zhuan chang ce han nen lao mo zhe hu hu ao nen qiang none bi gu wu qiao tuo zhan mao xian xian mo liao lian hua gui deng zhi xu none hua xi hui rao xi yan chan jiao mei fan fan xian yi wei chan fan shi bi shan sui qiang lian huan none niao dong yi can ai niang ning ma tiao chou jin ci yu pin none xu nai yan tai ying can niao none ying mian none ma shen xing ni du liu yuan lan yan shuangling jiao niang lan xian ying shuangshuai quan mi li luan yan zhu lan zi jie jue jue kong yun zi zi cun sun fu bei zi xiao xin meng si tai bao ji gu nu xue none chan hai luan sun nao mie cong jian shu chan ya zi ni fu zi li xue bo ru nai nie nie ying luan mian ning rong ta gui zhai qiong yu shou an tu song wan rou yao hong yi jing zhun mi guai dang hong zong guan zhou ding wa") .append("n yi bao shi shi chong shen ke xuan shi you huan yi tiao shi xian gong cheng qun gong xiao zai zha bao hai yan xiao jia shen chen rong huang mi kou kuan bin su cai zan ji yuan ji yin mi kou qing he zhen jian fu ning bing huan mei qin han yu shi ning jin ning zhi yu bao kuan ning qin mo cha ju gua qin hu wu liao shi ning zhai shen wei xie kuan hui liao jun huan yi yi bao qin chong bao feng cun dui si xun dao lu: dui shou po feng zhuan fu she ke jiang jiang zhuan wei zun xun shu dui dao xiao ji shao er er er ga jian shu chen shang shang yuan ga chang liao xian xian none wang wang you liao liao yao mang wang wang wang ga yao duo kui zhong jiu gan gu gan gan gan gan shi yin chi kao ni jin wei niao ju pi ceng xi bi ju jie tian qu ti jie wu diao shi shi ping ji xie chen xi ni zhan xi none man e lou ping ti fei shu xie tu lu: lu: xi ceng lu: ju xie ju jue liao jue shu xi che tun ni shan wa xian li e none none long yi qi ren wu han shen yu chu sui qi none yue ban yao ang ya wu jie e ji qian fen wan qi cen qian qi cha jie qu gang xian ao lan dao ba zhai zuo yang ju gang ke gou xue bo li tiao qu yan fu xiu jia ling tuo pei you dai kuang yue qu hu po min an tiao ling chi none dong none kui xiu mao tong xue yi none he ke luo e fu xun die lu lang er gai quan tong yi mu shi an wei hu zhi mi li ji tong kui you none xia li yao jiao zheng luan jiao e e yu ye bu qiao qun feng feng nao li you xian hong dao shen cheng tu geng jun hao xia yin wu lang kan lao lai xian que kong chong chong ta none hua ju lai qi min kun kun zu gu cui ya ya gang lun lun leng jue duo cheng guo yin dong han zheng wei yao pi yan song jie beng zu jue dong zhan gu yin zi ze huang yu wei yang feng qiu dun ti yi zhi shi zai yao e zhu kan lu: yan mei gan ji ji huan ting sheng mei qian wu yu zong lan jie yan yan wei zong cha sui rong ke qin yu qi lou tu dui xi weng cang dang rong jie ai liu wu song qiao zi wei beng dian cuo qian yong nie cuo ji none none song zong jiang liao none chan di cen ding tu lou zhang zhan zhan ao cao qu qiang zui zui dao dao xi yu bo long xiang ceng bo qin jiao yan lao zhan lin liao liao jin deng duo zun jiao gui yao qiao yao jue zhan yi xue nao ye ye yi e xian ji xie ke sui di ao zui none yi rong dao ling za yu yue yin none jie li sui long long dian ying xi ju chan ying kui yan wei nao quan chao cuan luan dian dian nie yan yan yan nao yan chuan gui chuan zhou huang jing xun chao chao lie gong zuo qiao ju gong none wu none none cha qiu qiu ji yi si ba zhi zhao xiang yi jin xun juan none xun jin fu za bi shi bu ding shuai fan nie shi fen pa zhi xi hu dan wei zhang tang dai ma pei pa tie fu lian zhi zhou bo zhi di mo yi yi ping qia juan ru shuai dai zhen shui qiao zhen shi qun xi bang dai gui chou ping zhang sha wan dai wei chang sha qi ze guo mao du hou zhen xu mi wei wo fu yi bang ping none gong pan huang dao mi jia teng hui zhong sen ")
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
true
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/LunarUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/LunarUtils.java
package com.blankj.subutil.util; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/12/05 * desc : 日历相关工具类 * </pre> */ public final class LunarUtils { private LunarUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /* * |----4位闰月|-------------13位1为30天,0为29天| */ private static final int[] LUNAR_MONTH_DAYS = {1887, 0x1694, 0x16aa, 0x4ad5, 0xab6, 0xc4b7, 0x4ae, 0xa56, 0xb52a, 0x1d2a, 0xd54, 0x75aa, 0x156a, 0x1096d, 0x95c, 0x14ae, 0xaa4d, 0x1a4c, 0x1b2a, 0x8d55, 0xad4, 0x135a, 0x495d, 0x95c, 0xd49b, 0x149a, 0x1a4a, 0xbaa5, 0x16a8, 0x1ad4, 0x52da, 0x12b6, 0xe937, 0x92e, 0x1496, 0xb64b, 0xd4a, 0xda8, 0x95b5, 0x56c, 0x12ae, 0x492f, 0x92e, 0xcc96, 0x1a94, 0x1d4a, 0xada9, 0xb5a, 0x56c, 0x726e, 0x125c, 0xf92d, 0x192a, 0x1a94, 0xdb4a, 0x16aa, 0xad4, 0x955b, 0x4ba, 0x125a, 0x592b, 0x152a, 0xf695, 0xd94, 0x16aa, 0xaab5, 0x9b4, 0x14b6, 0x6a57, 0xa56, 0x1152a, 0x1d2a, 0xd54, 0xd5aa, 0x156a, 0x96c, 0x94ae, 0x14ae, 0xa4c, 0x7d26, 0x1b2a, 0xeb55, 0xad4, 0x12da, 0xa95d, 0x95a, 0x149a, 0x9a4d, 0x1a4a, 0x11aa5, 0x16a8, 0x16d4, 0xd2da, 0x12b6, 0x936, 0x9497, 0x1496, 0x1564b, 0xd4a, 0xda8, 0xd5b4, 0x156c, 0x12ae, 0xa92f, 0x92e, 0xc96, 0x6d4a, 0x1d4a, 0x10d65, 0xb58, 0x156c, 0xb26d, 0x125c, 0x192c, 0x9a95, 0x1a94, 0x1b4a, 0x4b55, 0xad4, 0xf55b, 0x4ba, 0x125a, 0xb92b, 0x152a, 0x1694, 0x96aa, 0x15aa, 0x12ab5, 0x974, 0x14b6, 0xca57, 0xa56, 0x1526, 0x8e95, 0xd54, 0x15aa, 0x49b5, 0x96c, 0xd4ae, 0x149c, 0x1a4c, 0xbd26, 0x1aa6, 0xb54, 0x6d6a, 0x12da, 0x1695d, 0x95a, 0x149a, 0xda4b, 0x1a4a, 0x1aa4, 0xbb54, 0x16b4, 0xada, 0x495b, 0x936, 0xf497, 0x1496, 0x154a, 0xb6a5, 0xda4, 0x15b4, 0x6ab6, 0x126e, 0x1092f, 0x92e, 0xc96, 0xcd4a, 0x1d4a, 0xd64, 0x956c, 0x155c, 0x125c, 0x792e, 0x192c, 0xfa95, 0x1a94, 0x1b4a, 0xab55, 0xad4, 0x14da, 0x8a5d, 0xa5a, 0x1152b, 0x152a, 0x1694, 0xd6aa, 0x15aa, 0xab4, 0x94ba, 0x14b6, 0xa56, 0x7527, 0xd26, 0xee53, 0xd54, 0x15aa, 0xa9b5, 0x96c, 0x14ae, 0x8a4e, 0x1a4c, 0x11d26, 0x1aa4, 0x1b54, 0xcd6a, 0xada, 0x95c, 0x949d, 0x149a, 0x1a2a, 0x5b25, 0x1aa4, 0xfb52, 0x16b4, 0xaba, 0xa95b, 0x936, 0x1496, 0x9a4b, 0x154a, 0x136a5, 0xda4, 0x15ac}; private static final int[] SOLAR_1_1 = {1887, 0xec04c, 0xec23f, 0xec435, 0xec649, 0xec83e, 0xeca51, 0xecc46, 0xece3a, 0xed04d, 0xed242, 0xed436, 0xed64a, 0xed83f, 0xeda53, 0xedc48, 0xede3d, 0xee050, 0xee244, 0xee439, 0xee64d, 0xee842, 0xeea36, 0xeec4a, 0xeee3e, 0xef052, 0xef246, 0xef43a, 0xef64e, 0xef843, 0xefa37, 0xefc4b, 0xefe41, 0xf0054, 0xf0248, 0xf043c, 0xf0650, 0xf0845, 0xf0a38, 0xf0c4d, 0xf0e42, 0xf1037, 0xf124a, 0xf143e, 0xf1651, 0xf1846, 0xf1a3a, 0xf1c4e, 0xf1e44, 0xf2038, 0xf224b, 0xf243f, 0xf2653, 0xf2848, 0xf2a3b, 0xf2c4f, 0xf2e45, 0xf3039, 0xf324d, 0xf3442, 0xf3636, 0xf384a, 0xf3a3d, 0xf3c51, 0xf3e46, 0xf403b, 0xf424e, 0xf4443, 0xf4638, 0xf484c, 0xf4a3f, 0xf4c52, 0xf4e48, 0xf503c, 0xf524f, 0xf5445, 0xf5639, 0xf584d, 0xf5a42, 0xf5c35, 0xf5e49, 0xf603e, 0xf6251, 0xf6446, 0xf663b, 0xf684f, 0xf6a43, 0xf6c37, 0xf6e4b, 0xf703f, 0xf7252, 0xf7447, 0xf763c, 0xf7850, 0xf7a45, 0xf7c39, 0xf7e4d, 0xf8042, 0xf8254, 0xf8449, 0xf863d, 0xf8851, 0xf8a46, 0xf8c3b, 0xf8e4f, 0xf9044, 0xf9237, 0xf944a, 0xf963f, 0xf9853, 0xf9a47, 0xf9c3c, 0xf9e50, 0xfa045, 0xfa238, 0xfa44c, 0xfa641, 0xfa836, 0xfaa49, 0xfac3d, 0xfae52, 0xfb047, 0xfb23a, 0xfb44e, 0xfb643, 0xfb837, 0xfba4a, 0xfbc3f, 0xfbe53, 0xfc048, 0xfc23c, 0xfc450, 0xfc645, 0xfc839, 0xfca4c, 0xfcc41, 0xfce36, 0xfd04a, 0xfd23d, 0xfd451, 0xfd646, 0xfd83a, 0xfda4d, 0xfdc43, 0xfde37, 0xfe04b, 0xfe23f, 0xfe453, 0xfe648, 0xfe83c, 0xfea4f, 0xfec44, 0xfee38, 0xff04c, 0xff241, 0xff436, 0xff64a, 0xff83e, 0xffa51, 0xffc46, 0xffe3a, 0x10004e, 0x100242, 0x100437, 0x10064b, 0x100841, 0x100a53, 0x100c48, 0x100e3c, 0x10104f, 0x101244, 0x101438, 0x10164c, 0x101842, 0x101a35, 0x101c49, 0x101e3d, 0x102051, 0x102245, 0x10243a, 0x10264e, 0x102843, 0x102a37, 0x102c4b, 0x102e3f, 0x103053, 0x103247, 0x10343b, 0x10364f, 0x103845, 0x103a38, 0x103c4c, 0x103e42, 0x104036, 0x104249, 0x10443d, 0x104651, 0x104846, 0x104a3a, 0x104c4e, 0x104e43, 0x105038, 0x10524a, 0x10543e, 0x105652, 0x105847, 0x105a3b, 0x105c4f, 0x105e45, 0x106039, 0x10624c, 0x106441, 0x106635, 0x106849, 0x106a3d, 0x106c51, 0x106e47, 0x10703c, 0x10724f, 0x107444, 0x107638, 0x10784c, 0x107a3f, 0x107c53, 0x107e48}; private static int getBitInt(final int data, final int length, final int shift) { return (data & (((1 << length) - 1) << shift)) >> shift; } /** * 农历年转干支年 * * @param lunarYear 农历年份 * @return 干支年 */ public static String lunarYear2GanZhi(final int lunarYear) { final String[] tianGan = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}; final String[] diZhi = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; return tianGan[(lunarYear - 4) % 10] + diZhi[(lunarYear - 4) % 12] + "年"; } /** * 农历转公历 * * @param lunar 农历 * @return 公历 */ public static Solar lunar2Solar(final Lunar lunar) { int days = LUNAR_MONTH_DAYS[lunar.lunarYear - LUNAR_MONTH_DAYS[0]]; int leap = getBitInt(days, 4, 13); int offset = 0; int loopend = leap; if (!lunar.isLeap) { if (lunar.lunarMonth <= leap || leap == 0) { loopend = lunar.lunarMonth - 1; } else { loopend = lunar.lunarMonth; } } for (int i = 0; i < loopend; i++) { offset += getBitInt(days, 1, 12 - i) == 1 ? 30 : 29; } offset += lunar.lunarDay; int solar11 = SOLAR_1_1[lunar.lunarYear - SOLAR_1_1[0]]; int y = getBitInt(solar11, 12, 9); int m = getBitInt(solar11, 4, 5); int d = getBitInt(solar11, 5, 0); return solarFromInt(solarToInt(y, m, d) + offset - 1); } /** * 公历转农历 * * @param solar 公历 * @return 阴历 */ public static Lunar solar2Lunar(final Solar solar) { Lunar lunar = new Lunar(); int index = solar.solarYear - SOLAR_1_1[0]; int data = (solar.solarYear << 9) | (solar.solarMonth << 5) | (solar.solarDay); int solar11 = 0; if (SOLAR_1_1[index] > data) { index--; } solar11 = SOLAR_1_1[index]; int y = getBitInt(solar11, 12, 9); int m = getBitInt(solar11, 4, 5); int d = getBitInt(solar11, 5, 0); long offset = solarToInt(solar.solarYear, solar.solarMonth, solar.solarDay) - solarToInt(y, m, d); int days = LUNAR_MONTH_DAYS[index]; int leap = getBitInt(days, 4, 13); int lunarY = index + SOLAR_1_1[0]; int lunarM = 1; int lunarD = 1; offset += 1; for (int i = 0; i < 13; i++) { int dm = getBitInt(days, 1, 12 - i) == 1 ? 30 : 29; if (offset > dm) { lunarM++; offset -= dm; } else { break; } } lunarD = (int) (offset); lunar.lunarYear = lunarY; lunar.lunarMonth = lunarM; lunar.isLeap = false; if (leap != 0 && lunarM > leap) { lunar.lunarMonth = lunarM - 1; if (lunarM == leap + 1) { lunar.isLeap = true; } } lunar.lunarDay = lunarD; return lunar; } private static Solar solarFromInt(final long g) { long y = (10000 * g + 14780) / 3652425; long ddd = g - (365 * y + y / 4 - y / 100 + y / 400); if (ddd < 0) { y--; ddd = g - (365 * y + y / 4 - y / 100 + y / 400); } long mi = (100 * ddd + 52) / 3060; long mm = (mi + 2) % 12 + 1; y = y + (mi + 2) / 12; long dd = ddd - (mi * 306 + 5) / 10 + 1; Solar solar = new Solar(); solar.solarYear = (int) y; solar.solarMonth = (int) mm; solar.solarDay = (int) dd; return solar; } private static long solarToInt(int y, int m, final int d) { m = (m + 9) % 12; y = y - m / 10; return 365 * y + y / 4 - y / 100 + y / 400 + (m * 306 + 5) / 10 + (d - 1); } public static class Lunar { public int lunarYear; public int lunarMonth; public int lunarDay; public boolean isLeap; Lunar() { } public Lunar(int lunarYear, int lunarMonth, int lunarDay, boolean isLeap) { this.lunarYear = lunarYear; this.lunarMonth = lunarMonth; this.lunarDay = lunarDay; this.isLeap = isLeap; } @Override public String toString() { return "" + lunarYear + ", " + lunarMonth + ", " + lunarDay + ", " + isLeap; } } public static class Solar { public int solarYear; public int solarMonth; public int solarDay; Solar() { } public Solar(int solarYear, int solarMonth, int solarDay) { this.solarYear = solarYear; this.solarMonth = solarMonth; this.solarDay = solarDay; } @Override public String toString() { return "" + solarYear + ", " + solarMonth + ", " + solarDay; } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/HttpsUtil.java
lib/subutil/src/main/java/com/blankj/subutil/util/HttpsUtil.java
package com.blankj.subutil.util; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; /** * <pre> * author: MilkZS * time : 2019/01/09 * desc : https 工具类 * </pre> */ public final class HttpsUtil { private static final int CONNECT_TIMEOUT_TIME = 15000; private static final int READ_TIMEOUT_TIME = 19000; /** * POST + JSON * * @param data send data * @param url target url * @return data receive from server * @author MilkZS */ public static String postJson(String data, String url) { return doHttpAction(data, true, true, url); } /** * POST + FORM * * @param data send data * @param url target url * @return data receive from serv * @author MilkZS */ public static String postForm(String data, String url) { return doHttpAction(data, false, true, url); } /** * GET + JSON * * @param data send data * @param url target url * @return data receive from server * @author MilkZS */ public static String getJson(String data, String url) { return doHttpAction(data, true, false, url); } /** * GET + FORM * * @param data send data * @param url target url * @return data receive from server * @author MilkZS */ public static String getForm(String data, String url) { return doHttpAction(data, false, false, url); } private static String doHttpAction(String data, boolean json, boolean post, String url) { HttpURLConnection connection = null; DataOutputStream os = null; InputStream is = null; try { URL sUrl = new URL(url); connection = (HttpURLConnection) sUrl.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT_TIME); connection.setReadTimeout(READ_TIMEOUT_TIME); if (post) { connection.setRequestMethod("POST"); } else { connection.setRequestMethod("GET"); } //允许输入输出 connection.setDoInput(true); connection.setDoOutput(true); // 是否使用缓冲 connection.setUseCaches(false); // 本次连接是否处理重定向,设置成true,系统自动处理重定向; // 设置成false,则需要自己从http reply中分析新的url自己重新连接。 connection.setInstanceFollowRedirects(true); // 设置请求头里的属性 if (json) { connection.setRequestProperty("Content-Type", "application/json"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", data.length() + ""); } connection.connect(); os = new DataOutputStream(connection.getOutputStream()); os.write(data.getBytes(), 0, data.getBytes().length); os.flush(); os.close(); is = connection.getInputStream(); Scanner scan = new Scanner(is); scan.useDelimiter("\\A"); if (scan.hasNext()) return scan.next(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) connection.disconnect(); if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/AppStoreUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/AppStoreUtils.java
package com.blankj.subutil.util; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.util.Log; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.RomUtils; import com.blankj.utilcode.util.Utils; import java.util.List; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/05/20 * desc : utils about app store * </pre> */ public final class AppStoreUtils { private static final String TAG = "AppStoreUtils"; private static final String GOOGLE_PLAY_APP_STORE_PACKAGE_NAME = "com.android.vending"; /** * 获取跳转到应用商店的 Intent * * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent() { return getAppStoreIntent(Utils.getApp().getPackageName(), false); } /** * 获取跳转到应用商店的 Intent * * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(boolean isIncludeGooglePlayStore) { return getAppStoreIntent(Utils.getApp().getPackageName(), isIncludeGooglePlayStore); } /** * 获取跳转到应用商店的 Intent * * @param packageName 包名 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName) { return getAppStoreIntent(packageName, false); } /** * 获取跳转到应用商店的 Intent * <p>优先跳转到手机自带的应用市场</p> * * @param packageName 包名 * @param isIncludeGooglePlayStore 是否包括 Google Play 商店 * @return 跳转到应用商店的 Intent */ public static Intent getAppStoreIntent(final String packageName, boolean isIncludeGooglePlayStore) { if (RomUtils.isSamsung()) {// 三星单独处理跳转三星市场 Intent samsungAppStoreIntent = getSamsungAppStoreIntent(packageName); if (samsungAppStoreIntent != null) return samsungAppStoreIntent; } if (RomUtils.isLeeco()) {// 乐视单独处理跳转乐视市场 Intent leecoAppStoreIntent = getLeecoAppStoreIntent(packageName); if (leecoAppStoreIntent != null) return leecoAppStoreIntent; } Uri uri = Uri.parse("market://details?id=" + packageName); Intent intent = new Intent(); intent.setData(uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (resolveInfos == null || resolveInfos.size() == 0) { Log.e(TAG, "No app store!"); return null; } Intent googleIntent = null; for (ResolveInfo resolveInfo : resolveInfos) { String pkgName = resolveInfo.activityInfo.packageName; if (!GOOGLE_PLAY_APP_STORE_PACKAGE_NAME.equals(pkgName)) { if (AppUtils.isAppSystem(pkgName)) { intent.setPackage(pkgName); return intent; } } else { intent.setPackage(GOOGLE_PLAY_APP_STORE_PACKAGE_NAME); googleIntent = intent; } } if (isIncludeGooglePlayStore && googleIntent != null) { return googleIntent; } intent.setPackage(resolveInfos.get(0).activityInfo.packageName); return intent; } private static Intent getSamsungAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main"); intent.setData(Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + packageName)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static Intent getLeecoAppStoreIntent(final String packageName) { Intent intent = new Intent(); intent.setClassName("com.letv.app.appstore", "com.letv.app.appstore.appmodule.details.DetailsActivity"); intent.setAction("com.letv.app.appstore.appdetailactivity"); intent.putExtra("packageName", packageName); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getAvailableIntentSize(intent) > 0) { return intent; } return null; } private static int getAvailableIntentSize(final Intent intent) { return Utils.getApp().getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/BitUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/BitUtils.java
package com.blankj.subutil.util; import android.util.Log; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/03/21 * desc : 位运算工具类 * </pre> */ public final class BitUtils { private BitUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 获取运算数指定位置的值<br> * 例如: 0000 1011 获取其第 0 位的值为 1, 第 2 位 的值为 0<br> * * @param source 需要运算的数 * @param pos 指定位置 (0...7) * @return 指定位置的值(0 or 1) */ public static byte getBitValue(byte source, int pos) { return (byte) ((source >> pos) & 1); } /** * 将运算数指定位置的值置为指定值<br> * 例: 0000 1011 需要更新为 0000 1111, 即第 2 位的值需要置为 1<br> * * @param source 需要运算的数 * @param pos 指定位置 (0<=pos<=7) * @param value 只能取值为 0, 或 1, 所有大于0的值作为1处理, 所有小于0的值作为0处理 * @return 运算后的结果数 */ public static byte setBitValue(byte source, int pos, byte value) { byte mask = (byte) (1 << pos); if (value > 0) { source |= mask; } else { source &= (~mask); } return source; } /** * 将运算数指定位置取反值<br> * 例: 0000 1011 指定第 3 位取反, 结果为 0000 0011; 指定第2位取反, 结果为 0000 1111<br> * * @param source * @param pos 指定位置 (0<=pos<=7) * @return 运算后的结果数 */ public static byte reverseBitValue(byte source, int pos) { byte mask = (byte) (1 << pos); return (byte) (source ^ mask); } /** * 检查运算数的指定位置是否为1<br> * * @param source 需要运算的数 * @param pos 指定位置 (0<=pos<=7) * @return true 表示指定位置值为1, false 表示指定位置值为 0 */ public static boolean checkBitValue(byte source, int pos) { source = (byte) (source >>> pos); return (source & 1) == 1; } /** * 入口函数做测试<br> * * @param args */ public static void main(String[] args) { // 取十进制 11 (二级制 0000 1011) 为例子 byte source = 11; // 取第2位值并输出, 结果应为 0000 1011 for (byte i = 7; i >= 0; i--) { Log.d("BitUtils", getBitValue(source, i) + ""); } // 将第6位置为1并输出 , 结果为 75 (0100 1011) Log.d("BitUtils", setBitValue(source, 6, (byte) 1) + ""); // 将第6位取反并输出, 结果应为75(0100 1011) Log.d("BitUtils", reverseBitValue(source, 6) + ""); // 检查第6位是否为1,结果应为false Log.d("BitUtils", checkBitValue(source, 6) + ""); // 输出为1的位, 结果应为 0 1 3 for (byte i = 0; i < 8; i++) { if (checkBitValue(source, i)) { Log.d("BitUtils", i + ""); } } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/RetrofitUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/RetrofitUtils.java
package com.blankj.subutil.util; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/08/25 * desc : utils about retrofit * </pre> */ public final class RetrofitUtils { }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/CameraUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/CameraUtils.java
package com.blankj.subutil.util; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/09/19 * desc : 相机相关工具类 * </pre> */ public final class CameraUtils { // private CameraUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 获取打开照程序界面的Intent // */ // public static Intent getOpenCameraIntent() { // return new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // } // // /** // * 获取跳转至相册选择界面的Intent // */ // public static Intent getImagePickerIntent() { // Intent intent = new Intent(Intent.ACTION_PICK, null); // return intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getImagePickerIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,可以指定是否缩放裁剪区域]的Intent // * // * @param aspectX 裁剪框尺寸比例X // * @param aspectY 裁剪框尺寸比例Y // * @param outputX 输出尺寸宽度 // * @param outputY 输出尺寸高度 // * @param canScale 是否可缩放 // * @param fromFileURI 文件来源路径URI // * @param saveFileURI 输出文件路径URI // */ // public static Intent getImagePickerIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent = new Intent(Intent.ACTION_PICK); // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 去除人脸识别 // return intent.putExtra("noFaceDetection", true); // } // // /** // * 获取[跳转至相册选择界面,并跳转至裁剪界面,默认可缩放裁剪区域]的Intent // */ // public static Intent getCameraIntent(final Uri saveFileURI) { // Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // return mIntent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(1, 1, outputX, outputY, true, fromFileURI, saveFileURI); // } // // /** // * 获取[跳转至裁剪界面,默认可缩放]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, Uri fromFileURI, // Uri saveFileURI) { // return getCropImageIntent(aspectX, aspectY, outputX, outputY, true, fromFileURI, saveFileURI); // } // // // /** // * 获取[跳转至裁剪界面]的Intent // */ // public static Intent getCropImageIntent(int aspectX, int aspectY, int outputX, int outputY, boolean canScale, // Uri fromFileURI, Uri saveFileURI) { // Intent intent = new Intent("com.android.camera.action.CROP"); // intent.setDataAndType(fromFileURI, "image/*"); // intent.putExtra("crop", "true"); // // X方向上的比例 // intent.putExtra("aspectX", aspectX <= 0 ? 1 : aspectX); // // Y方向上的比例 // intent.putExtra("aspectY", aspectY <= 0 ? 1 : aspectY); // intent.putExtra("outputX", outputX); // intent.putExtra("outputY", outputY); // intent.putExtra("scale", canScale); // // 图片剪裁不足黑边解决 // intent.putExtra("scaleUpIfNeeded", true); // intent.putExtra("return-data", false); // // 需要将读取的文件路径和裁剪写入的路径区分,否则会造成文件0byte // intent.putExtra(MediaStore.EXTRA_OUTPUT, saveFileURI); // // true-->返回数据类型可以设置为Bitmap,但是不能传输太大,截大图用URI,小图用Bitmap或者全部使用URI // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); // // 取消人脸识别功能 // intent.putExtra("noFaceDetection", true); // return intent; // } // // /** // * 获得选中相册的图片 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return bitmap // */ // public static Bitmap getChoosedImage(final Activity context, final Intent data) { // if (data == null) return null; // Bitmap bm = null; // ContentResolver cr = context.getContentResolver(); // Uri originalUri = data.getData(); // try { // bm = MediaStore.Images.Media.getBitmap(cr, originalUri); // } catch (IOException e) { // e.printStackTrace(); // } // return bm; // } // // /** // * 获得选中相册的图片路径 // * // * @param context 上下文 // * @param data onActivityResult返回的Intent // * @return // */ // public static String getChoosedImagePath(final Activity context, final Intent data) { // if (data == null) return null; // String path = ""; // ContentResolver resolver = context.getContentResolver(); // Uri originalUri = data.getData(); // if (null == originalUri) return null; // String[] projection = {MediaStore.Images.Media.DATA}; // Cursor cursor = resolver.query(originalUri, projection, null, null, null); // if (null != cursor) { // try { // int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // cursor.moveToFirst(); // path = cursor.getString(column_index); // } catch (IllegalArgumentException e) { // e.printStackTrace(); // } finally { // try { // if (!cursor.isClosed()) { // cursor.close(); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // } // return StringUtils.isEmpty(path) ? originalUri.getPath() : null; // } // // /** // * 获取拍照之后的照片文件(JPG格式) // * // * @param data onActivityResult回调返回的数据 // * @param filePath The path of file. // * @return 文件 // */ // public static File getTakePictureFile(final Intent data, final String filePath) { // if (data == null) return null; // Bundle extras = data.getExtras(); // if (extras == null) return null; // Bitmap photo = extras.getParcelable("data"); // File file = new File(filePath); // if (ImageUtils.save(photo, file, Bitmap.CompressFormat.JPEG)) return file; // return null; // } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/SSLConfig.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/SSLConfig.java
package com.blankj.subutil.util.http; import android.annotation.SuppressLint; import android.os.Build; import androidx.annotation.NonNull; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedTrustManager; import javax.net.ssl.X509TrustManager; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/02/20 * </pre> */ public final class SSLConfig { SSLSocketFactory mSSLSocketFactory; HostnameVerifier mHostnameVerifier; public SSLConfig(@NonNull SSLSocketFactory factory, @NonNull HostnameVerifier verifier) { mSSLSocketFactory = factory; mHostnameVerifier = verifier; } public static final HostnameVerifier DEFAULT_VERIFIER = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; public static final SSLSocketFactory DEFAULT_SSL_SOCKET_FACTORY = new DefaultSSLSocketFactory(); public static final SSLConfig DEFAULT_SSL_CONFIG = new SSLConfig(DEFAULT_SSL_SOCKET_FACTORY, DEFAULT_VERIFIER); private static class DefaultSSLSocketFactory extends SSLSocketFactory { private static final String[] PROTOCOL_ARRAY; private static final TrustManager[] DEFAULT_TRUST_MANAGERS; static { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { PROTOCOL_ARRAY = new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"}; } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { PROTOCOL_ARRAY = new String[]{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; } else { PROTOCOL_ARRAY = new String[]{"SSLv3", "TLSv1"}; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { DEFAULT_TRUST_MANAGERS = new TrustManager[]{ new X509ExtendedTrustManager() { @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType) {/**/} @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {/**/} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {/**/} @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {/**/} @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {/**/} @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {/**/} } }; } else { DEFAULT_TRUST_MANAGERS = new TrustManager[]{ new X509TrustManager() { @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType) {/**/} @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {/**/} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; } } private SSLSocketFactory mFactory; DefaultSSLSocketFactory() { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, DEFAULT_TRUST_MANAGERS, new SecureRandom()); mFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new AssertionError(); } } @Override public String[] getDefaultCipherSuites() { return mFactory.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return mFactory.getSupportedCipherSuites(); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { Socket ssl = mFactory.createSocket(s, host, port, autoClose); setSupportProtocolAndCipherSuites(ssl); return ssl; } @Override public Socket createSocket(String host, int port) throws IOException { Socket ssl = mFactory.createSocket(host, port); setSupportProtocolAndCipherSuites(ssl); return ssl; } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { Socket ssl = mFactory.createSocket(host, port, localHost, localPort); setSupportProtocolAndCipherSuites(ssl); return ssl; } @Override public Socket createSocket(InetAddress host, int port) throws IOException { Socket ssl = mFactory.createSocket(host, port); setSupportProtocolAndCipherSuites(ssl); return ssl; } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { Socket ssl = mFactory.createSocket(address, port, localAddress, localPort); setSupportProtocolAndCipherSuites(ssl); return ssl; } @Override public Socket createSocket() throws IOException { Socket ssl = mFactory.createSocket(); setSupportProtocolAndCipherSuites(ssl); return ssl; } private void setSupportProtocolAndCipherSuites(Socket socket) { if (socket instanceof SSLSocket) { ((SSLSocket) socket).setEnabledProtocols(PROTOCOL_ARRAY); } } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/ExecutorFactory.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/ExecutorFactory.java
package com.blankj.subutil.util.http; import android.os.Handler; import android.os.Looper; import androidx.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public final class ExecutorFactory { private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final Executor DEFAULT_WORK_EXECUTOR = new ThreadPoolExecutor(2 * CPU_COUNT + 1, 2 * CPU_COUNT + 1, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(128), new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(@NonNull Runnable r) { return new Thread(r, "http-pool-" + mCount.getAndIncrement()); } } ); private static final Executor DEFAULT_MAIN_EXECUTOR = new Executor() { private final Handler mHandler = new Handler(Looper.getMainLooper()); @Override public void execute(@NonNull Runnable command) { mHandler.post(command); } }; public static Executor getDefaultWorkExecutor() { return DEFAULT_WORK_EXECUTOR; } public static Executor getDefaultMainExecutor() { return DEFAULT_MAIN_EXECUTOR; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/ResponseCallback.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/ResponseCallback.java
package com.blankj.subutil.util.http; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/02/17 * </pre> */ public abstract class ResponseCallback { public abstract void onResponse(Response response); public abstract void onFailed(Exception e); }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/HttpUtils.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/HttpUtils.java
package com.blankj.subutil.util.http; import android.accounts.NetworkErrorException; import androidx.annotation.NonNull; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.Proxy; import java.nio.charset.Charset; import java.util.Map; import java.util.concurrent.Executor; import javax.net.ssl.HttpsURLConnection; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/02/08 * desc : utils about http * </pre> */ public final class HttpUtils { private static final String BOUNDARY = java.util.UUID.randomUUID().toString(); private static final String TWO_HYPHENS = "--"; private static final int CONNECT_TIMEOUT_TIME = 15000; private static final int READ_TIMEOUT_TIME = 20000; private static final int BUFFER_SIZE = 8192; private static final Config CONFIG = new Config(); private final Config mConfig; private static HttpUtils sHttpUtils; private HttpUtils(@NonNull Config config) { mConfig = config; } public static HttpUtils getInstance(@NonNull Config config) { if (sHttpUtils == null) { synchronized (HttpUtils.class) { sHttpUtils = new HttpUtils(config); } } return sHttpUtils; } public static void call(@NonNull final Request request, @NonNull final ResponseCallback callback) { new Call(request, callback).run(); } private static HttpURLConnection getConnection(final Request request) throws IOException { HttpURLConnection conn = (HttpURLConnection) request.mURL.openConnection(); if (conn instanceof HttpsURLConnection) { HttpsURLConnection httpsConn = (HttpsURLConnection) conn; httpsConn.setSSLSocketFactory(CONFIG.sslConfig.mSSLSocketFactory); httpsConn.setHostnameVerifier(CONFIG.sslConfig.mHostnameVerifier); } System.out.println(conn.getHeaderField("USE")); addHeader(conn, request.mHeader); addBody(conn, request.mBody); conn.setConnectTimeout(CONFIG.connectTimeout); conn.setReadTimeout(CONFIG.readTimeout); return conn; } private static void addBody(HttpURLConnection conn, Request.Body body) throws IOException { if (body == null) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("content-type", body.mediaType); if (body.length > 0) { conn.setRequestProperty("content-length", String.valueOf(body.length)); } BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream(), 10240); if (body.bis != null) { byte[] buffer = new byte[10240]; for (int len; (len = body.bis.read(buffer)) != -1; ) { bos.write(buffer, 0, len); } bos.close(); body.bis.close(); } } } private static void addHeader(final HttpURLConnection conn, final Map<String, String> headerMap) { if (headerMap != null) { for (String key : headerMap.keySet()) { conn.setRequestProperty(key, headerMap.get(key)); } } } private static boolean isSpace(final String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } static String is2String(final InputStream is, final String charset) { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; try { for (int len; (len = is.read(buffer)) != -1; ) { result.write(buffer, 0, len); } return result.toString(charset); } catch (Exception e) { e.printStackTrace(); return ""; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } static boolean writeFileFromIS(final File file, final InputStream is) { if (!createOrExistsFile(file) || is == null) return false; OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); byte[] data = new byte[8192]; for (int len; (len = is.read(data)) != -1; ) { os.write(data, 0, len); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } } private static boolean createOrExistsFile(final File file) { if (file == null) return false; if (file.exists()) return file.isFile(); if (!createOrExistsDir(file.getParentFile())) return false; try { return file.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } } private static boolean createOrExistsDir(final File file) { return file != null && (file.exists() ? file.isDirectory() : file.mkdirs()); } public static class Config { private Executor workExecutor = ExecutorFactory.getDefaultWorkExecutor(); private Executor mainExecutor = ExecutorFactory.getDefaultMainExecutor(); private SSLConfig sslConfig = SSLConfig.DEFAULT_SSL_CONFIG; private int connectTimeout = CONNECT_TIMEOUT_TIME; private int readTimeout = READ_TIMEOUT_TIME; private Charset charset = Charset.defaultCharset(); private Proxy proxy = null; } static class Call implements Runnable { private Request request; private ResponseCallback callback; public Call(Request request, ResponseCallback callback) { this.request = request; this.callback = callback; } @Override public void run() { HttpURLConnection conn = null; try { conn = getConnection(request); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); callback.onResponse(new Response(conn.getHeaderFields(), is)); is.close(); } else if (responseCode == 301 || responseCode == 302) { String location = conn.getHeaderField("Location"); call(request, callback); } else { String errorMsg = null; InputStream es = conn.getErrorStream(); if (es != null) { errorMsg = is2String(es, "utf-8"); } callback.onFailed(new NetworkErrorException("error code: " + responseCode + (isSpace(errorMsg) ? "" : ("\n" + "error message: " + errorMsg)))); } } catch (IOException e) { callback.onFailed(e); } finally { if (conn != null) { conn.disconnect(); } } } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/Chain.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/Chain.java
package com.blankj.subutil.util.http; public interface Chain { }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/Response.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/Response.java
package com.blankj.subutil.util.http; import com.google.gson.Gson; import java.io.File; import java.io.InputStream; import java.lang.reflect.Type; import java.util.List; import java.util.Map; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/02/17 * </pre> */ public class Response { private Map<String, List<String>> mHeaders; private InputStream mBody; public Response(Map<String, List<String>> headers, InputStream body) { mHeaders = headers; mBody = body; } public Map<String, List<String>> getHeaders() { return mHeaders; } public InputStream getBody() { return mBody; } public String getString() { return getString("utf-8"); } public String getString(final String charset) { return HttpUtils.is2String(mBody, charset); } public <T> T getJson(final Type type) { return getJson(type, "utf-8"); } public <T> T getJson(final Type type, final String charset) { return new Gson().fromJson(getString(charset), type); } public boolean downloadFile(final File file) { return HttpUtils.writeFileFromIS(file, mBody); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/Headers.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/Headers.java
package com.blankj.subutil.util.http; import java.util.HashMap; import java.util.List; import java.util.Map; public class Headers { private Map<String, List<String>> header = new HashMap<>(); }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/Request.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/Request.java
package com.blankj.subutil.util.http; import androidx.annotation.NonNull; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.util.HashMap; import java.util.Map; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/02/17 * </pre> */ public final class Request { URL mURL; Map<String, String> mHeader; Body mBody; public static Request withUrl(@NonNull final String url) { return new Request(url); } private Request(final String url) { try { mURL = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } } public Request addHeader(@NonNull final String name, @NonNull final String value) { if (mHeader == null) { mHeader = new HashMap<>(); } mHeader.put(name, value); return this; } public Request addHeader(@NonNull final Map<String, String> header) { if (this.mHeader == null) { this.mHeader = new HashMap<>(); } this.mHeader.putAll(header); return this; } public Request post(@NonNull final Body body) { this.mBody = body; return this; } public static class Body { String mediaType; BufferedInputStream bis; long length; private Body(final String mediaType, final byte[] body) { this.mediaType = mediaType; bis = new BufferedInputStream(new ByteArrayInputStream(body)); length = body.length; } private Body(final String mediaType, final InputStream body) { this.mediaType = mediaType; if (body instanceof BufferedInputStream) { bis = (BufferedInputStream) body; } else { bis = new BufferedInputStream(body); } length = -1; } private static String getCharsetFromMediaType(String mediaType) { mediaType = mediaType.toLowerCase().replace(" ", ""); int index = mediaType.indexOf("charset="); if (index == -1) return "utf-8"; int st = index + 8; int end = mediaType.length(); if (st >= end) { throw new IllegalArgumentException("MediaType is not correct: \"" + mediaType + "\""); } for (int i = st; i < end; i++) { char c = mediaType.charAt(i); if (c >= 'A' && c <= 'Z') continue; if (c >= 'a' && c <= 'z') continue; if (c >= '0' && c <= '9') continue; if (c == '-' && i != 0) continue; if (c == '+' && i != 0) continue; if (c == ':' && i != 0) continue; if (c == '_' && i != 0) continue; if (c == '.' && i != 0) continue; end = i; break; } String charset = mediaType.substring(st, end); return checkCharset(charset); } public static Body create(@NonNull String mediaType, @NonNull byte[] content) { return new Body(mediaType, content); } public static Body form(@NonNull final Map<String, String> form) { return form(form, "utf-8"); } public static Body form(@NonNull final Map<String, String> form, String charset) { String mediaType = "application/x-www-form-urlencoded;charset=" + checkCharset(charset); final StringBuilder sb = new StringBuilder(); for (String key : form.keySet()) { if (sb.length() > 0) sb.append("&"); sb.append(key).append("=").append(form.get(key)); } try { return new Body(mediaType, sb.toString().getBytes(charset)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static Body json(@NonNull final String json) { return json(json, "utf-8"); } public static Body json(@NonNull final String json, String charset) { String mediaType = "application/json;charset=" + checkCharset(charset); try { return new Body(mediaType, json.getBytes(charset)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } // public static RequestBody file(String mediaType, final File file) { // // return new RequestBody(mediaType, ); // } } private static String checkCharset(final String charset) { if (Charset.isSupported(charset)) return charset; throw new IllegalCharsetNameException(charset); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/subutil/src/main/java/com/blankj/subutil/util/http/Interceptor.java
lib/subutil/src/main/java/com/blankj/subutil/util/http/Interceptor.java
package com.blankj.subutil.util.http; import java.io.IOException; public interface Interceptor { Response intercept(Chain chain) throws IOException; }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/CommonApplication.java
lib/common/src/main/java/com/blankj/common/CommonApplication.java
package com.blankj.common; import com.blankj.base.BaseApplication; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/06/05 * desc : app about common * </pre> */ public class CommonApplication extends BaseApplication { @Override public void onCreate() { super.onCreate(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/fragment/CommonFragment.java
lib/common/src/main/java/com/blankj/common/fragment/CommonFragment.java
package com.blankj.common.fragment; import android.os.Bundle; import android.view.View; import com.blankj.base.BaseFragment; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.activity.CommonActivityItemsView; import com.blankj.common.item.CommonItem; import java.util.List; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/11/03 * desc : * </pre> */ public class CommonFragment extends BaseFragment { private CommonActivityItemsView mItemsView; /////////////////////////////////////////////////////////////////////////// // items view /////////////////////////////////////////////////////////////////////////// public CommonActivityItemsView bindItemsView() { return null; } public List<CommonItem> bindItems() { return null; } @CallSuper @Override public void initData(@Nullable Bundle bundle) { mItemsView = bindItemsView(); if (mItemsView == null) { List<CommonItem> items = bindItems(); if (items != null) { mItemsView = new CommonActivityItemsView(mActivity, items); } } } @Override public int bindLayout() { return View.NO_ID; } @Override public void setContentView() { if (mItemsView != null) { mContentView = mInflater.inflate(mItemsView.bindLayout(), null); } else { super.setContentView(); } } @CallSuper @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { if (mItemsView != null) { mItemsView.initView(); } } @Override public void doBusiness() { log("doBusiness"); } @Override public void onDebouncingClick(@NonNull View view) { } public CommonActivityItemsView getItemsView() { return mItemsView; } private BaseItemAdapter<CommonItem> mCommonItemAdapter; public void setCommonItems(RecyclerView rv, List<CommonItem> items) { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(items); rv.setAdapter(mCommonItemAdapter); rv.setLayoutManager(new LinearLayoutManager(mActivity)); rv.addItemDecoration(new RecycleViewDivider(mActivity, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateCommonItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateCommonItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } public BaseItemAdapter<CommonItem> getCommonItemAdapter() { return mCommonItemAdapter; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/activity/CommonActivityDrawerView.java
lib/common/src/main/java/com/blankj/common/activity/CommonActivityDrawerView.java
package com.blankj.common.activity; import android.content.Intent; import android.net.Uri; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import com.blankj.common.R; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.StringUtils; import com.google.android.material.navigation.NavigationView; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityDrawerView { public AppCompatActivity mBaseActivity; public DrawerLayout mBaseDrawerRootLayout; public FrameLayout mBaseDrawerContainerView; private NavigationView.OnNavigationItemSelectedListener mListener = new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == R.id.baseDrawerActionGitHub) { return goWeb(R.string.github); } else if (id == R.id.baseDrawerActionBlog) { return goWeb(R.string.blog); } return false; } }; public CommonActivityDrawerView(@NonNull AppCompatActivity activity) { mBaseActivity = activity; } public int bindLayout() { return R.layout.common_activity_drawer; } public View getContentView() { mBaseDrawerRootLayout = mBaseActivity.findViewById(R.id.baseDrawerRootLayout); mBaseDrawerContainerView = mBaseActivity.findViewById(R.id.baseDrawerContainerView); NavigationView nav = mBaseActivity.findViewById(R.id.baseDrawerNavView); nav.setNavigationItemSelectedListener(mListener); return mBaseDrawerContainerView; } private boolean goWeb(@StringRes int id) { return ActivityUtils.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(StringUtils.getString(id)))); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/activity/CommonActivity.java
lib/common/src/main/java/com/blankj/common/activity/CommonActivity.java
package com.blankj.common.activity; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.blankj.base.BaseActivity; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.dialog.CommonDialogLoading; import com.blankj.common.item.CommonItem; import com.blankj.swipepanel.SwipePanel; import com.blankj.utilcode.util.LanguageUtils; import com.blankj.utilcode.util.SizeUtils; import java.util.List; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/06/05 * desc : * </pre> */ public abstract class CommonActivity extends BaseActivity { private CommonActivityItemsView mItemsView; private CommonActivityTitleView mTitleView; private CommonActivityDrawerView mDrawerView; private CommonDialogLoading mDialogLoading; public View commonContentView; // @Override // protected void attachBaseContext(Context newBase) { // super.attachBaseContext(LanguageUtils.attachBaseContext(newBase)); // } /////////////////////////////////////////////////////////////////////////// // title view /////////////////////////////////////////////////////////////////////////// public boolean isSwipeBack() { return true; } @StringRes public int bindTitleRes() { return View.NO_ID; } public CharSequence bindTitle() { return ""; } public boolean isSupportScroll() { return true; } public CommonActivityTitleView bindTitleView() { return null; } /////////////////////////////////////////////////////////////////////////// // items view /////////////////////////////////////////////////////////////////////////// public CommonActivityItemsView bindItemsView() { return null; } public List<CommonItem> bindItems() { return null; } /////////////////////////////////////////////////////////////////////////// // drawer view /////////////////////////////////////////////////////////////////////////// public CommonActivityDrawerView bindDrawerView() { return null; } public boolean bindDrawer() { return false; } @CallSuper @Override public void initData(@Nullable Bundle bundle) { mTitleView = bindTitleView(); if (mTitleView == null) { int titleRes = bindTitleRes(); if (titleRes != View.NO_ID) { mTitleView = new CommonActivityTitleView(this, titleRes, isSupportScroll()); } else { CharSequence title = bindTitle(); if (!TextUtils.isEmpty(title)) { mTitleView = new CommonActivityTitleView(this, title, isSupportScroll()); } } } mItemsView = bindItemsView(); if (mItemsView == null) { List<CommonItem> items = bindItems(); if (items != null) { mItemsView = new CommonActivityItemsView(this, items); } } mDrawerView = bindDrawerView(); if (mDrawerView == null) { if (bindDrawer()) { mDrawerView = new CommonActivityDrawerView(this); } } if (mTitleView != null && mItemsView != null) { mTitleView.setIsSupportScroll(false); } findViewById(android.R.id.content).setBackgroundColor(getResources().getColor(R.color.lightGrayDark)); initSwipeBack(); } @Override public int bindLayout() { return View.NO_ID; } @Override public void setContentView() { if (mTitleView != null) { mContentView = LayoutInflater.from(this).inflate(mTitleView.bindLayout(), null); setContentView(mContentView); commonContentView = mTitleView.getContentView(); } else if (mDrawerView != null) { mContentView = LayoutInflater.from(this).inflate(mDrawerView.bindLayout(), null); setContentView(mContentView); commonContentView = mDrawerView.getContentView(); } else { if (mItemsView != null) { mContentView = LayoutInflater.from(this).inflate(mItemsView.bindLayout(), null); setContentView(mContentView); } else { super.setContentView(); } commonContentView = mContentView; return; } if (mItemsView != null) { LayoutInflater.from(this).inflate(mItemsView.bindLayout(), (ViewGroup) commonContentView); } else { if (bindLayout() > 0) { LayoutInflater.from(this).inflate(bindLayout(), (ViewGroup) commonContentView); } } } private void initSwipeBack() { if (isSwipeBack()) { final SwipePanel swipeLayout = new SwipePanel(this); swipeLayout.setLeftDrawable(R.drawable.common_back); swipeLayout.setLeftEdgeSize(SizeUtils.dp2px(16)); swipeLayout.setLeftSwipeColor(getResources().getColor(R.color.colorPrimary)); swipeLayout.wrapView(findViewById(android.R.id.content)); swipeLayout.setOnFullSwipeListener(new SwipePanel.OnFullSwipeListener() { @Override public void onFullSwipe(int direction) { swipeLayout.close(direction); finish(); } }); } } @CallSuper @Override public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) { if (mItemsView != null) { mItemsView.initView(); } } @Override public void doBusiness() { } @Override public void onDebouncingClick(@NonNull View view) { } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mTitleView != null) { return mTitleView.onOptionsItemSelected(item); } return super.onOptionsItemSelected(item); } public void showLoading() { showLoading(null); } public void showLoading(Runnable listener) { if (mDialogLoading != null) { return; } mDialogLoading = new CommonDialogLoading().init(this, listener); mDialogLoading.show(); } public void dismissLoading() { if (mDialogLoading != null) { mDialogLoading.dismiss(); mDialogLoading = null; } } public CommonActivityItemsView getItemsView() { return mItemsView; } public CommonActivityTitleView getTitleView() { return mTitleView; } public CommonActivityDrawerView getDrawerView() { return mDrawerView; } private BaseItemAdapter<CommonItem> mCommonItemAdapter; public void setCommonItems(RecyclerView rv, List<CommonItem> items) { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(items); rv.setAdapter(mCommonItemAdapter); rv.setLayoutManager(new LinearLayoutManager(this)); rv.addItemDecoration(new RecycleViewDivider(this, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateCommonItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateCommonItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } public BaseItemAdapter<CommonItem> getCommonItemAdapter() { return mCommonItemAdapter; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/activity/CommonActivityItemsView.java
lib/common/src/main/java/com/blankj/common/activity/CommonActivityItemsView.java
package com.blankj.common.activity; import com.blankj.base.rv.BaseItemAdapter; import com.blankj.base.rv.RecycleViewDivider; import com.blankj.common.R; import com.blankj.common.item.CommonItem; import java.util.List; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityItemsView { public AppCompatActivity mBaseActivity; private List<CommonItem> mItems; public BaseItemAdapter<CommonItem> mCommonItemAdapter; public RecyclerView mCommonItemRv; public CommonActivityItemsView(@NonNull AppCompatActivity activity, @NonNull List<CommonItem> items) { mBaseActivity = activity; mItems = items; } public int bindLayout() { return R.layout.common_item; } public void initView() { mCommonItemAdapter = new BaseItemAdapter<>(); mCommonItemAdapter.setItems(mItems); mCommonItemRv = mBaseActivity.findViewById(R.id.commonItemRv); mCommonItemRv.setAdapter(mCommonItemAdapter); mCommonItemRv.setLayoutManager(new LinearLayoutManager(mBaseActivity)); mCommonItemRv.addItemDecoration(new RecycleViewDivider(mBaseActivity, RecycleViewDivider.VERTICAL, R.drawable.common_item_divider)); } public void updateItems(List<CommonItem> data) { mCommonItemAdapter.setItems(data); mCommonItemAdapter.notifyDataSetChanged(); } public void updateItem(int position) { mCommonItemAdapter.notifyItemChanged(position); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/activity/CommonActivityTitleView.java
lib/common/src/main/java/com/blankj/common/activity/CommonActivityTitleView.java
package com.blankj.common.activity; import android.view.MenuItem; import android.view.View; import android.view.ViewStub; import android.widget.FrameLayout; import com.blankj.common.R; import com.blankj.utilcode.util.BarUtils; import com.blankj.utilcode.util.ColorUtils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/11/01 * desc : * </pre> */ public class CommonActivityTitleView { public AppCompatActivity mBaseActivity; public CharSequence mTitle; public boolean mIsSupportScroll; public CoordinatorLayout baseTitleRootLayout; public Toolbar baseTitleToolbar; public FrameLayout baseTitleContentView; public ViewStub mViewStub; public CommonActivityTitleView(@NonNull AppCompatActivity activity, @StringRes int resId) { this(activity, activity.getString(resId), true); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @NonNull CharSequence title) { this(activity, title, true); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @StringRes int resId, boolean isSupportScroll) { this(activity, activity.getString(resId), isSupportScroll); } public CommonActivityTitleView(@NonNull AppCompatActivity activity, @NonNull CharSequence title, boolean isSupportScroll) { mBaseActivity = activity; mTitle = title; mIsSupportScroll = isSupportScroll; } public void setIsSupportScroll(boolean isSupportScroll) { mIsSupportScroll = isSupportScroll; } public int bindLayout() { return R.layout.common_activity_title; } public View getContentView() { baseTitleRootLayout = mBaseActivity.findViewById(R.id.baseTitleRootLayout); baseTitleToolbar = mBaseActivity.findViewById(R.id.baseTitleToolbar); if (mIsSupportScroll) { mViewStub = mBaseActivity.findViewById(R.id.baseTitleStubScroll); } else { mViewStub = mBaseActivity.findViewById(R.id.baseTitleStubNoScroll); } mViewStub.setVisibility(View.VISIBLE); baseTitleContentView = mBaseActivity.findViewById(R.id.commonTitleContentView); setTitleBar(); BarUtils.setStatusBarColor(mBaseActivity, ColorUtils.getColor(R.color.colorPrimary)); BarUtils.addMarginTopEqualStatusBarHeight(baseTitleRootLayout); return baseTitleContentView; } private void setTitleBar() { mBaseActivity.setSupportActionBar(baseTitleToolbar); ActionBar titleBar = mBaseActivity.getSupportActionBar(); if (titleBar != null) { titleBar.setDisplayHomeAsUpEnabled(true); titleBar.setTitle(mTitle); } } public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { mBaseActivity.finish(); return true; } return mBaseActivity.onOptionsItemSelected(item); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/dialog/CommonDialogContent.java
lib/common/src/main/java/com/blankj/common/dialog/CommonDialogContent.java
package com.blankj.common.dialog; import android.content.Context; import android.text.TextUtils; import android.util.Pair; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TextView; import com.blankj.base.dialog.BaseDialogFragment; import com.blankj.base.dialog.DialogLayoutCallback; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/11/18 * desc : * </pre> */ public class CommonDialogContent extends BaseDialogFragment { private RelativeLayout cdcTitleRl; private TextView cdcTitleTv; private RelativeLayout cdcContentRl; private TextView cdcContentTv; private RelativeLayout cdcBottomRl; private TextView cdcBottomPositiveTv; private TextView cdcBottomNegativeTv; public CommonDialogContent init(Context context, final CharSequence title, final CharSequence content, final Pair<CharSequence, View.OnClickListener> positiveBtnAction, final Pair<CharSequence, View.OnClickListener> negativeBtnAction) { super.init(context, new DialogLayoutCallback() { @Override public int bindTheme() { return R.style.CommonContentDialogStyle; } @Override public int bindLayout() { return R.layout.common_dialog_content; } @Override public void initView(final BaseDialogFragment dialog, View contentView) { cdcTitleRl = contentView.findViewById(R.id.cdcTitleRl); cdcTitleTv = contentView.findViewById(R.id.cdcTitleTv); cdcContentRl = contentView.findViewById(R.id.cdcContentRl); cdcContentTv = contentView.findViewById(R.id.cdcContentTv); cdcBottomRl = contentView.findViewById(R.id.cdcBottomRl); cdcBottomPositiveTv = contentView.findViewById(R.id.cdcBottomPositiveTv); cdcBottomNegativeTv = contentView.findViewById(R.id.cdcBottomNegativeTv); if (TextUtils.isEmpty(title)) { cdcTitleRl.setVisibility(View.GONE); } else { cdcTitleTv.setText(title); } if (TextUtils.isEmpty(content)) { cdcContentRl.setVisibility(View.GONE); } else { cdcContentTv.setText(content); } if (positiveBtnAction == null && negativeBtnAction == null) { cdcBottomRl.setVisibility(View.GONE); } else { if (positiveBtnAction != null) { ClickUtils.applyPressedBgDark(cdcBottomPositiveTv); cdcBottomPositiveTv.setText(positiveBtnAction.first); cdcBottomPositiveTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); positiveBtnAction.second.onClick(v); } }); } if (negativeBtnAction != null) { ClickUtils.applyPressedBgDark(cdcBottomNegativeTv); cdcBottomNegativeTv.setText(negativeBtnAction.first); cdcBottomNegativeTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); negativeBtnAction.second.onClick(v); } }); } } } @Override public void setWindowStyle(Window window) { } @Override public void onCancel(BaseDialogFragment dialog) { } @Override public void onDismiss(BaseDialogFragment dialog) { } }); return this; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/dialog/CommonDialogLoading.java
lib/common/src/main/java/com/blankj/common/dialog/CommonDialogLoading.java
package com.blankj.common.dialog; import android.content.Context; import android.graphics.Color; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.blankj.base.dialog.BaseDialogFragment; import com.blankj.base.dialog.DialogLayoutCallback; import com.blankj.common.R; import com.blankj.utilcode.util.BarUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/29 * desc : * </pre> */ public class CommonDialogLoading extends BaseDialogFragment { public CommonDialogLoading init(Context context, final Runnable onCancelListener) { super.init(context, new DialogLayoutCallback() { @Override public int bindTheme() { return R.style.CommonLoadingDialogStyle; } @Override public int bindLayout() { return R.layout.common_dialog_loading; } @Override public void initView(BaseDialogFragment dialog, View contentView) { if (onCancelListener == null) { setCancelable(false); } else { setCancelable(true); } } @Override public void setWindowStyle(final Window window) { window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); BarUtils.setStatusBarColor(window, Color.TRANSPARENT); } @Override public void onCancel(BaseDialogFragment dialog) { if (onCancelListener != null) { onCancelListener.run(); } } @Override public void onDismiss(BaseDialogFragment dialog) { } }); return this; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/view/RotateView.java
lib/common/src/main/java/com/blankj/common/view/RotateView.java
package com.blankj.common.view; import android.animation.ObjectAnimator; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2020/03/28 * desc : * </pre> */ public class RotateView extends View { private ObjectAnimator headerAnimator; public RotateView(Context context) { this(context, null); } public RotateView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public RotateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onVisibilityChanged(@NonNull View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (headerAnimator == null) { initAnimator(); } if (visibility == VISIBLE) { headerAnimator.start(); } else { headerAnimator.end(); } } private void initAnimator() { headerAnimator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f); headerAnimator.setRepeatCount(ObjectAnimator.INFINITE); headerAnimator.setInterpolator(new LinearInterpolator()); headerAnimator.setRepeatMode(ObjectAnimator.RESTART); headerAnimator.setDuration(1000); headerAnimator.start(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItem.java
lib/common/src/main/java/com/blankj/common/item/CommonItem.java
package com.blankj.common.item; import com.blankj.base.rv.BaseItem; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ColorUtils; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/25 * desc : * </pre> */ public class CommonItem<T extends BaseItem> extends BaseItem<T> { private int backgroundColor = ColorUtils.getColor(R.color.lightGray); public CommonItem(int layoutId) { super(layoutId); } @CallSuper @Override public void bind(@NonNull final ItemViewHolder holder, int position) { holder.itemView.setBackgroundColor(backgroundColor); } public CommonItem<T> setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; return this; } public int getBackgroundColor() { return backgroundColor; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItemImage.java
lib/common/src/main/java/com/blankj/common/item/CommonItemImage.java
package com.blankj.common.item; import android.widget.ImageView; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/31 * desc : * </pre> */ public class CommonItemImage extends CommonItem { private CharSequence mTitle; private Utils.Consumer<ImageView> mSetImageConsumer; public CommonItemImage(@StringRes int title, @NonNull Utils.Consumer<ImageView> setImageConsumer) { this(StringUtils.getString(title), setImageConsumer); } public CommonItemImage(@NonNull CharSequence title, @NonNull Utils.Consumer<ImageView> setImageConsumer) { super(R.layout.common_item_title_image); mTitle = title; mSetImageConsumer = setImageConsumer; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); titleTv.setText(mTitle); ImageView commonItemIv = holder.findViewById(R.id.commonItemIv); mSetImageConsumer.accept(commonItemIv); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItemTitle.java
lib/common/src/main/java/com/blankj/common/item/CommonItemTitle.java
package com.blankj.common.item; import android.graphics.Color; import android.view.Gravity; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/31 * desc : * </pre> */ public class CommonItemTitle extends CommonItem { private CharSequence mTitle; private Utils.Supplier<CharSequence> mGetTitleSupplier; private boolean mIsTitleCenter; private CharSequence mContent; public CommonItemTitle(@NonNull Utils.Supplier<CharSequence> getTitleSupplier, boolean isTitleCenter) { super(R.layout.common_item_title_content); mTitle = mGetTitleSupplier.get(); mGetTitleSupplier = getTitleSupplier; mIsTitleCenter = isTitleCenter; } public CommonItemTitle(@StringRes int title, boolean isTitleCenter) { this(StringUtils.getString(title), isTitleCenter); } public CommonItemTitle(@NonNull CharSequence title, boolean isTitleCenter) { super(R.layout.common_item_title_content); mTitle = title; mIsTitleCenter = isTitleCenter; } public CommonItemTitle(@NonNull CharSequence title, CharSequence content) { super(R.layout.common_item_title_content); mTitle = title; mContent = content; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); if (mGetTitleSupplier != null) { mTitle = mGetTitleSupplier.get(); } final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (isViewType(R.layout.common_item_title_content)) { if (mIsTitleCenter) { holder.itemView.setBackgroundColor(Color.TRANSPARENT); titleTv.setGravity(Gravity.CENTER_HORIZONTAL); titleTv.getPaint().setFakeBoldText(true); } else { titleTv.setGravity(Gravity.START); titleTv.getPaint().setFakeBoldText(false); } } } public void setTitle(CharSequence title) { setTitle(title, true); } public void setContent(CharSequence content) { setContent(content, true); } public void setTitle(CharSequence title, boolean isUpdate) { mTitle = title; if (isUpdate) { update(); } } public void setContent(CharSequence content, boolean isUpdate) { mContent = content; if (isUpdate) { update(); } } public CharSequence getTitle() { return mTitle; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItemSeekBar.java
lib/common/src/main/java/com/blankj/common/item/CommonItemSeekBar.java
package com.blankj.common.item; import android.view.MotionEvent; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.StringUtils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/31 * desc : * </pre> */ public class CommonItemSeekBar extends CommonItem { private CharSequence mTitle; private CharSequence mContent; private int mMaxProgress; private int mCurProgress; private ProgressListener mProgressListener; public CommonItemSeekBar(@StringRes int title, int maxProgress, @NonNull ProgressListener listener) { this(StringUtils.getString(title), maxProgress, listener); } public CommonItemSeekBar(@NonNull CharSequence title, int maxProgress, @NonNull ProgressListener listener) { super(R.layout.common_item_title_seekbar); mTitle = title; mMaxProgress = maxProgress; mCurProgress = listener.getCurValue(); mProgressListener = listener; mContent = String.valueOf(mCurProgress); } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); final SeekBar seekBar = holder.findViewById(R.id.commonItemSb); seekBar.setMax(mMaxProgress); seekBar.setProgress(mCurProgress); holder.itemView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return seekBar.dispatchTouchEvent(event); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mProgressListener.onProgressChanged(seekBar, progress, fromUser); int curValue = mProgressListener.getCurValue(); mCurProgress = curValue; contentTv.setText(String.valueOf(curValue)); seekBar.setProgress(curValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) { mProgressListener.onStartTrackingTouch(seekBar); } @Override public void onStopTrackingTouch(SeekBar seekBar) { mProgressListener.onStopTrackingTouch(seekBar); } }); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } public static abstract class ProgressListener implements SeekBar.OnSeekBarChangeListener { public abstract int getCurValue(); @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItemClick.java
lib/common/src/main/java/com/blankj/common/item/CommonItemClick.java
package com.blankj.common.item; import android.view.View; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/31 * desc : * </pre> */ public class CommonItemClick extends CommonItem<CommonItemClick> { private CharSequence mTitle; private CharSequence mContent; private boolean mIsJump; public CommonItemClick(@StringRes int title) { this(StringUtils.getString(title), "", false, null); } public CommonItemClick(@NonNull CharSequence title) { this(title, "", false, null); } public CommonItemClick(@StringRes int title, boolean isJump) { this(StringUtils.getString(title), "", isJump); } public CommonItemClick(@NonNull CharSequence title, boolean isJump) { this(title, "", isJump, null); } public CommonItemClick(@StringRes int title, CharSequence content) { this(StringUtils.getString(title), content, false, null); } public CommonItemClick(@NonNull CharSequence title, CharSequence content) { this(title, content, false, null); } public CommonItemClick(@StringRes int title, CharSequence content, boolean isJump) { this(StringUtils.getString(title), content, isJump); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, boolean isJump) { this(title, content, isJump, null); } public CommonItemClick(@StringRes int title, final Runnable simpleClickListener) { this(StringUtils.getString(title), "", false, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, final Runnable simpleClickListener) { this(title, "", false, simpleClickListener); } public CommonItemClick(@StringRes int title, boolean isJump, final Runnable simpleClickListener) { this(StringUtils.getString(title), "", isJump, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, boolean isJump, final Runnable simpleClickListener) { this(title, "", isJump, simpleClickListener); } public CommonItemClick(@StringRes int title, CharSequence content, final Runnable simpleClickListener) { this(StringUtils.getString(title), content, false, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, final Runnable simpleClickListener) { this(title, content, false, simpleClickListener); } public CommonItemClick(@StringRes int title, CharSequence content, boolean isJump, final Runnable simpleClickListener) { this(StringUtils.getString(title), content, isJump, simpleClickListener); } public CommonItemClick(@NonNull CharSequence title, CharSequence content, boolean isJump, final Runnable simpleClickListener) { super(R.layout.common_item_title_click); mTitle = title; mContent = content; mIsJump = isJump; if (simpleClickListener == null) return; setOnItemClickListener(new OnItemClickListener<CommonItemClick>() { @Override public void onItemClick(ItemViewHolder holder, CommonItemClick item, int position) { if (simpleClickListener != null) { simpleClickListener.run(); } } }); } public CommonItemClick setOnClickUpdateContentListener(@NonNull final Utils.Supplier<CharSequence> supplier) { setOnItemClickListener(new OnItemClickListener<CommonItemClick>() { @Override public void onItemClick(ItemViewHolder holder, CommonItemClick item, int position) { item.mContent = supplier.get(); update(); } }); return this; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { super.bind(holder, position); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); ClickUtils.applyPressedBgDark(holder.itemView); holder.findViewById(R.id.commonItemGoIv).setVisibility(mIsJump ? View.VISIBLE : View.GONE); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/common/src/main/java/com/blankj/common/item/CommonItemSwitch.java
lib/common/src/main/java/com/blankj/common/item/CommonItemSwitch.java
package com.blankj.common.item; import android.annotation.SuppressLint; import android.view.MotionEvent; import android.view.View; import android.widget.Switch; import android.widget.TextView; import com.blankj.base.rv.ItemViewHolder; import com.blankj.common.R; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.Utils; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/10/31 * desc : * </pre> */ public class CommonItemSwitch extends CommonItem { private CharSequence mTitle; private CharSequence mContent; private boolean mState; private Utils.Supplier<Boolean> mGetStateSupplier; private Utils.Consumer<Boolean> mSetStateConsumer; public CommonItemSwitch(@StringRes int title, @NonNull Utils.Supplier<Boolean> getStateSupplier, @NonNull Utils.Consumer<Boolean> setStateConsumer) { this(StringUtils.getString(title), getStateSupplier, setStateConsumer); } public CommonItemSwitch(@NonNull CharSequence title, @NonNull Utils.Supplier<Boolean> getStateSupplier, @NonNull Utils.Consumer<Boolean> setStateConsumer) { super(R.layout.common_item_title_switch); mTitle = title; mGetStateSupplier = getStateSupplier; mSetStateConsumer = setStateConsumer; mState = getStateSupplier.get(); mContent = String.valueOf(mState); } @SuppressLint("ClickableViewAccessibility") @Override public void bind(@NonNull final ItemViewHolder holder, int position) { super.bind(holder, position); ClickUtils.applyPressedBgDark(holder.itemView); final TextView titleTv = holder.findViewById(R.id.commonItemTitleTv); final TextView contentTv = holder.findViewById(R.id.commonItemContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); final Switch switchView = holder.findViewById(R.id.commonItemSwitch); switchView.setChecked(mState); switchView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { holder.itemView.onTouchEvent(event); return true; } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mSetStateConsumer.accept(!mState); mState = mGetStateSupplier.get(); contentTv.setText(String.valueOf(mState)); switchView.setChecked(mState); } }); } public void setTitle(CharSequence title) { mTitle = title; update(); } public CharSequence getTitle() { return mTitle; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug-no-op/src/main/java/com/blankj/utildebug/DebugUtils.java
lib/utildebug-no-op/src/main/java/com/blankj/utildebug/DebugUtils.java
package com.blankj.utildebug; import com.blankj.utildebug.debug.IDebug; import java.util.List; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/28 * desc : utils about debug * </pre> */ public class DebugUtils { private DebugUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } public static void setIconId(final int icon) { } public static void addDebugs(final List<IDebug> debugs) { } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug-no-op/src/main/java/com/blankj/utildebug/debug/IDebug.java
lib/utildebug-no-op/src/main/java/com/blankj/utildebug/debug/IDebug.java
package com.blankj.utildebug.debug; import android.content.Context; import android.view.View; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/28 * desc : * </pre> */ public interface IDebug { void onAppCreate(Context context); int getCategory(); int getIcon(); int getName(); void onClick(View view); int TOOLS = 0; int PERFORMANCE = 1; int UI = 2; int BIZ = 3; }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/DebugUtils.java
lib/utildebug/src/main/java/com/blankj/utildebug/DebugUtils.java
package com.blankj.utildebug; import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.view.ViewGroup; import android.view.ViewParent; import com.blankj.utilcode.util.Utils; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.icon.DebugIcon; import com.blankj.utildebug.menu.DebugMenu; import java.util.ArrayList; import java.util.List; import androidx.annotation.DrawableRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/28 * desc : utils about debug * </pre> */ public class DebugUtils { private DebugUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } static { List<IDebug> debugList = new ArrayList<>(); AbsToolDebug.addToolDebugs(debugList); DebugMenu.getInstance().setDebugs(debugList); getApp().registerActivityLifecycleCallbacks(ActivityLifecycleImpl.instance); } public static void setIconId(final @DrawableRes int icon) { DebugIcon.getInstance().setIconId(icon); } public static void addDebugs(final List<IDebug> debugs) { DebugMenu.getInstance().addDebugs(debugs); } public static Application getApp() { return Utils.getApp(); } static class ActivityLifecycleImpl implements Application.ActivityLifecycleCallbacks { private static ActivityLifecycleImpl instance = new ActivityLifecycleImpl(); private int mConfigCount = 0; private ViewGroup.LayoutParams mParams = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } @Override public void onActivityStarted(Activity activity) { if (mConfigCount < 0) { ++mConfigCount; } } @Override public void onActivityResumed(Activity activity) { ViewParent parent = DebugIcon.getInstance().getParent(); if (parent != null) { ((ViewGroup) parent).removeView(DebugIcon.getInstance()); } ((ViewGroup) activity.findViewById(android.R.id.content)).addView(DebugIcon.getInstance(), mParams); } @Override public void onActivityPaused(Activity activity) { ((ViewGroup) activity.findViewById(android.R.id.content)).removeView(DebugIcon.getInstance()); } @Override public void onActivityStopped(Activity activity) { if (activity.isChangingConfigurations()) { --mConfigCount; } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/icon/DebugIcon.java
lib/utildebug/src/main/java/com/blankj/utildebug/icon/DebugIcon.java
package com.blankj.utildebug.icon; import android.content.res.Configuration; import android.os.Build; import android.view.MotionEvent; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import com.blankj.utilcode.util.BarUtils; import com.blankj.utilcode.util.PermissionUtils; import com.blankj.utilcode.util.ToastUtils; import com.blankj.utilcode.util.TouchUtils; import com.blankj.utildebug.DebugUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.config.DebugConfig; import com.blankj.utildebug.helper.ShadowHelper; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/26 * desc : * </pre> */ public class DebugIcon extends RelativeLayout { private static final DebugIcon INSTANCE = new DebugIcon(); private int mIconId; public static DebugIcon getInstance() { return INSTANCE; } public static void setVisibility(boolean isShow) { if (INSTANCE == null) return; INSTANCE.setVisibility(isShow ? VISIBLE : GONE); } public DebugIcon() { super(DebugUtils.getApp()); inflate(getContext(), R.layout.du_debug_icon, this); ShadowHelper.applyDebugIcon(this); TouchUtils.setOnTouchListener(this, new TouchUtils.OnTouchUtilsListener() { private int rootViewWidth; private int rootViewHeight; private int viewWidth; private int viewHeight; private int statusBarHeight; @Override public boolean onDown(View view, int x, int y, MotionEvent event) { viewWidth = view.getWidth(); viewHeight = view.getHeight(); View contentView = view.getRootView().findViewById(android.R.id.content); rootViewWidth = contentView.getWidth(); rootViewHeight = contentView.getHeight(); statusBarHeight = BarUtils.getStatusBarHeight(); processScale(view, true); return true; } @Override public boolean onMove(View view, int direction, int x, int y, int dx, int dy, int totalX, int totalY, MotionEvent event) { view.setX(Math.min(Math.max(0, view.getX() + dx), rootViewWidth - viewWidth)); view.setY(Math.min(Math.max(statusBarHeight, view.getY() + dy), rootViewHeight - viewHeight)); return true; } @Override public boolean onStop(View view, int direction, int x, int y, int totalX, int totalY, int vx, int vy, MotionEvent event) { stick2HorizontalSide(view); processScale(view, false); return true; } private void stick2HorizontalSide(View view) { view.animate() .setInterpolator(new DecelerateInterpolator()) .translationX(view.getX() + viewWidth / 2f > rootViewWidth / 2f ? rootViewWidth - viewWidth : 0) .setDuration(100) .withEndAction(new Runnable() { @Override public void run() { savePosition(); } }) .start(); } private void processScale(final View view, boolean isDown) { float value = isDown ? 1 - 0.1f : 1; view.animate() .scaleX(value) .scaleY(value) .setDuration(100) .start(); } }); setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PermissionUtils.requestDrawOverlays(new PermissionUtils.SimpleCallback() { @Override public void onGranted() { DebugMenu.getInstance().show(); } @Override public void onDenied() { ToastUtils.showLong(R.string.de_permission_tips); } }); } else { DebugMenu.getInstance().show(); } } }); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); wrapPosition(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); savePosition(); } private void savePosition() { DebugConfig.saveViewX(this, (int) getX()); DebugConfig.saveViewY(this, (int) getY()); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); wrapPosition(); } private void wrapPosition() { post(new Runnable() { @Override public void run() { View contentView = getRootView().findViewById(android.R.id.content); if (contentView == null) return; setX(DebugConfig.getViewX(DebugIcon.this)); setY(DebugConfig.getViewY(DebugIcon.this, contentView.getHeight() / 3)); setX(getX() + getWidth() / 2f > contentView.getWidth() / 2f ? contentView.getWidth() - getWidth() : 0); } }); } public void setIconId(final int iconId) { ImageView debugPanelIconIv = findViewById(R.id.debugIconIv); debugPanelIconIv.setImageResource(mIconId); } public int getIconId() { return mIconId; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/BaseItemAdapter.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/BaseItemAdapter.java
package com.blankj.utildebug.base.rv; import android.view.ViewGroup; import java.util.Collections; import java.util.Comparator; import java.util.List; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/08/22 * desc : * </pre> */ public class BaseItemAdapter<Item extends BaseItem> extends RecyclerView.Adapter<ItemViewHolder> { public List<Item> mItems; private RecyclerView mRecyclerView; public BaseItemAdapter() { this(false); } public BaseItemAdapter(boolean hasStableIds) { setHasStableIds(hasStableIds); } @Override public final int getItemViewType(int position) { Item item = mItems.get(position); item.mAdapter = this; return item.getViewType(); } @Override public long getItemId(int position) { return mItems.get(position).getItemId(); } @NonNull @Override public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return Item.onCreateViewHolder(parent, viewType); } @Override public final void onBindViewHolder(@NonNull ItemViewHolder holder, int position) { mItems.get(position).bind(holder, position); } @Override public int getItemCount() { return mItems.size(); } @Override public void onViewRecycled(@NonNull ItemViewHolder holder) { super.onViewRecycled(holder); int position = holder.getAdapterPosition(); if (position < 0 || position >= mItems.size()) { return; } mItems.get(position).onViewRecycled(holder, position); } @Override public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); mRecyclerView = recyclerView; } public RecyclerView getRecyclerView() { return mRecyclerView; } public void setItems(@NonNull final List<Item> items) { mItems = items; } public List<Item> getItems() { return Collections.unmodifiableList(mItems); } public Item getItem(@IntRange(from = 0) final int position) { return mItems.get(position); } public boolean isEmpty() { return mItems.isEmpty(); } /////////////////////////////////////////////////////////////////////////// // id /////////////////////////////////////////////////////////////////////////// public Item getItemById(final long id) { int itemIndex = getItemIndexById(id); if (itemIndex != -1) { return mItems.get(itemIndex); } else { return null; } } public int getItemIndexById(final long id) { for (int i = 0; i < mItems.size(); i++) { if (getItemId(i) == id) { return i; } } return -1; } public boolean hasItemWithId(final long id) { return getItemIndexById(id) != -1; } public int replaceItemById(final long id, @NonNull final Item item) { return replaceItemById(id, item, false); } public int replaceItemById(final long id, @NonNull final Item item, boolean notifyChanged) { int itemIndex = getItemIndexById(id); if (itemIndex != -1) { replaceItem(itemIndex, item, notifyChanged); } return itemIndex; } public int removeItemById(final long id) { return removeItemById(id, false); } public int removeItemById(final long id, boolean notifyRemoved) { for (int i = 0; i < mItems.size(); i++) { if (getItemId(i) == id) { removeItem(i, notifyRemoved); return i; } } return -1; } /////////////////////////////////////////////////////////////////////////// // operate /////////////////////////////////////////////////////////////////////////// public void updateItem(@NonNull final Item item) { int itemIndex = mItems.indexOf(item); if (itemIndex != -1) { notifyItemChanged(itemIndex); } } public void updateItem(@IntRange(from = 0) final int index) { notifyItemChanged(index); } public void addItem(@NonNull final Item item) { addItem(item, false); } public void addItem(@NonNull final Item item, boolean notifyInserted) { mItems.add(item); if (notifyInserted) notifyItemInserted(mItems.size() - 1); } public void addItem(@IntRange(from = 0) final int index, @NonNull final Item item) { addItem(index, item, false); } public void addItem(@IntRange(from = 0) final int index, @NonNull final Item item, boolean notifyInserted) { mItems.add(index, item); if (notifyInserted) notifyItemInserted(index); } public void addItems(@NonNull final List<Item> items) { addItems(items, false); } public void addItems(@NonNull final List<Item> items, boolean notifyInserted) { mItems.addAll(items); if (notifyInserted) notifyItemRangeInserted(mItems.size() - items.size() - 1, items.size()); } public void addItems(@IntRange(from = 0) final int index, @NonNull final List<Item> items) { addItems(index, items, false); } public void addItems(@IntRange(from = 0) final int index, @NonNull final List<Item> items, boolean notifyInserted) { mItems.addAll(index, items); if (notifyInserted) notifyItemRangeInserted(index, items.size()); } public void swapItem(@IntRange(from = 0) final int firstIndex, @IntRange(from = 0) final int secondIndex) { swapItem(firstIndex, secondIndex, false); } public void swapItem(@IntRange(from = 0) final int firstIndex, @IntRange(from = 0) final int secondIndex, boolean notifyMoved) { Collections.swap(mItems, firstIndex, secondIndex); if (notifyMoved) notifyItemMoved(firstIndex, secondIndex); } public Item replaceItem(@IntRange(from = 0) final int index, @NonNull final Item item) { return replaceItem(index, item, false); } public Item replaceItem(@IntRange(from = 0) final int index, @NonNull final Item item, boolean notifyChanged) { Item prevItem = mItems.set(index, item); if (notifyChanged) notifyItemChanged(index); return prevItem; } public boolean replaceItems(@NonNull final List<Item> items) { return replaceItems(items, false); } public boolean replaceItems(@NonNull final List<Item> items, boolean notifyChanged) { mItems.clear(); boolean added = mItems.addAll(items); if (notifyChanged) notifyDataSetChanged(); return added; } public Item removeItem(@IntRange(from = 0) final int index) { return removeItem(index, false); } public Item removeItem(@IntRange(from = 0) final int index, boolean notifyRemoved) { Item removedItem = mItems.remove(index); if (notifyRemoved) notifyItemRemoved(index); return removedItem; } public int removeItem(@NonNull final Item item) { return removeItem(item, false); } public int removeItem(@NonNull final Item item, boolean notifyRemoved) { int itemIndex = mItems.indexOf(item); if (itemIndex != -1) { mItems.remove(itemIndex); if (notifyRemoved) notifyItemRemoved(itemIndex); } return itemIndex; } public void clear() { clear(false); } public void clear(boolean notifyDataSetChanged) { mItems.clear(); if (notifyDataSetChanged) notifyDataSetChanged(); } public void sortItems(@NonNull final Comparator<Item> comparator) { sortItems(comparator, false); } public void sortItems(@NonNull final Comparator<Item> comparator, boolean notifyDataSetChanged) { Collections.sort(mItems, comparator); if (notifyDataSetChanged) notifyDataSetChanged(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/RecycleViewDivider.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/RecycleViewDivider.java
package com.blankj.utildebug.base.rv; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/08/17 * desc : * </pre> */ public class RecycleViewDivider extends RecyclerView.ItemDecoration { public static final int HORIZONTAL = LinearLayout.HORIZONTAL; public static final int VERTICAL = LinearLayout.VERTICAL; protected Drawable mDivider; protected int mOrientation; protected boolean mShowFooterDivider; protected final Rect mBounds = new Rect(); public RecycleViewDivider(Context context, int orientation, @DrawableRes int resId) { this(context, orientation, resId, false); } public RecycleViewDivider(Context context, int orientation, @NonNull Drawable divider) { this(context, orientation, divider, false); } public RecycleViewDivider(Context context, int orientation, @DrawableRes int resId, boolean showFooterDivider) { this(context, orientation, ContextCompat.getDrawable(context, resId), showFooterDivider); } public RecycleViewDivider(Context context, int orientation, @NonNull Drawable divider, boolean showFooterDivider) { setOrientation(orientation); mDivider = divider; mShowFooterDivider = showFooterDivider; } private void setOrientation(int orientation) { if (orientation != HORIZONTAL && orientation != VERTICAL) { throw new IllegalArgumentException( "Invalid orientation. It should be either HORIZONTAL or VERTICAL"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if (parent.getLayoutManager() == null) { return; } if (mOrientation == VERTICAL) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } @SuppressLint("NewApi") protected void drawVertical(Canvas canvas, RecyclerView parent) { canvas.save(); final int left; final int right; if (parent.getClipToPadding()) { left = parent.getPaddingLeft(); right = parent.getWidth() - parent.getPaddingRight(); canvas.clipRect(left, parent.getPaddingTop(), right, parent.getHeight() - parent.getPaddingBottom()); } else { left = 0; right = parent.getWidth(); } final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { if (i == childCount - 1 && !mShowFooterDivider) continue; final View child = parent.getChildAt(i); parent.getDecoratedBoundsWithMargins(child, mBounds); final int bottom = mBounds.bottom + Math.round(ViewCompat.getTranslationY(child)); final int top = bottom - mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(canvas); } canvas.restore(); } @SuppressLint("NewApi") protected void drawHorizontal(Canvas canvas, RecyclerView parent) { canvas.save(); final int top; final int bottom; if (parent.getClipToPadding()) { top = parent.getPaddingTop(); bottom = parent.getHeight() - parent.getPaddingBottom(); canvas.clipRect(parent.getPaddingLeft(), top, parent.getWidth() - parent.getPaddingRight(), bottom); } else { top = 0; bottom = parent.getHeight(); } final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { if (i == childCount - 1 && !mShowFooterDivider) continue; final View child = parent.getChildAt(i); parent.getLayoutManager().getDecoratedBoundsWithMargins(child, mBounds); final int right = mBounds.right + Math.round(ViewCompat.getTranslationX(child)); final int left = right - mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(canvas); } canvas.restore(); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if (mOrientation == VERTICAL) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/BaseItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/BaseItem.java
package com.blankj.utildebug.base.rv; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2019/03/16 * desc : * </pre> */ public abstract class BaseItem<T extends BaseItem> { private static final SparseIntArray LAYOUT_SPARSE_ARRAY = new SparseIntArray(); private static final SparseArray<View> VIEW_SPARSE_ARRAY = new SparseArray<>(); static ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int layoutByType = LAYOUT_SPARSE_ARRAY.get(viewType, -1); if (layoutByType != -1) { return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(layoutByType, parent, false)); } View viewByType = VIEW_SPARSE_ARRAY.get(viewType); if (viewByType != null) { return new ItemViewHolder(viewByType); } throw new RuntimeException("onCreateViewHolder: get holder from view type failed."); } public abstract void bind(@NonNull final ItemViewHolder holder, final int position); public void onViewRecycled(@NonNull final ItemViewHolder holder, final int position) {/**/} public long getItemId() { return RecyclerView.NO_ID; } private int viewType; BaseItemAdapter<T> mAdapter; public BaseItem(@LayoutRes int layoutId) { viewType = getViewTypeByLayoutId(layoutId); LAYOUT_SPARSE_ARRAY.put(viewType, layoutId); } public BaseItem(@NonNull View view) { viewType = getViewTypeByView(view); VIEW_SPARSE_ARRAY.put(viewType, view); } public int getViewType() { return viewType; } public BaseItemAdapter<T> getAdapter() { return mAdapter; } public boolean isViewType(@LayoutRes int layoutId) { return viewType == getViewTypeByLayoutId(layoutId); } public boolean isViewType(@NonNull View view) { return viewType == getViewTypeByView(view); } private int getViewTypeByLayoutId(@LayoutRes int layoutId) { return layoutId + getClass().hashCode(); } private int getViewTypeByView(@NonNull View view) { return view.hashCode() + getClass().hashCode(); } public void update() { //noinspection unchecked getAdapter().updateItem((T) this); } public int getIndex() { //noinspection SuspiciousMethodCalls return getAdapter().getItems().indexOf(this); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/ItemViewHolder.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/rv/ItemViewHolder.java
package com.blankj.utildebug.base.rv; import android.util.SparseArray; import android.view.View; import androidx.annotation.IdRes; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/08/22 * desc : * </pre> */ public class ItemViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> viewArray = new SparseArray<>(); public ItemViewHolder(View itemView) { super(itemView); } @SuppressWarnings("unchecked") public <T extends View> T findViewById(@IdRes final int viewId) { View view = viewArray.get(viewId); if (view == null) { view = itemView.findViewById(viewId); viewArray.put(viewId, view); } return (T) view; } public void setOnClickListener(@IdRes final int viewId, View.OnClickListener listener) { findViewById(viewId).setOnClickListener(listener); } public void setOnLongClickListener(@IdRes final int viewId, View.OnLongClickListener listener) { findViewById(viewId).setOnLongClickListener(listener); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/drawable/PolygonDrawable.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/drawable/PolygonDrawable.java
package com.blankj.utildebug.base.drawable; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class PolygonDrawable extends Drawable { private Paint mPaint; private int mNum; public PolygonDrawable(int num, int color) { mNum = num; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(color); } @Override public void draw(@NonNull Canvas canvas) { if (mNum < 3) return; final Rect rect = getBounds(); float r = rect.right / 2; float x = r; float y = r; Path path = new Path(); for (int i = 0; i <= mNum; i++) { float alpha = Double.valueOf(((2f / mNum) * i - 0.5) * Math.PI).floatValue(); float nextX = x + Double.valueOf(r * Math.cos(alpha)).floatValue(); float nextY = y + Double.valueOf(r * Math.sin(alpha)).floatValue(); if (i == 0) { path.moveTo(nextX, nextY); } else { path.lineTo(nextX, nextY); } } canvas.drawPath(path, mPaint); } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { } @Override public int getOpacity() { return PixelFormat.OPAQUE; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatEditText.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatEditText.java
package com.blankj.utildebug.base.view; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import com.blankj.utilcode.util.KeyboardUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.helper.WindowHelper; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/10 * desc : * </pre> */ @SuppressLint("AppCompatCustomView") public class FloatEditText extends EditText { public FloatEditText(Context context) { super(context); init(); } public FloatEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FloatEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { setBackgroundResource(R.drawable.du_sel_et_bg); post(new Runnable() { @Override public void run() { View rootView = getRootView(); if (rootView instanceof BaseContentFloatView) { bindFloatView((BaseContentFloatView) rootView); } } }); } public void bindFloatView(final BaseContentFloatView floatView) { setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { WindowManager.LayoutParams params = floatView.getLayoutParams(); if ((params.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) { params.flags = params.flags & ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; WindowHelper.updateViewLayout(floatView, params); KeyboardUtils.showSoftInput(v); } } }); } @Override protected void onDetachedFromWindow() { KeyboardUtils.hideSoftInput(this); super.onDetachedFromWindow(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SwipeRightMenu.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SwipeRightMenu.java
package com.blankj.utildebug.base.view; import android.animation.ValueAnimator; import android.content.Context; import android.os.SystemClock; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.LinearLayout; import com.blankj.utilcode.util.SizeUtils; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/10 * desc : * </pre> */ public class SwipeRightMenu extends LinearLayout { private static final AccelerateInterpolator OPEN_INTERPOLATOR = new AccelerateInterpolator(0.5f); private static final DecelerateInterpolator CLOSE_INTERPOLATOR = new DecelerateInterpolator(0.5f); private static boolean isTouching; private static WeakReference<SwipeRightMenu> swipeMenuOpened; private View mContentView; private List<MenuBean> mMenus = new ArrayList<>(); private int mMenusWidth = 0; public SwipeRightMenu(Context context) { this(context, null); } public SwipeRightMenu(Context context, @Nullable AttributeSet attrs) { super(context, attrs); setOrientation(HORIZONTAL); post(new Runnable() { @Override public void run() { initView(); } }); } private void initView() { int childCount = getChildCount(); if (childCount <= 1) { throw new IllegalArgumentException("no menus"); } mContentView = getChildAt(0); for (int i = 1; i < childCount; i++) { MenuBean bean = new MenuBean(getChildAt(i)); mMenus.add(bean); if (i == 1) { bean.setCloseMargin(0); } else { bean.setCloseMargin(-mMenus.get(i - 2).getWidth()); } mMenusWidth += bean.getWidth(); } for (int i = 0; i < mMenus.size(); i++) { mMenus.get(i).setOpenMargin(0); } } private static final int STATE_DOWN = 0; private static final int STATE_MOVE = 1; private static final int STATE_STOP = 2; private static final int SLIDE_INIT = 0; private static final int SLIDE_HORIZONTAL = 1; private static final int SLIDE_VERTICAL = 2; private static final int MIN_DISTANCE_MOVE = SizeUtils.dp2px(4); private static final int THRESHOLD_DISTANCE = SizeUtils.dp2px(20); private static final int ANIM_TIMING = 350; private int mState; private int mDownX; private int mDownY; private int mLastX; private int mLastY; private int slideDirection; private boolean isTouchPointInView(View view, int x, int y) { if (view == null) { return false; } int[] location = new int[2]; view.getLocationOnScreen(location); int left = location[0]; int top = location[1]; int right = left + view.getMeasuredWidth(); int bottom = top + view.getMeasuredHeight(); return y >= top && y <= bottom && x >= left && x <= right; } public boolean isOpen() { return swipeMenuOpened != null; } @Override public boolean dispatchTouchEvent(MotionEvent event) { int x = (int) event.getRawX(); int y = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (isTouching) { return false; } isTouching = true; close(this); mDownX = x; mDownY = y; mLastX = x; mLastY = y; mState = STATE_DOWN; slideDirection = SLIDE_INIT; super.dispatchTouchEvent(event); break; case MotionEvent.ACTION_MOVE: if (mState == STATE_DOWN && Math.abs(x - mDownX) < MIN_DISTANCE_MOVE && Math.abs(y - mDownY) < MIN_DISTANCE_MOVE) { break; } if (slideDirection == SLIDE_INIT) { if (Math.abs(x - mDownX) > Math.abs(y - mDownY)) { slideDirection = SLIDE_HORIZONTAL; cancelChildViewTouch(); requestDisallowInterceptTouchEvent(true);// 让父 view 不要拦截 } else { slideDirection = SLIDE_VERTICAL; } } if (slideDirection == SLIDE_VERTICAL) { return super.dispatchTouchEvent(event); } scrollTo(Math.max(Math.min(getScrollX() - x + mLastX, mMenusWidth), 0), 0); float percent = getScrollX() / (float) mMenusWidth; updateLeftMarginByPercent(percent); mLastX = x; mLastY = y; mState = STATE_MOVE; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: try { if (event.getAction() == MotionEvent.ACTION_UP) { if (mState == STATE_DOWN) { if (isOpen()) { if (isTouchPointInView(mContentView, x, y)) { close(true); final long now = SystemClock.elapsedRealtime(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); super.dispatchTouchEvent(cancelEvent); return true; } } super.dispatchTouchEvent(event); close(true); return true; } } else { super.dispatchTouchEvent(event); } if (swipeMenuOpened != null && swipeMenuOpened.get() == this) {// 如果之前是展开状态 if (getScrollX() < mMenusWidth - THRESHOLD_DISTANCE) {// 超过阈值则关闭 close(true); } else {// 否则还是打开 open(true); } } else { if (getScrollX() > THRESHOLD_DISTANCE) {// 如果是关闭 open(true);// 超过阈值则打开 } else { close(true);// 否则还是关闭 } } } finally { isTouching = false; mState = STATE_STOP; } break; default: break; } return true; } private void updateLeftMarginByPercent(float percent) { for (MenuBean menu : mMenus) { menu.getParams().leftMargin = (int) (menu.getCloseMargin() + percent * (menu.getOpenMargin() - menu.getCloseMargin())); menu.getView().requestLayout(); } } private void close(boolean isAnim) { swipeMenuOpened = null; if (isAnim) { ValueAnimator anim = ValueAnimator.ofInt(getScrollX(), 0); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { scrollTo((int) animation.getAnimatedValue(), 0); } }); anim.setInterpolator(CLOSE_INTERPOLATOR); anim.setDuration(ANIM_TIMING).start(); for (final MenuBean menu : mMenus) { ValueAnimator menuAnim = ValueAnimator.ofInt(menu.getParams().leftMargin, menu.getCloseMargin()); menuAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { menu.getParams().leftMargin = (int) animation.getAnimatedValue(); menu.getView().requestLayout(); } }); menuAnim.setInterpolator(CLOSE_INTERPOLATOR); menuAnim.setDuration(ANIM_TIMING).start(); } } else { scrollTo(0, 0); for (final MenuBean menu : mMenus) { menu.getParams().leftMargin = menu.getCloseMargin(); menu.getView().requestLayout(); } } } private void open(boolean isAnim) { swipeMenuOpened = new WeakReference<>(this); if (isAnim) { ValueAnimator anim = ValueAnimator.ofInt(getScrollX(), mMenusWidth); anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { scrollTo((int) animation.getAnimatedValue(), 0); } }); anim.setInterpolator(OPEN_INTERPOLATOR); anim.setDuration(ANIM_TIMING).start(); for (final MenuBean menu : mMenus) { ValueAnimator menuAnim = ValueAnimator.ofInt(menu.getParams().leftMargin, menu.getOpenMargin()); menuAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { menu.getParams().leftMargin = (int) animation.getAnimatedValue(); menu.getView().requestLayout(); } }); menuAnim.setInterpolator(OPEN_INTERPOLATOR); menuAnim.setDuration(ANIM_TIMING).start(); } } else { scrollTo(mMenusWidth, 0); for (final MenuBean menu : mMenus) { menu.getParams().leftMargin = menu.getOpenMargin(); menu.getView().requestLayout(); } } } public void close(SwipeRightMenu exclude) { if (swipeMenuOpened != null) { final SwipeRightMenu swipeMenu = swipeMenuOpened.get(); if (swipeMenu != exclude) { swipeMenu.close(true); } } } private void cancelChildViewTouch() { final long now = SystemClock.elapsedRealtime(); final MotionEvent cancelEvent = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).dispatchTouchEvent(cancelEvent); } cancelEvent.recycle(); } private static class MenuBean { private View mView; private LinearLayout.LayoutParams mParams; private int mWidth; private int mCloseMargin; private int mOpenMargin; public MenuBean(View view) { mView = view; mParams = (LayoutParams) view.getLayoutParams(); mWidth = view.getWidth(); } public View getView() { return mView; } public LayoutParams getParams() { return mParams; } public int getWidth() { return mWidth; } public int getCloseMargin() { return mCloseMargin; } public int getOpenMargin() { return mOpenMargin; } public void setCloseMargin(int closeMargin) { mCloseMargin = closeMargin; } public void setOpenMargin(int openMargin) { mOpenMargin = openMargin; } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseFloatView.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseFloatView.java
package com.blankj.utildebug.base.view; import android.app.Activity; import android.graphics.PixelFormat; import android.os.Build; import android.view.KeyEvent; import android.view.WindowManager; import android.widget.RelativeLayout; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.Utils; import com.blankj.utildebug.DebugUtils; import com.blankj.utildebug.R; import androidx.annotation.CallSuper; import androidx.annotation.LayoutRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/10 * desc : * </pre> */ public abstract class BaseFloatView extends RelativeLayout implements Utils.OnAppStatusChangedListener { private boolean isCreated; protected WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(); @LayoutRes public abstract int bindLayout(); public abstract void initContentView(); public BaseFloatView() { super(DebugUtils.getApp()); setId(R.id.baseFloatView); if (bindLayout() != NO_ID) { inflate(getContext(), bindLayout(), this); } onCreateLayoutParams(); } void createFloatView() { if (isCreated) return; isCreated = true; initContentView(); } @CallSuper protected void onCreateLayoutParams() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; } mLayoutParams.format = PixelFormat.TRANSPARENT; mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; try { int currentFlags = (Integer) mLayoutParams.getClass().getField("privateFlags").get(mLayoutParams); mLayoutParams.getClass().getField("privateFlags").set(mLayoutParams, currentFlags | 0x00000040); } catch (Exception ignore) { } } public void show() { FloatViewManager.getInstance().show(this); } public void dismiss() { FloatViewManager.getInstance().dismiss(this); } @Override public WindowManager.LayoutParams getLayoutParams() { return mLayoutParams; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); AppUtils.registerAppStatusChangedListener(this); } @Override protected void onDetachedFromWindow() { AppUtils.unregisterAppStatusChangedListener(this); super.onDetachedFromWindow(); } @Override public void onForeground(Activity activity) { setVisibility(VISIBLE); } @Override public void onBackground(Activity activity) { setVisibility(GONE); } /////////////////////////////////////////////////////////////////////////// // When flag with FLAG_NOT_TOUCH_MODAL, should process the key event. /////////////////////////////////////////////////////////////////////////// @Override public boolean dispatchKeyEvent(KeyEvent event) { Activity topActivity = ActivityUtils.getTopActivity(); if (topActivity != null) { if (topActivity.getWindow().getDecorView().dispatchKeyEvent(event)) { return true; } } return super.dispatchKeyEvent(event); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SearchEditText.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SearchEditText.java
package com.blankj.utildebug.base.view; import android.content.Context; import android.util.AttributeSet; import com.blankj.utilcode.util.KeyboardUtils; import com.blankj.utilcode.util.StringUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/06 * desc : * </pre> */ public class SearchEditText extends FloatEditText { private static final long LIMIT = 200; private OnTextChangedListener mListener; private String mStartSearchText = "";// 记录开始输入前的文本内容 private Runnable mAction = new Runnable() { @Override public void run() { if (mListener != null) { // 判断最终和开始前是否一致 if (!StringUtils.equals(mStartSearchText, getText().toString())) { mStartSearchText = getText().toString();// 更新 mStartSearchText mListener.onTextChanged(mStartSearchText); } } } }; public SearchEditText(Context context) { this(context, null); } public SearchEditText(Context context, AttributeSet attrs) { super(context, attrs); } /** * 在 LIMIT 时间内连续输入不触发文本变化 */ public void setOnTextChangedListener(OnTextChangedListener listener) { mListener = listener; } public void reset() { mStartSearchText = ""; setText(""); KeyboardUtils.hideSoftInput(this); } @Override protected void onTextChanged(final CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); // 移除上一次的回调 removeCallbacks(mAction); postDelayed(mAction, LIMIT); } @Override protected void onDetachedFromWindow() { removeCallbacks(mAction); KeyboardUtils.hideSoftInput(this); super.onDetachedFromWindow(); } public interface OnTextChangedListener { void onTextChanged(String text); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseContentView.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseContentView.java
package com.blankj.utildebug.base.view; import android.widget.FrameLayout; import com.blankj.utildebug.DebugUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.listener.OnBackListener; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/01 * desc : * </pre> */ public abstract class BaseContentView<T extends BaseContentFloatView<T>> extends FrameLayout implements OnBackListener { private T mFloatView; private boolean isAddStack; private OnRefreshListener mRefreshRunnable; private boolean mRefreshEnabled; public BaseContentView() { super(DebugUtils.getApp()); setId(R.id.baseContentView); inflate(getContext(), bindLayout(), this); } public void attach(T floatView, boolean isAddStack) { this.mFloatView = floatView; this.isAddStack = isAddStack; floatView.replace(this, isAddStack); } @LayoutRes public abstract int bindLayout(); public abstract void onAttach(); public T getFloatView() { return mFloatView; } public boolean isAddStack() { return isAddStack; } public void setOnRefreshListener(RecyclerView rv, OnRefreshListener listener) { mRefreshRunnable = listener; mFloatView.setOnRefreshListener(listener); attachRefresh(rv); } @Override public void onBack() { } OnRefreshListener getOnRefreshListener() { return mRefreshRunnable; } boolean isRefreshEnabled() { return mRefreshEnabled; } private void attachRefresh(RecyclerView rv) { rv.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); mRefreshEnabled = newState == RecyclerView.SCROLL_STATE_IDLE && !recyclerView.canScrollVertically(-1); mFloatView.setRefreshEnabled(mRefreshEnabled); } }); mRefreshEnabled = !rv.canScrollVertically(-1); mFloatView.setRefreshEnabled(mRefreshEnabled); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/EmptyGoneTextView.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/EmptyGoneTextView.java
package com.blankj.utildebug.base.view; import android.annotation.SuppressLint; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; import com.blankj.utilcode.util.StringUtils; import androidx.annotation.Nullable; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/03 * desc : * </pre> */ @SuppressLint("AppCompatCustomView") public class EmptyGoneTextView extends TextView { public EmptyGoneTextView(Context context) { this(context, null); } public EmptyGoneTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); setVisibility(GONE); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); if (StringUtils.isEmpty(text)) { setVisibility(GONE); } else { setVisibility(VISIBLE); } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatToast.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatToast.java
package com.blankj.utildebug.base.view; import android.annotation.SuppressLint; import android.view.Gravity; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import com.blankj.utilcode.util.SizeUtils; import com.blankj.utildebug.R; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/10 * desc : * </pre> */ public class FloatToast extends BaseFloatView { public static final int SUCCESS = 0; public static final int WARNING = 1; public static final int ERROR = 2; @IntDef({SUCCESS, WARNING, ERROR}) @Retention(RetentionPolicy.SOURCE) public @interface Type { } private static final FloatToast INSTANCE = new FloatToast(); private static final Runnable DISMISS_RUNNABLE = new Runnable() { @Override public void run() { INSTANCE.dismiss(); } }; @Type private int mType; private String mMsg; private ImageView toastIconIv; private TextView toastMsgTv; private FloatToast() { } @Override public int bindLayout() { return R.layout.du_float_toast; } @Override public void initContentView() { toastIconIv = findViewById(R.id.toastIconIv); toastMsgTv = findViewById(R.id.toastMsgTv); } @Override protected void onCreateLayoutParams() { super.onCreateLayoutParams(); mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT; mLayoutParams.windowAnimations = android.R.style.Animation_Toast; mLayoutParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; mLayoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; mLayoutParams.y = SizeUtils.dp2px(64); } @Override public void show() { super.show(); if (mType < 0 || mType > 2) { toastIconIv.setVisibility(GONE); } else { toastIconIv.setVisibility(VISIBLE); if (mType == SUCCESS) { toastIconIv.setImageResource(R.drawable.du_ic_toast_success); } else if (mType == WARNING) { toastIconIv.setImageResource(R.drawable.du_ic_toast_warn); } else { toastIconIv.setImageResource(R.drawable.du_ic_toast_error); } } toastMsgTv.setText(mMsg); } private void setType(int type) { mType = type; } private void setMsg(String msg) { mMsg = msg == null ? "" : msg; } public static void showShort(String msg) { show(msg, 2000); } public static void showShort(@Type int type, String msg) { show(type, msg, 2000); } public static void showLong(String msg) { show(msg, 3500); } public static void showLong(@Type int type, String msg) { show(type, msg, 3500); } @SuppressLint("WrongConstant") public static void show(String msg, long millis) { show(-1, msg, millis); } public static void show(@Type int type, String msg, long millis) { INSTANCE.removeCallbacks(DISMISS_RUNNABLE); INSTANCE.dismiss(); INSTANCE.setType(type); INSTANCE.setMsg(msg); INSTANCE.show(); INSTANCE.postDelayed(DISMISS_RUNNABLE, millis); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatViewManager.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/FloatViewManager.java
package com.blankj.utildebug.base.view; import android.view.WindowManager; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utildebug.helper.WindowHelper; import java.util.ArrayList; import java.util.List; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/30 * desc : * </pre> */ public class FloatViewManager { private final WindowManager mWM = WindowHelper.getWindowManager(); private final List<BaseFloatView> mFloatViews = new ArrayList<>(); private FloatViewManager() { } public static FloatViewManager getInstance() { return LazyHolder.INSTANCE; } private static final class LazyHolder { private static final FloatViewManager INSTANCE = new FloatViewManager(); } public void show(final BaseFloatView view) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { if (mFloatViews.contains(view)) return; view.createFloatView(); mWM.addView(view, view.getLayoutParams()); mFloatViews.add(view); } }); } public void dismiss(final BaseFloatView view) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { if (!mFloatViews.contains(view)) return; mWM.removeView(view); mFloatViews.remove(view); } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseContentFloatView.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/BaseContentFloatView.java
package com.blankj.utildebug.base.view; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.blankj.swipepanel.SwipePanel; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.SizeUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.TouchUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import com.blankj.utildebug.config.DebugConfig; import com.blankj.utildebug.helper.ShadowHelper; import com.blankj.utildebug.helper.WindowHelper; import java.util.Stack; import androidx.annotation.LayoutRes; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/30 * desc : * </pre> */ public abstract class BaseContentFloatView<T extends BaseContentFloatView<T>> extends BaseFloatView { private static final int ROTATE_DELAY = 30; private LinearLayout bcfRootLayout; private RelativeLayout bcfTitleRl; private ImageView bcfCloseIv; private TextView bcfTitleTv; private ImageView bcfAdjustIv; private SwipePanel swipePanel; private BaseContentView<T> mContentView; private OnRefreshListener mRefreshListener; private Runnable mRotateRunnable = new Runnable() { @Override public void run() { Drawable topDrawable = swipePanel.getTopDrawable(); topDrawable.setLevel(topDrawable.getLevel() + 500); swipePanel.invalidate(); startRotate(); } }; private static final ViewGroup.LayoutParams PARAMS = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); private Stack<BaseContentView<T>> mViewStack = new Stack<>(); @StringRes public abstract int bindTitle(); @LayoutRes public abstract int bindContentLayout(); @Override public int bindLayout() { return R.layout.du_base_content_float; } public BaseContentFloatView() { bcfRootLayout = findViewById(R.id.bcfRootLayout); ShadowHelper.applyFloatView(bcfRootLayout); initTitleBar(); initSwipePanel(); if (bindContentLayout() != NO_ID) { //noinspection unchecked new BaseContentView<T>() { @Override public int bindLayout() { return BaseContentFloatView.this.bindContentLayout(); } @Override public void onAttach() { } }.attach((T) this, true); } } public void setTitle(CharSequence title) { bcfTitleTv.setText(title); } void setOnRefreshListener(OnRefreshListener listener) { mRefreshListener = listener; } void setRefreshEnabled(boolean enabled) { swipePanel.setTopEnabled(enabled); } public void setSwipeBackEnabled(boolean enabled) { swipePanel.setLeftEnabled(enabled); } public void back() { swipePanel.close(SwipePanel.TOP, false);// 返回先关闭刷新 swipePanel.removeAllViews(); if (mContentView == null) { dismiss(); return; } mContentView.onBack(); if (mViewStack.isEmpty()) { dismiss(); return; } if (mContentView.isAddStack()) { mViewStack.pop(); } if (mViewStack.isEmpty()) { dismiss(); return; } BaseContentView<T> peek = mViewStack.peek(); swipePanel.addView(peek, PARAMS); setOnRefreshListener(peek.getOnRefreshListener()); setRefreshEnabled(peek.isRefreshEnabled()); mContentView = peek; } public void closeRefresh() { postDelayed(new Runnable() { @Override public void run() { swipePanel.close(SwipePanel.TOP); } }, 500); } public BaseContentView<T> getContentView() { return mContentView; } @Override protected void onDetachedFromWindow() { DebugConfig.saveViewY(this, mLayoutParams.y); DebugConfig.saveViewHeight(this, mLayoutParams.height); DebugConfig.saveViewAlpha(this, mLayoutParams.alpha); super.onDetachedFromWindow(); } void replace(BaseContentView<T> view, boolean isAddStack) { if (view == null) return; if (isAddStack) { mViewStack.add(view); } swipePanel.removeAllViews(); mContentView = view; mContentView.onAttach(); swipePanel.addView(mContentView, PARAMS); } private void initTitleBar() { bcfTitleRl = findViewById(R.id.bcfTitleRl); bcfCloseIv = findViewById(R.id.bcfCloseIv); bcfTitleTv = findViewById(R.id.bcfTitleTv); bcfAdjustIv = findViewById(R.id.bcfAdjustIv); bcfTitleTv.setText(bindTitle()); ClickUtils.applyPressedBgDark(bcfTitleRl); bcfTitleRl.setOnClickListener(new ClickUtils.OnMultiClickListener(2) { @Override public void onTriggerClick(View v) { mLayoutParams.alpha = mLayoutParams.alpha == 0.5f ? 1f : 0.5f; WindowHelper.updateViewLayout(BaseContentFloatView.this, mLayoutParams); DebugConfig.saveViewAlpha(BaseContentFloatView.this, mLayoutParams.alpha); } @Override public void onBeforeTriggerClick(View v, int count) { if (count == 1) { } } }); TouchUtils.setOnTouchListener(bcfTitleRl, new TouchUtils.OnTouchUtilsListener() { @Override public boolean onDown(View view, int x, int y, MotionEvent event) { return true; } @Override public boolean onMove(View view, int direction, int x, int y, int dx, int dy, int totalX, int totalY, MotionEvent event) { mLayoutParams.y = Math.min(Math.max(mLayoutParams.y + dy, 0), WindowHelper.getAppWindowHeight() - bcfRootLayout.getHeight()); WindowHelper.updateViewLayout(BaseContentFloatView.this, mLayoutParams); return true; } @Override public boolean onStop(View view, int direction, int x, int y, int totalX, int totalY, int vx, int vy, MotionEvent event) { DebugConfig.saveViewY(BaseContentFloatView.this, mLayoutParams.y); return true; } }); ClickUtils.applyPressedBgDark(bcfCloseIv, 0.8f); bcfCloseIv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); ClickUtils.applyPressedBgDark(bcfAdjustIv, 0.8f); bcfAdjustIv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FloatToast.showLong(FloatToast.WARNING, StringUtils.getString(R.string.du_adjust_tips)); } }); TouchUtils.setOnTouchListener(bcfAdjustIv, new TouchUtils.OnTouchUtilsListener() { private int minHeight; @Override public boolean onDown(View view, int x, int y, MotionEvent event) { int[] locations = new int[2]; getLocationOnScreen(locations); mLayoutParams.height = WindowHelper.getAppWindowHeight() - locations[1]; WindowHelper.updateViewLayout(BaseContentFloatView.this, mLayoutParams); minHeight = bcfTitleRl.getHeight() + SizeUtils.dp2px(30); return true; } @Override public boolean onMove(View view, int direction, int x, int y, int dx, final int dy, int totalX, int totalY, MotionEvent event) { ViewGroup.LayoutParams layoutParams = bcfRootLayout.getLayoutParams(); layoutParams.height = Math.min(Math.max(bcfRootLayout.getHeight() + dy, minHeight), mLayoutParams.height); bcfRootLayout.setLayoutParams(layoutParams); return true; } @Override public boolean onStop(View view, int direction, int x, int y, int totalX, int totalY, int vx, int vy, MotionEvent event) { mLayoutParams.height = bcfRootLayout.getHeight(); WindowHelper.updateViewLayout(BaseContentFloatView.this, mLayoutParams); DebugConfig.saveViewHeight(BaseContentFloatView.this, mLayoutParams.height); return true; } }); } private void initSwipePanel() { swipePanel = findViewById(R.id.bcfSwipePanel); swipePanel.setOnFullSwipeListener(new SwipePanel.OnFullSwipeListener() { @Override public void onFullSwipe(int direction) { if (direction == SwipePanel.LEFT) { swipePanel.close(direction); back(); } else if (direction == SwipePanel.TOP) { if (mRefreshListener != null) { startRotate(); mRefreshListener.onRefresh(BaseContentFloatView.this); } } } }); swipePanel.setOnProgressChangedListener(new SwipePanel.OnProgressChangedListener() { @Override public void onProgressChanged(int direction, float progress, boolean isTouch) { if (direction == SwipePanel.TOP) { Drawable topDrawable = swipePanel.getTopDrawable(); if (isTouch) { topDrawable.setLevel((int) (progress * 20000)); } else { if (progress < 0.5) { stopRotate(); } } } } }); } private void startRotate() { swipePanel.postDelayed(mRotateRunnable, ROTATE_DELAY); } private void stopRotate() { swipePanel.removeCallbacks(mRotateRunnable); } @Override protected void onCreateLayoutParams() { super.onCreateLayoutParams(); mLayoutParams.gravity = Gravity.TOP; mLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; mLayoutParams.height = DebugConfig.getViewHeight(BaseContentFloatView.this, WindowManager.LayoutParams.WRAP_CONTENT); mLayoutParams.windowAnimations = R.style.FloatAnimation; mLayoutParams.alpha = DebugConfig.getViewAlpha(this); mLayoutParams.y = DebugConfig.getViewY(this); post(new Runnable() { @Override public void run() { if (getParent() != null) { wrapWindow(); } } }); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); wrapWindow(); } private void wrapWindow() { int[] locations = new int[2]; getLocationOnScreen(locations); int floatViewHeight = DebugConfig.getViewHeight(BaseContentFloatView.this, bcfRootLayout.getHeight()); if (locations[1] + floatViewHeight > WindowHelper.getAppWindowHeight()) { floatViewHeight = WindowHelper.getAppWindowHeight() - locations[1]; } mLayoutParams.height = floatViewHeight; WindowHelper.updateViewLayout(BaseContentFloatView.this, mLayoutParams); ViewGroup.LayoutParams layoutParams = bcfRootLayout.getLayoutParams(); layoutParams.height = mLayoutParams.height; bcfRootLayout.setLayoutParams(layoutParams); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/listener/OnRefreshListener.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/listener/OnRefreshListener.java
package com.blankj.utildebug.base.view.listener; import com.blankj.utildebug.base.view.BaseContentFloatView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/20 * desc : * </pre> */ public interface OnRefreshListener { void onRefresh(BaseContentFloatView floatView); }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/base/view/listener/OnBackListener.java
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/listener/OnBackListener.java
package com.blankj.utildebug.base.view.listener; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/20 * desc : * </pre> */ public interface OnBackListener { void onBack(); }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/helper/FileHelper.java
lib/utildebug/src/main/java/com/blankj/utildebug/helper/FileHelper.java
package com.blankj.utildebug.helper; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.ImageUtils; import com.blankj.utilcode.util.StringUtils; import java.io.File; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/08 * desc : * </pre> */ public class FileHelper { public static final int IMAGE = 0; public static final int SP = 1; public static final int UTF8 = 2; public static final int UNKNOWN = -1; @IntDef({IMAGE, SP, UTF8, UNKNOWN}) @Retention(RetentionPolicy.SOURCE) public @interface FileType { } @FileType public static int getFileType(String path) { return getFileType(FileUtils.getFileByPath(path)); } @FileType public static int getFileType(File file) { if (!FileUtils.isFileExists(file)) return UNKNOWN; if (ImageUtils.isImage(file)) { return IMAGE; } if (FileUtils.getFileExtension(file).equals("xml")) { File parentFile = file.getParentFile(); if (parentFile != null) { if (StringUtils.equals(parentFile.getName(), "shared_prefs")) { return SP; } } } if (FileUtils.isUtf8(file)) { return UTF8; } return UNKNOWN; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/helper/SpHelper.java
lib/utildebug/src/main/java/com/blankj/utildebug/helper/SpHelper.java
package com.blankj.utildebug.helper; import com.blankj.utilcode.util.SPUtils; import java.util.HashSet; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/09 * desc : * </pre> */ public class SpHelper { public static String getSpClassName(Class cls) { if (cls == null) return "null"; if (Boolean.class.equals(cls)) { return "boolean"; } if (String.class.equals(cls)) { return "String"; } if (Integer.class.equals(cls)) { return "int"; } if (Float.class.equals(cls)) { return "float"; } if (Long.class.equals(cls)) { return "long"; } if (HashSet.class.equals(cls)) { return "set"; } return "unknown"; } public static boolean putValue(SPUtils spUtils, String key, String value, Class cls) { if (cls == null) return false; if (String.class.equals(cls)) { spUtils.put(key, value); return true; } if (Integer.class.equals(cls)) { try { int val = Integer.parseInt(value); spUtils.put(key, val); return true; } catch (NumberFormatException e) { return false; } } if (Float.class.equals(cls)) { try { float val = Float.parseFloat(value); spUtils.put(key, val); return true; } catch (NumberFormatException e) { return false; } } if (Long.class.equals(cls)) { try { long val = Long.parseLong(value); spUtils.put(key, val); return true; } catch (NumberFormatException e) { return false; } } return false; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/helper/WindowHelper.java
lib/utildebug/src/main/java/com/blankj/utildebug/helper/WindowHelper.java
package com.blankj.utildebug.helper; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import com.blankj.utilcode.util.ScreenUtils; import com.blankj.utilcode.util.Utils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/29 * desc : * </pre> */ public class WindowHelper { private static WindowManager sWM; private WindowHelper() { } public static void updateViewLayout(final View view, ViewGroup.LayoutParams params) { getWindowManager().updateViewLayout(view, params); } public static int getAppWindowHeight() { return ScreenUtils.getAppScreenHeight(); } public static WindowManager getWindowManager() { if (sWM == null) { sWM = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE); } return sWM; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/helper/ShadowHelper.java
lib/utildebug/src/main/java/com/blankj/utildebug/helper/ShadowHelper.java
package com.blankj.utildebug.helper; import android.view.View; import com.blankj.utilcode.util.ShadowUtils; import com.blankj.utilcode.util.SizeUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/16 * desc : * </pre> */ public class ShadowHelper { public static void applyDebugIcon(View view) { ShadowUtils.apply(view, new ShadowUtils.Config() .setCircle() .setShadowColor(0xc0_ffffff, 0x60_ffffff) ); } public static void applyFloatView(View view) { ShadowUtils.apply(view, new ShadowUtils.Config().setShadowRadius(SizeUtils.dp2px(8))); } public static void applyMenu(View view) { ShadowUtils.apply(view, new ShadowUtils.Config() .setShadowRadius(SizeUtils.dp2px(4)) ); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/helper/ImageLoader.java
lib/utildebug/src/main/java/com/blankj/utildebug/helper/ImageLoader.java
package com.blankj.utildebug.helper; import android.graphics.Bitmap; import android.widget.ImageView; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.ImageUtils; import com.blankj.utilcode.util.ThreadUtils; import java.io.File; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/06 * desc : * </pre> */ public class ImageLoader { public static void load(final String path, final ImageView imageView) { load(FileUtils.getFileByPath(path), imageView); } public static void load(final File file, final ImageView imageView) { if (!FileUtils.isFileExists(file)) return; imageView.post(new Runnable() { @Override public void run() { ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<Bitmap>() { @Override public Bitmap doInBackground() throws Throwable { return ImageUtils.getBitmap(file, imageView.getWidth(), imageView.getHeight()); } @Override public void onSuccess(final Bitmap result) { imageView.setImageBitmap(result); } }); } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/config/DebugConfig.java
lib/utildebug/src/main/java/com/blankj/utildebug/config/DebugConfig.java
package com.blankj.utildebug.config; import android.view.View; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.ScreenUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class DebugConfig { private static final String DEBUG_ICON_X = "DEBUG_ICON_X"; private static final String DEBUG_ICON_Y = "DEBUG_ICON_Y"; private static final String NO_MORE_REMINDER = "NO_MORE_REMINDER"; public static void saveDebugIconX(float x) { getSp().put(DEBUG_ICON_X, x); } public static float getDebugIconX() { return getSp().getFloat(DEBUG_ICON_X); } public static void saveDebugIconY(float y) { getSp().put(DEBUG_ICON_Y, y); } public static float getDebugIconY() { return getSp().getFloat(DEBUG_ICON_Y, ScreenUtils.getAppScreenHeight() / 3); } public static void saveNoMoreReminder() { getSp().put(NO_MORE_REMINDER, true); } public static boolean isNoMoreReminder() { return getSp().getBoolean(NO_MORE_REMINDER, false); } public static void saveViewY(View view, int y) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".yP", y); } else { getSp().put(view.getClass().getSimpleName() + ".yL", y); } } public static int getViewY(View view) { return getViewY(view, 0); } public static int getViewY(View view, int defaultVal) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".yP", defaultVal); } else { return getSp().getInt(view.getClass().getSimpleName() + ".yL", defaultVal); } } public static void saveViewX(View view, int x) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".xP", x); } else { getSp().put(view.getClass().getSimpleName() + ".xL", x); } } public static int getViewX(View view) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".xP"); } else { return getSp().getInt(view.getClass().getSimpleName() + ".xL"); } } public static void saveViewHeight(View view, int height) { if (ScreenUtils.isPortrait()) { getSp().put(view.getClass().getSimpleName() + ".heightP", height); } else { getSp().put(view.getClass().getSimpleName() + ".heightL", height); } } public static int getViewHeight(View view, int height) { if (ScreenUtils.isPortrait()) { return getSp().getInt(view.getClass().getSimpleName() + ".heightP", height); } else { return getSp().getInt(view.getClass().getSimpleName() + ".heightL", height); } } public static void saveViewAlpha(View view, float alpha) { getSp().put(view.getClass().getSimpleName() + ".alpha", alpha); } public static float getViewAlpha(View view) { return getSp().getFloat(view.getClass().getSimpleName() + ".alpha", 1f); } private static SPUtils getSp() { return SPUtils.getInstance("DebugUtils"); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenu.java
lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenu.java
package com.blankj.utildebug.menu; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.config.DebugConfig; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.icon.DebugIcon; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/29 * desc : * </pre> */ public class DebugMenu extends BaseContentFloatView<DebugMenu> { private static final DebugMenu INSTANCE = new DebugMenu(); private List<IDebug> mDebugs; private BaseItemAdapter<DebugMenuItem> mAdapter; private RecyclerView debugMenuRv; public static DebugMenu getInstance() { return INSTANCE; } @Override public int bindTitle() { return R.string.du_menus; } @Override public int bindContentLayout() { return R.layout.du_debug_menu; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); DebugIcon.setVisibility(false); if (!DebugConfig.isNoMoreReminder()) { new ReminderView().show(); } } @Override protected void onDetachedFromWindow() { int a = 0xe1; DebugIcon.setVisibility(true); super.onDetachedFromWindow(); } @Override public void initContentView() { setSwipeBackEnabled(false); debugMenuRv = findViewById(R.id.debugMenuRv); mAdapter = new BaseItemAdapter<>(); mAdapter.setItems(DebugMenuItem.getDebugMenuItems(mDebugs)); debugMenuRv.setAdapter(mAdapter); debugMenuRv.setLayoutManager(new LinearLayoutManager(getContext())); } public void setDebugs(List<IDebug> debugs) { mDebugs = debugs; } public void addDebugs(List<IDebug> debugs) { if (debugs == null || debugs.size() == 0) return; mDebugs.addAll(debugs); if (mAdapter == null) return; mAdapter.notifyDataSetChanged(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenuItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugMenuItem.java
package com.blankj.utildebug.menu; import android.widget.TextView; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.helper.ShadowHelper; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/29 * desc : * </pre> */ public class DebugMenuItem extends BaseItem<DebugMenuItem> { private String mTitle; private List<IDebug> mDebugs; private DebugMenuItem(String title, List<IDebug> debugs) { super(R.layout.du_item_menu); mTitle = title; mDebugs = debugs; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { TextView menuTitle = holder.findViewById(R.id.menuCategory); RecyclerView menuRv = holder.findViewById(R.id.menuRv); ShadowHelper.applyMenu(holder.itemView); menuTitle.setText(mTitle); BaseItemAdapter<DebugItem> adapter = new BaseItemAdapter<>(); adapter.setItems(DebugItem.getDebugItems(mDebugs)); menuRv.setAdapter(adapter); menuRv.setLayoutManager(new GridLayoutManager(menuRv.getContext(), 4)); } public static List<DebugMenuItem> getDebugMenuItems(List<IDebug> debugs) { Map<Integer, List<IDebug>> debugMap = new LinkedHashMap<>(); for (IDebug debug : debugs) { List<IDebug> debugList = debugMap.get(debug.getCategory()); if (debugList == null) { debugList = new ArrayList<>(); debugMap.put(debug.getCategory(), debugList); } debugList.add(debug); } List<DebugMenuItem> itemList = new ArrayList<>(); for (Map.Entry<Integer, List<IDebug>> entry : debugMap.entrySet()) { itemList.add(new DebugMenuItem(getCategoryString(entry.getKey()), entry.getValue())); } return itemList; } private static String getCategoryString(int category) { switch (category) { case IDebug.TOOLS: return StringUtils.getString(R.string.du_tools); case IDebug.PERFORMANCE: return StringUtils.getString(R.string.du_performance); case IDebug.UI: return StringUtils.getString(R.string.du_ui); case IDebug.BIZ: return StringUtils.getString(R.string.du_biz); default: return StringUtils.getString(R.string.du_uncategorized); } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/menu/ReminderView.java
lib/utildebug/src/main/java/com/blankj/utildebug/menu/ReminderView.java
package com.blankj.utildebug.menu; import android.widget.Switch; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.config.DebugConfig; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/10 * desc : * </pre> */ public class ReminderView extends BaseContentFloatView<ReminderView> { private Switch reminderNoMoreSwitch; @Override public int bindTitle() { return R.string.du_reminder; } @Override public int bindContentLayout() { return R.layout.du_reminder_view; } @Override public void initContentView() { reminderNoMoreSwitch = findViewById(R.id.reminderNoMoreSwitch); } @Override public void dismiss() { super.dismiss(); if (reminderNoMoreSwitch.isChecked()) { DebugConfig.saveNoMoreReminder(); } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/menu/DebugItem.java
package com.blankj.utildebug.menu; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.drawable.PolygonDrawable; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.debug.IDebug; import java.util.List; import java.util.Random; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/29 * desc : * </pre> */ public class DebugItem extends BaseItem<DebugItem> { private IDebug mDebug; private int mColor = getRandomColor(); private DebugItem(IDebug debug) { super(R.layout.du_item_menu_item); mDebug = debug; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { ImageView menuItemIconIv = holder.findViewById(R.id.menuItemIconIv); TextView menuItemNameTv = holder.findViewById(R.id.menuItemNameTv); ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyPressedViewScale(holder.itemView); menuItemIconIv.setBackgroundDrawable(new PolygonDrawable(5, mColor)); menuItemIconIv.setImageResource(mDebug.getIcon()); menuItemNameTv.setText(StringUtils.getString(mDebug.getName())); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDebug.onClick(v); } }); } public static List<DebugItem> getDebugItems(List<IDebug> debugs) { return (List<DebugItem>) CollectionUtils.collect(debugs, new CollectionUtils.Transformer<IDebug, DebugItem>() { @Override public DebugItem transform(IDebug input) { return new DebugItem(input); } }); } private static final Random RANDOM = new Random(); private static int getRandomColor() { return ColorUtils.getColor(COLORS[RANDOM.nextInt(6)]); } private static final int[] COLORS = new int[]{ R.color.bittersweet, R.color.sunflower, R.color.grass, R.color.blueJeans, R.color.lavander, R.color.pinkRose }; }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/IDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/IDebug.java
package com.blankj.utildebug.debug; import android.content.Context; import android.view.View; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.DrawableRes; import androidx.annotation.IntDef; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/08/28 * desc : * </pre> */ public interface IDebug { void onAppCreate(Context context); @Category int getCategory(); @DrawableRes int getIcon(); @StringRes int getName(); void onClick(View view); int TOOLS = 0; int PERFORMANCE = 1; int UI = 2; int BIZ = 3; @IntDef({TOOLS, PERFORMANCE, UI, BIZ}) @Retention(RetentionPolicy.SOURCE) @interface Category { } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/AbsToolDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/AbsToolDebug.java
package com.blankj.utildebug.debug.tool; import com.blankj.utildebug.debug.IDebug; import com.blankj.utildebug.debug.tool.appInfo.AppInfoDebug; import com.blankj.utildebug.debug.tool.clearCache.ClearCacheDebug; import com.blankj.utildebug.debug.tool.clearStorage.ClearStorageDebug; import com.blankj.utildebug.debug.tool.deviceInfo.DeviceInfoDebug; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerDebug; import com.blankj.utildebug.debug.tool.logcat.LogcatDebug; import com.blankj.utildebug.debug.tool.restartApp.RestartAppDebug; import java.util.List; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public abstract class AbsToolDebug implements IDebug { @Override public int getCategory() { return TOOLS; } public static void addToolDebugs(List<IDebug> debugList) { debugList.add(new AppInfoDebug()); debugList.add(new DeviceInfoDebug()); debugList.add(new FileExplorerDebug()); debugList.add(new LogcatDebug()); debugList.add(new RestartAppDebug()); debugList.add(new ClearStorageDebug()); debugList.add(new ClearCacheDebug()); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileContentView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileContentView.java
package com.blankj.utildebug.debug.tool.fileExplorer; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.SearchEditText; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/06 * desc : * </pre> */ public class FileContentView extends BaseContentView<FileExplorerFloatView> { private FileItem mParent; private BaseItemAdapter<FileItem> mAdapter; private List<FileItem> mSrcItems; private SearchEditText fileExplorerSearchEt; private RecyclerView fileExplorerRv; public static void show(FileExplorerFloatView floatView) { new FileContentView(null).attach(floatView, true); } public static void show(FileExplorerFloatView floatView, FileItem fileItem) { new FileContentView(fileItem).attach(floatView, true); } public FileContentView(FileItem parent) { mParent = parent; mSrcItems = FileItem.getFileItems(mParent); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer; } @Override public void onAttach() { fileExplorerSearchEt = findViewById(R.id.fileExplorerSearchEt); fileExplorerRv = findViewById(R.id.fileExplorerRv); if (FileItem.isEmptyItems(mSrcItems)) { fileExplorerSearchEt.setVisibility(GONE); } mAdapter = new BaseItemAdapter<>(); mAdapter.setItems(mSrcItems); fileExplorerRv.setAdapter(mAdapter); fileExplorerRv.setLayoutManager(new LinearLayoutManager(getContext())); fileExplorerRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_file_divider)); fileExplorerSearchEt.setOnTextChangedListener(new SearchEditText.OnTextChangedListener() { @Override public void onTextChanged(String text) { mAdapter.setItems(FileItem.filterItems(mSrcItems, text)); mAdapter.notifyDataSetChanged(); } }); setOnRefreshListener(fileExplorerRv, new OnRefreshListener() { @Override public void onRefresh(BaseContentFloatView floatView) { mSrcItems = FileItem.getFileItems(mParent); mAdapter.setItems(mSrcItems); mAdapter.notifyDataSetChanged(); fileExplorerSearchEt.reset(); floatView.closeRefresh(); } }); } @Override public void onBack() { super.onBack(); if (mParent != null) { mParent.update(); } } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileItem.java
package com.blankj.utildebug.debug.tool.fileExplorer; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.blankj.utilcode.constant.PermissionConstants; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.PathUtils; import com.blankj.utilcode.util.PermissionUtils; import com.blankj.utilcode.util.SDCardUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utilcode.util.TimeUtils; import com.blankj.utilcode.util.UriUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.image.ImageViewer; import com.blankj.utildebug.debug.tool.fileExplorer.sp.SpViewerContentView; import com.blankj.utildebug.helper.FileHelper; import com.blankj.utildebug.helper.ImageLoader; import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/05 * desc : * </pre> */ public class FileItem extends BaseItem<FileItem> { private static final ArrayList<FileItem> EMPTY = CollectionUtils.newArrayList(new FileItem()); private FileItem mParent; private File mFile; private String mName; private boolean isSdcard; private RelativeLayout fileContentRl; private ImageView fileTypeIv; private TextView fileNameTv; private TextView fileInfoTv; private TextView fileMenuDeleteTv; public FileItem(File file, String name) { this(file, name, false); } public FileItem(File file, String name, boolean isSdcard) { super(R.layout.du_item_file); mFile = file; mName = name; this.isSdcard = isSdcard; } public FileItem(FileItem parent, File file) { super(R.layout.du_item_file); mParent = parent; mFile = file; mName = file.getName(); } public FileItem() { super(R.layout.du_item_empty); } @Override public void bind(@NonNull ItemViewHolder holder, int position) { if (isViewType(R.layout.du_item_empty)) return; fileContentRl = holder.findViewById(R.id.fileContentRl); fileTypeIv = holder.findViewById(R.id.fileTypeIv); fileNameTv = holder.findViewById(R.id.fileNameTv); fileInfoTv = holder.findViewById(R.id.fileInfoTv); fileMenuDeleteTv = holder.findViewById(R.id.fileMenuDeleteTv); ClickUtils.applyPressedBgDark(fileContentRl); ClickUtils.applyPressedBgDark(fileMenuDeleteTv); fileNameTv.setText(mName); fileMenuDeleteTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean delete = FileUtils.delete(mFile); if (delete) { getAdapter().removeItem(FileItem.this, true); if (getAdapter().getItems().isEmpty()) { getAdapter().addItem(new FileItem()); getAdapter().notifyDataSetChanged(); v.getRootView().findViewById(R.id.fileExplorerSearchEt).setVisibility(View.GONE); } } else { FloatToast.showLong(FloatToast.WARNING, "Delete failed!"); } } }); fileMenuDeleteTv.setVisibility(mParent == null ? View.GONE : View.VISIBLE); if (mFile.isDirectory()) { fileTypeIv.setImageResource(R.drawable.du_ic_debug_file_explorer); fileInfoTv.setText(String.format("%s %s", StringUtils.getString(R.string.du_file_item_num, CollectionUtils.size(mFile.list())), TimeUtils.millis2String(mFile.lastModified(), "yyyy.MM.dd"))); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (isSdcard) { PermissionUtils.permission(PermissionConstants.STORAGE) .callback(new PermissionUtils.SimpleCallback() { @Override public void onGranted() { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); FileContentView.show(floatView, FileItem.this); } @Override public void onDenied() { FloatToast.showShort("Permission of storage denied!"); } }) .request(); } else { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); FileContentView.show(floatView, FileItem.this); } } }); } else { fileInfoTv.setText(String.format("%s %s", FileUtils.getSize(mFile), TimeUtils.millis2String(mFile.lastModified(), "yyyy.MM.dd"))); @FileHelper.FileType int fileType = FileHelper.getFileType(mFile); if (fileType == FileHelper.IMAGE) { ImageLoader.load(mFile, fileTypeIv); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); ImageViewer.show(floatView, mFile); } }); } else if (fileType == FileHelper.UTF8) { fileTypeIv.setImageResource(R.drawable.du_ic_item_file_utf8); } else if (fileType == FileHelper.SP) { fileTypeIv.setImageResource(R.drawable.du_ic_item_file_sp); fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); SpViewerContentView.show(floatView, mFile); } }); } else { fileContentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(UriUtils.file2Uri(mFile)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); ActivityUtils.startActivity(intent); } }); fileTypeIv.setImageResource(R.drawable.du_ic_item_file_default); } } } public File getFile() { return mFile; } public static List<FileItem> getFileItems(final FileItem parent) { if (parent == null) return getFileItems(); List<File> files = FileUtils.listFilesInDir(parent.getFile(), new Comparator<File>() { @Override public int compare(File o1, File o2) { if (o1.isDirectory() && o2.isFile()) { return -1; } else if (o1.isFile() && o2.isDirectory()) { return 1; } else { return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } } }); return (List<FileItem>) CollectionUtils.collect(files, new CollectionUtils.Transformer<File, FileItem>() { @Override public FileItem transform(File input) { return new FileItem(parent, input); } }); } private static List<FileItem> getFileItems() { List<FileItem> fileItems = new ArrayList<>(); String internalAppDataPath = PathUtils.getInternalAppDataPath(); if (!StringUtils.isEmpty(internalAppDataPath)) { File internalDataFile = new File(internalAppDataPath); if (internalDataFile.exists()) { fileItems.add(new FileItem(internalDataFile, "internal")); } } String externalAppDataPath = PathUtils.getExternalAppDataPath(); if (!StringUtils.isEmpty(externalAppDataPath)) { File externalDataFile = new File(externalAppDataPath); if (externalDataFile.exists()) { fileItems.add(new FileItem(externalDataFile, "external")); } } List<String> mountedSDCardPath = SDCardUtils.getMountedSDCardPath(); if (!mountedSDCardPath.isEmpty()) { for (int i = 0; i < mountedSDCardPath.size(); i++) { String path = mountedSDCardPath.get(i); File sdPath = new File(path); if (sdPath.exists()) { fileItems.add(new FileItem(sdPath, "sdcard" + i + "_" + sdPath.getName(), true)); } } } return fileItems; } public static List<FileItem> filterItems(List<FileItem> items, final String key) { return (List<FileItem>) CollectionUtils.select(items, new CollectionUtils.Predicate<FileItem>() { @Override public boolean evaluate(FileItem item) { return item.mName.toLowerCase().contains(key.toLowerCase()); } }); } public static boolean isEmptyItems(List<FileItem> items) { return EMPTY == items; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerDebug.java
package com.blankj.utildebug.debug.tool.fileExplorer; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class FileExplorerDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_file_explorer; } @Override public int getName() { return R.string.du_file_explorer; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new FileExplorerFloatView().show(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerFloatView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/FileExplorerFloatView.java
package com.blankj.utildebug.debug.tool.fileExplorer; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentFloatView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class FileExplorerFloatView extends BaseContentFloatView<FileExplorerFloatView> { @Override public int bindTitle() { return R.string.du_file_explorer; } @Override public int bindContentLayout() { return NO_ID; } @Override public void initContentView() { FileContentView.show(this); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/image/ImageViewer.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/image/ImageViewer.java
package com.blankj.utildebug.debug.tool.fileExplorer.image; import com.blankj.utilcode.util.ImageUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.github.chrisbanes.photoview.PhotoView; import java.io.File; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/08 * desc : * </pre> */ public class ImageViewer extends BaseContentView<FileExplorerFloatView> { private File mFile; private PhotoView photoView; public static void show(FileExplorerFloatView floatView, File file) { new ImageViewer(file).attach(floatView, true); } public ImageViewer(File file) { mFile = file; } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_image; } @Override public void onAttach() { photoView = findViewById(R.id.imageViewerPv); photoView.setImageBitmap(ImageUtils.getBitmap(mFile)); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpViewerContentView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpViewerContentView.java
package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.widget.TextView; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.SearchEditText; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import java.io.File; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/09 * desc : * </pre> */ public class SpViewerContentView extends BaseContentView<FileExplorerFloatView> { private File mFile; private BaseItemAdapter<SpItem> mAdapter; private List<SpItem> mSrcItems; private String mSpName; private SPUtils mSPUtils; private TextView spViewTitle; private SearchEditText spViewSearchEt; private RecyclerView spViewRv; public static void show(FileExplorerFloatView floatView, File file) { new SpViewerContentView(file).attach(floatView, true); } public SpViewerContentView(File file) { mFile = file; mSpName = FileUtils.getFileNameNoExtension(mFile); mSPUtils = SPUtils.getInstance(mSpName); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_sp; } @Override public void onAttach() { spViewTitle = findViewById(R.id.spViewTitle); spViewSearchEt = findViewById(R.id.spViewSearchEt); spViewRv = findViewById(R.id.spViewRv); spViewTitle.setText(mSpName); mAdapter = new BaseItemAdapter<>(); mSrcItems = SpItem.getSpItems(mSPUtils); mAdapter.setItems(mSrcItems); spViewRv.setAdapter(mAdapter); spViewRv.setLayoutManager(new LinearLayoutManager(getContext())); spViewRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); spViewSearchEt.setOnTextChangedListener(new SearchEditText.OnTextChangedListener() { @Override public void onTextChanged(String text) { mAdapter.setItems(SpItem.filterItems(mSrcItems, text)); mAdapter.notifyDataSetChanged(); } }); setOnRefreshListener(spViewRv, new OnRefreshListener() { @Override public void onRefresh(BaseContentFloatView floatView) { mSrcItems = SpItem.getSpItems(mSPUtils); mAdapter.setItems(mSrcItems); mAdapter.notifyDataSetChanged(); spViewSearchEt.reset(); floatView.closeRefresh(); } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpItem.java
package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.CollectionUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.MapUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.SpanUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.blankj.utildebug.helper.SpHelper; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/09 * desc : * </pre> */ public class SpItem extends BaseItem<SpItem> { private SPUtils mSPUtils; private String mKey; private Object mValue; private Class mClass; private RelativeLayout contentRl; private TextView titleTv; private TextView contentTv; private ImageView goIv; private Switch aSwitch; private TextView deleteTv; public SpItem() { super(R.layout.du_item_empty); } public SpItem(SPUtils spUtils, String key, Object value) { super(R.layout.du_item_sp); mSPUtils = spUtils; mKey = key; mValue = value; mClass = mValue.getClass(); } @Override public void bind(@NonNull final ItemViewHolder holder, int position) { if (isViewType(R.layout.du_item_empty)) return; contentRl = holder.findViewById(R.id.itemSpContentRl); titleTv = holder.findViewById(R.id.itemSpTitleTv); contentTv = holder.findViewById(R.id.itemSpContentTv); goIv = holder.findViewById(R.id.itemSpGoIv); aSwitch = holder.findViewById(R.id.itemSpSwitch); deleteTv = holder.findViewById(R.id.itemSpDeleteTv); SpanUtils.with(titleTv) .append(mKey) .append("(" + SpHelper.getSpClassName(mClass) + ")").setForegroundColor(ColorUtils.getColor(R.color.loveGreen)) .create(); contentTv.setText(mValue.toString()); deleteTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FloatToast.showShort("haha"); } }); if (Boolean.class.equals(mClass)) { holder.itemView.setOnTouchListener(null); aSwitch.setVisibility(View.VISIBLE); goIv.setVisibility(View.GONE); aSwitch.setChecked((Boolean) mValue); View.OnClickListener toggle = new View.OnClickListener() { @Override public void onClick(View v) { final boolean state = !(Boolean) mValue; mValue = state; mSPUtils.put(mKey, state); aSwitch.setChecked(state); contentTv.setText(mValue.toString()); } }; aSwitch.setOnClickListener(toggle); contentRl.setOnClickListener(toggle); } else if (HashSet.class.equals(mClass)) { holder.itemView.setOnTouchListener(null); aSwitch.setVisibility(View.GONE); goIv.setVisibility(View.GONE); contentRl.setOnClickListener(null); } else { ClickUtils.applyPressedBgDark(holder.itemView); aSwitch.setVisibility(View.GONE); goIv.setVisibility(View.VISIBLE); contentRl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileExplorerFloatView floatView = (FileExplorerFloatView) v.getRootView(); SpModifyContentView.show(floatView, mSPUtils, mKey, mValue); } }); } } public static List<SpItem> getSpItems(SPUtils spUtils) { Map<String, ?> spMap = spUtils.getAll(); if (MapUtils.isEmpty(spMap)) { return CollectionUtils.newArrayList(new SpItem()); } List<SpItem> items = new ArrayList<>(); for (Map.Entry<String, ?> entry : spMap.entrySet()) { items.add(new SpItem(spUtils, entry.getKey(), entry.getValue())); } return items; } public static List<SpItem> filterItems(List<SpItem> items, final String key) { return (List<SpItem>) CollectionUtils.select(items, new CollectionUtils.Predicate<SpItem>() { @Override public boolean evaluate(SpItem item) { return item.mKey.toLowerCase().contains(key.toLowerCase()); } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpModifyContentView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/sp/SpModifyContentView.java
package com.blankj.utildebug.debug.tool.fileExplorer.sp; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.ColorUtils; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.SpanUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.BaseContentView; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.fileExplorer.FileExplorerFloatView; import com.blankj.utildebug.helper.SpHelper; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/09 * desc : * </pre> */ public class SpModifyContentView extends BaseContentView<FileExplorerFloatView> { private SPUtils mSPUtils; private String mKey; private Object mValue; private Class mClass; private TextView spModifyTitleTv; private EditText spModifyEt; private TextView spModifyCancelTv; private TextView spModifyYesTv; public static void show(FileExplorerFloatView floatView, SPUtils spUtils, String key, Object value) { new SpModifyContentView(spUtils, key, value).attach(floatView, true); } public SpModifyContentView(SPUtils spUtils, String key, Object value) { mSPUtils = spUtils; mKey = key; mValue = value; mClass = value.getClass(); } @Override public int bindLayout() { return R.layout.du_debug_file_explorer_sp_modify; } @Override public void onAttach() { spModifyTitleTv = findViewById(R.id.spModifyTitleTv); spModifyEt = findViewById(R.id.spModifyEt); spModifyCancelTv = findViewById(R.id.spModifyCancelTv); spModifyYesTv = findViewById(R.id.spModifyYesTv); SpanUtils.with(spModifyTitleTv) .append(mKey) .append("(" + SpHelper.getSpClassName(mClass) + ")").setForegroundColor(ColorUtils.getColor(R.color.loveGreen)) .create(); spModifyEt.setText(mValue.toString()); ClickUtils.applyPressedViewScale(spModifyCancelTv, spModifyYesTv); spModifyCancelTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFloatView().back(); } }); spModifyYesTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String val = spModifyEt.getText().toString(); boolean isSuccess = SpHelper.putValue(mSPUtils, mKey, val, mClass); if (isSuccess) { getFloatView().back(); } else { FloatToast.showShort("Type is wrong."); } } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/text/TextViewer.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/fileExplorer/text/TextViewer.java
package com.blankj.utildebug.debug.tool.fileExplorer.text; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/08 * desc : * </pre> */ public class TextViewer { }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/logcat/LogcatDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/logcat/LogcatDebug.java
package com.blankj.utildebug.debug.tool.logcat; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.base.view.FloatToast; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/05 * desc : * </pre> */ public class LogcatDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_logcat; } @Override public int getName() { return R.string.du_logcat; } @Override public void onClick(View view) { FloatToast.showShort(FloatToast.WARNING, "Developing..."); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoDebug.java
package com.blankj.utildebug.debug.tool.appInfo; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class AppInfoDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { int appIconId = AppUtils.getAppIconId(); if (appIconId != 0) return appIconId; return R.drawable.du_ic_debug_app_info_default; } @Override public int getName() { return R.string.du_app_info; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new AppInfoFloatView().show(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoItem.java
package com.blankj.utildebug.debug.tool.appInfo; import android.os.Build; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.StringRes; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import java.util.ArrayList; import java.util.List; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class AppInfoItem extends BaseItem<AppInfoItem> { private String mTitle; private String mContent; private OnClickListener mListener; private TextView titleTv; private TextView contentTv; public AppInfoItem(@StringRes int name, String info) { this(name, info, null); } public AppInfoItem(@StringRes int name, String info, OnClickListener listener) { super(R.layout.du_item_base_info); mTitle = StringUtils.getString(name); mContent = info; mListener = listener; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { titleTv = holder.findViewById(R.id.baseInfoTitleTv); contentTv = holder.findViewById(R.id.baseInfoContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (mListener != null) { ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyGlobalDebouncing(holder.itemView, mListener); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.VISIBLE); } else { holder.itemView.setOnTouchListener(null); holder.itemView.setOnClickListener(null); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.GONE); } } public static List<AppInfoItem> getAppInfoItems() { final List<AppInfoItem> appInfoItems = new ArrayList<>(); appInfoItems.add(new AppInfoItem(R.string.du_app_info_pkg_name, AppUtils.getAppPackageName())); appInfoItems.add(new AppInfoItem(R.string.du_app_info_version_name, AppUtils.getAppVersionName())); appInfoItems.add(new AppInfoItem(R.string.du_app_info_version_code, String.valueOf(AppUtils.getAppVersionCode()))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { appInfoItems.add(new AppInfoItem(R.string.du_app_info_min_sdk_version, String.valueOf(AppUtils.getAppMinSdkVersion()))); } appInfoItems.add(new AppInfoItem(R.string.du_app_info_target_sdk_version, String.valueOf(AppUtils.getAppTargetSdkVersion()))); appInfoItems.add(new AppInfoItem(R.string.du_app_info_open_app_info_page, "", new OnClickListener() { @Override public void onClick(View v) { AppUtils.launchAppDetailsSettings(); } })); return appInfoItems; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoFloatView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/appInfo/AppInfoFloatView.java
package com.blankj.utildebug.debug.tool.appInfo; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class AppInfoFloatView extends BaseContentFloatView<AppInfoFloatView> { private RecyclerView appInfoRv; @Override public int bindTitle() { return R.string.du_app_info; } @Override public int bindContentLayout() { return R.layout.du_debug_app_info; } @Override public void initContentView() { appInfoRv = findViewById(R.id.appInfoRv); BaseItemAdapter<AppInfoItem> adapter = new BaseItemAdapter<>(); adapter.setItems(AppInfoItem.getAppInfoItems()); appInfoRv.setAdapter(adapter); appInfoRv.setLayoutManager(new LinearLayoutManager(getContext())); appInfoRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearCache/ClearCacheDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearCache/ClearCacheDebug.java
package com.blankj.utildebug.debug.tool.clearCache; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.ConvertUtils; import com.blankj.utilcode.util.FileUtils; import com.blankj.utilcode.util.LogUtils; import com.blankj.utilcode.util.PathUtils; import com.blankj.utilcode.util.ThreadUtils; import com.blankj.utilcode.util.ToastUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; import java.io.File; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class ClearCacheDebug extends AbsToolDebug { private ThreadUtils.SimpleTask<Long> clearCacheTask; @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_clear_cache; } @Override public int getName() { return R.string.du_clear_cache; } @Override public void onClick(View view) { clearCache(); } private void clearCache() { DebugMenu.getInstance().dismiss(); if (clearCacheTask != null && !clearCacheTask.isDone()) { ToastUtils.showShort("Cleaning..."); return; } clearCacheTask = createClearCacheTask(); ThreadUtils.executeByIo(clearCacheTask); } private ThreadUtils.SimpleTask<Long> createClearCacheTask() { return new ThreadUtils.SimpleTask<Long>() { @Override public Long doInBackground() throws Throwable { try { long len = 0; File appDataDir = new File(PathUtils.getInternalAppDataPath()); if (appDataDir.exists()) { String[] names = appDataDir.list(); for (String name : names) { if (!name.equals("lib")) { File file = new File(appDataDir, name); len += FileUtils.getLength(file); FileUtils.delete(file); LogUtils.i("「" + file + "」 was deleted."); } } } String externalAppCachePath = PathUtils.getExternalAppCachePath(); len += FileUtils.getLength(externalAppCachePath); FileUtils.delete(externalAppCachePath); LogUtils.i("「" + externalAppCachePath + "」 was deleted."); return len; } catch (Exception e) { ToastUtils.showLong(e.toString()); return -1L; } } @Override public void onSuccess(Long result) { if (result != -1) { ToastUtils.showLong("Clear Cache: " + ConvertUtils.byte2FitMemorySize(result)); } } }; } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoDebug.java
package com.blankj.utildebug.debug.tool.deviceInfo; import android.content.Context; import android.view.View; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; import com.blankj.utildebug.menu.DebugMenu; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_device_info; } @Override public int getName() { return R.string.du_device_info; } @Override public void onClick(View view) { DebugMenu.getInstance().dismiss(); new DeviceInfoFloatView().show(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoItem.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoItem.java
package com.blankj.utildebug.debug.tool.deviceInfo; import android.content.Intent; import android.os.Build; import android.provider.Settings; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.blankj.utilcode.util.ActivityUtils; import com.blankj.utilcode.util.ArrayUtils; import com.blankj.utilcode.util.ClickUtils; import com.blankj.utilcode.util.DeviceUtils; import com.blankj.utilcode.util.ScreenUtils; import com.blankj.utilcode.util.StringUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItem; import com.blankj.utildebug.base.rv.ItemViewHolder; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.StringRes; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoItem extends BaseItem<DeviceInfoItem> { private String mTitle; private String mContent; private OnClickListener mListener; private TextView titleTv; private TextView contentTv; public DeviceInfoItem(@StringRes int name, String info) { this(name, info, null); } public DeviceInfoItem(@StringRes int name, String info, OnClickListener listener) { super(R.layout.du_item_base_info); mTitle = StringUtils.getString(name); mContent = info; mListener = listener; } @Override public void bind(@NonNull ItemViewHolder holder, int position) { titleTv = holder.findViewById(R.id.baseInfoTitleTv); contentTv = holder.findViewById(R.id.baseInfoContentTv); titleTv.setText(mTitle); contentTv.setText(mContent); if (mListener != null) { ClickUtils.applyPressedBgDark(holder.itemView); ClickUtils.applyGlobalDebouncing(holder.itemView, mListener); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.VISIBLE); } else { holder.itemView.setOnTouchListener(null); holder.itemView.setOnClickListener(null); holder.findViewById(R.id.baseInfoGoIv).setVisibility(View.GONE); } } public static List<DeviceInfoItem> getAppInfoItems() { List<DeviceInfoItem> appInfoItems = new ArrayList<>(); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_name, Build.MANUFACTURER + " " + Build.MODEL)); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_android_version, DeviceUtils.getSDKVersionName() + " (" + DeviceUtils.getSDKVersionCode() + ")")); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_adb_enabled, String.valueOf(DeviceUtils.isAdbEnabled()))); } appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_support_abis, ArrayUtils.toString(DeviceUtils.getABIs()))); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_screen_info, getScreenInfo())); appInfoItems.add(new DeviceInfoItem(R.string.du_device_info_open_development_settings_page, "", new OnClickListener() { @Override public void onClick(View v) { ActivityUtils.startActivity(new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)); } })); return appInfoItems; } private static String getScreenInfo() { return "width=" + ScreenUtils.getScreenWidth() + ", height=" + ScreenUtils.getScreenHeight() + ", density=" + ScreenUtils.getScreenDensity(); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoFloatView.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/deviceInfo/DeviceInfoFloatView.java
package com.blankj.utildebug.debug.tool.deviceInfo; import com.blankj.utildebug.R; import com.blankj.utildebug.base.rv.BaseItemAdapter; import com.blankj.utildebug.base.rv.RecycleViewDivider; import com.blankj.utildebug.base.view.BaseContentFloatView; import com.blankj.utildebug.base.view.listener.OnRefreshListener; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/02 * desc : * </pre> */ public class DeviceInfoFloatView extends BaseContentFloatView<DeviceInfoFloatView> { private RecyclerView deviceInfoRv; @Override public int bindTitle() { return R.string.du_device_info; } @Override public int bindContentLayout() { return R.layout.du_debug_device_info; } @Override public void initContentView() { deviceInfoRv = findViewById(R.id.deviceInfoRv); final BaseItemAdapter<DeviceInfoItem> adapter = new BaseItemAdapter<>(); adapter.setItems(DeviceInfoItem.getAppInfoItems()); deviceInfoRv.setAdapter(adapter); deviceInfoRv.setLayoutManager(new LinearLayoutManager(getContext())); deviceInfoRv.addItemDecoration(new RecycleViewDivider(getContext(), RecycleViewDivider.VERTICAL, R.drawable.du_shape_divider)); getContentView().setOnRefreshListener(deviceInfoRv, new OnRefreshListener() { @Override public void onRefresh(final BaseContentFloatView floatView) { adapter.setItems(DeviceInfoItem.getAppInfoItems()); adapter.notifyDataSetChanged(); floatView.closeRefresh(); } }); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearStorage/ClearStorageDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/clearStorage/ClearStorageDebug.java
package com.blankj.utildebug.debug.tool.clearStorage; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utilcode.util.ShellUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class ClearStorageDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_clear_storage; } @Override public int getName() { return R.string.du_clear_storage; } @Override public void onClick(View view) { ShellUtils.execCmd("pm clear " + AppUtils.getAppPackageName(), false); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
Blankj/AndroidUtilCode
https://github.com/Blankj/AndroidUtilCode/blob/7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809/lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/restartApp/RestartAppDebug.java
lib/utildebug/src/main/java/com/blankj/utildebug/debug/tool/restartApp/RestartAppDebug.java
package com.blankj.utildebug.debug.tool.restartApp; import android.content.Context; import android.view.View; import com.blankj.utilcode.util.AppUtils; import com.blankj.utildebug.R; import com.blankj.utildebug.debug.tool.AbsToolDebug; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/04 * desc : * </pre> */ public class RestartAppDebug extends AbsToolDebug { @Override public void onAppCreate(Context context) { } @Override public int getIcon() { return R.drawable.du_ic_debug_restart_app; } @Override public int getName() { return R.string.du_restart_app; } @Override public void onClick(View view) { AppUtils.relaunchApp(true); } }
java
Apache-2.0
7b4caf9e5440046b3fefb63b6b6e2ead7ebaf809
2026-01-04T14:46:34.292032Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/RestClientManager.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/RestClientManager.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; import java.io.IOException; import java.io.InterruptedIOException; import java.net.SocketException; import java.util.HashMap; import java.util.Map; import javax.net.ssl.SSLException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.ServiceUnavailableRetryStrategy; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RestClientManager { private static final Logger logger = LoggerFactory.getLogger(RestClientManager.class); private StatusNotifierNotificationProperties config; private CloseableHttpClient client; private String notifType; private String notifId; public enum NotificationType { TASK, WORKFLOW }; public RestClientManager(StatusNotifierNotificationProperties config) { logger.info("created RestClientManager" + System.currentTimeMillis()); this.config = config; this.client = prepareClient(); } private PoolingHttpClientConnectionManager prepareConnManager() { PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(config.getConnectionPoolMaxRequest()); connManager.setDefaultMaxPerRoute(config.getConnectionPoolMaxRequestPerRoute()); return connManager; } private RequestConfig prepareRequestConfig() { return RequestConfig.custom() // The time to establish the connection with the remote host // [http.connection.timeout]. // Responsible for java.net.SocketTimeoutException: connect timed out. .setConnectTimeout(config.getRequestTimeOutMsConnect()) // The time waiting for data after the connection was established // [http.socket.timeout]. The maximum time // of inactivity between two data packets. Responsible for // java.net.SocketTimeoutException: Read timed out. .setSocketTimeout(config.getRequestTimeoutMsread()) // The time to wait for a connection from the connection manager/pool // [http.connection-manager.timeout]. // Responsible for org.apache.http.conn.ConnectionPoolTimeoutException. .setConnectionRequestTimeout(config.getRequestTimeoutMsConnMgr()) .build(); } /** * Custom HttpRequestRetryHandler implementation to customize retries for different IOException */ private class CustomHttpRequestRetryHandler implements HttpRequestRetryHandler { int maxRetriesCount = config.getRequestRetryCount(); int retryIntervalInMilisec = config.getRequestRetryCountIntervalMs(); /** * Triggered only in case of exception * * @param exception The cause * @param executionCount Retry attempt sequence number * @param context {@link HttpContext} * @return True if we want to retry request, false otherwise */ public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { Throwable rootCause = ExceptionUtils.getRootCause(exception); logger.warn( "Retrying {} notification. Id: {}, root cause: {}", notifType, notifId, rootCause.toString()); if (executionCount >= maxRetriesCount) { logger.warn( "{} notification failed after {} retries. Id: {} .", notifType, executionCount, notifId); return false; } else if (rootCause instanceof SocketException || rootCause instanceof InterruptedIOException || exception instanceof SSLException) { try { Thread.sleep(retryIntervalInMilisec); } catch (InterruptedException e) { e.printStackTrace(); // do nothing } return true; } else return false; } } /** * Custom ServiceUnavailableRetryStrategy implementation to retry on HTTP 503 (= service * unavailable) */ private class CustomServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { int maxRetriesCount = config.getRequestRetryCount(); int retryIntervalInMilisec = config.getRequestRetryCountIntervalMs(); @Override public boolean retryRequest( final HttpResponse response, final int executionCount, final HttpContext context) { int httpStatusCode = response.getStatusLine().getStatusCode(); if (httpStatusCode != 503) return false; // retry only on HTTP 503 if (executionCount >= maxRetriesCount) { logger.warn( "HTTP 503 error. {} notification failed after {} retries. Id: {} .", notifType, executionCount, notifId); return false; } else { logger.warn( "HTTP 503 error. {} notification failed after {} retries. Id: {} .", notifType, executionCount, notifId); return true; } } @Override public long getRetryInterval() { // Retry interval between subsequent requests, in milliseconds. // If not set, the default value is 1000 milliseconds. return retryIntervalInMilisec; } } // By default retries 3 times private CloseableHttpClient prepareClient() { return HttpClients.custom() .setConnectionManager(prepareConnManager()) .setDefaultRequestConfig(prepareRequestConfig()) .setRetryHandler(new CustomHttpRequestRetryHandler()) .setServiceUnavailableRetryStrategy(new CustomServiceUnavailableRetryStrategy()) .build(); } public void postNotification( RestClientManager.NotificationType notifType, String data, String id, StatusNotifier statusNotifier) throws IOException { this.notifType = notifType.toString(); notifId = id; String url = prepareUrl(notifType, statusNotifier); Map<String, String> headers = new HashMap<>(); if (config.getHeaderPrefer() != "" && config.getHeaderPreferValue() != "") headers.put(config.getHeaderPrefer(), config.getHeaderPreferValue()); HttpPost request = createPostRequest(url, data, headers); long start = System.currentTimeMillis(); executePost(request); long duration = System.currentTimeMillis() - start; if (duration > 100) { logger.info("Round trip response time = {} millis", duration); } } private String prepareUrl( RestClientManager.NotificationType notifType, StatusNotifier statusNotifier) { String urlEndPoint = ""; if (notifType == RestClientManager.NotificationType.TASK) { if (statusNotifier != null && StringUtils.isNotBlank(statusNotifier.getEndpointTask())) { urlEndPoint = statusNotifier.getEndpointTask(); } else { urlEndPoint = config.getEndpointTask(); } } else if (notifType == RestClientManager.NotificationType.WORKFLOW) { if (statusNotifier != null && StringUtils.isNotBlank(statusNotifier.getEndpointWorkflow())) { urlEndPoint = statusNotifier.getEndpointWorkflow(); } else { urlEndPoint = config.getEndpointWorkflow(); } } String url; if (statusNotifier != null) { url = statusNotifier.getUrl(); } else { url = config.getUrl(); } return url + "/" + urlEndPoint; } private HttpPost createPostRequest(String url, String data, Map<String, String> headers) throws IOException { HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(data); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); headers.forEach(httpPost::setHeader); return httpPost; } private void executePost(HttpPost httpPost) throws IOException { try (CloseableHttpResponse response = client.execute(httpPost)) { int sc = response.getStatusLine().getStatusCode(); if (!(sc == HttpStatus.SC_ACCEPTED || sc == HttpStatus.SC_OK)) { throw new ClientProtocolException("Unexpected response status: " + sc); } } finally { httpPost.releaseConnection(); // Release the connection gracefully so the connection can // be reused by connection manager } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskNotification.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskNotification.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.run.TaskSummary; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; @JsonFilter("SecretRemovalFilter") public class TaskNotification extends TaskSummary { private static final Logger LOGGER = LoggerFactory.getLogger(TaskStatusPublisher.class); public String workflowTaskType; /** * Following attributes doesnt exist in TaskSummary so add it here. Not adding in TaskSummary as * it belongs to conductor-common */ private String referenceTaskName; private int retryCount; private String taskDescription; private ObjectMapper objectMapper = new ObjectMapper(); public String getReferenceTaskName() { return referenceTaskName; } public int getRetryCount() { return retryCount; } public String getTaskDescription() { return taskDescription; } public TaskNotification(Task task) { super(task); referenceTaskName = task.getReferenceTaskName(); retryCount = task.getRetryCount(); taskDescription = task.getWorkflowTask().getDescription(); workflowTaskType = task.getWorkflowTask().getType(); boolean isFusionMetaPresent = task.getInputData().containsKey("_ioMeta"); if (!isFusionMetaPresent) { return; } } String toJsonString() { String jsonString; SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("input", "output"); FilterProvider provider = new SimpleFilterProvider().addFilter("SecretRemovalFilter", theFilter); try { jsonString = objectMapper.writer(provider).writeValueAsString(this); } catch (JsonProcessingException e) { LOGGER.error("Failed to convert Task: {} to String. Exception: {}", this, e); throw new RuntimeException(e); } return jsonString; } /* * https://github.com/Netflix/conductor/pull/2128 * To enable Workflow/Task Summary Input/Output JSON Serialization, use the following: * conductor.app.summary-input-output-json-serialization.enabled=true */ String toJsonStringWithInputOutput() { String jsonString; try { SimpleBeanPropertyFilter emptyFilter = SimpleBeanPropertyFilter.serializeAllExcept(); FilterProvider provider = new SimpleFilterProvider().addFilter("SecretRemovalFilter", emptyFilter); jsonString = objectMapper.writer(provider).writeValueAsString(this); } catch (JsonProcessingException e) { LOGGER.error("Failed to convert Task: {} to String. Exception: {}", this, e); throw new RuntimeException(e); } return jsonString; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/StatusNotifierNotificationProperties.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/StatusNotifierNotificationProperties.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("conductor.status-notifier.notification") public class StatusNotifierNotificationProperties { private String url; private String endpointTask; /* * TBD: list of Task status we are interested in */ private List<String> subscribedTaskStatuses; private String endpointWorkflow; private String headerPrefer = ""; private String headerPreferValue = ""; private int requestTimeOutMsConnect = 100; private int requestTimeoutMsread = 300; private int requestTimeoutMsConnMgr = 300; private int requestRetryCount = 3; private int requestRetryCountIntervalMs = 50; private int connectionPoolMaxRequest = 3; private int connectionPoolMaxRequestPerRoute = 3; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getEndpointTask() { return endpointTask; } public void setEndpointTask(String endpointTask) { this.endpointTask = endpointTask; } public String getEndpointWorkflow() { return endpointWorkflow; } public void setEndpointWorkflow(String endpointWorkflow) { this.endpointWorkflow = endpointWorkflow; } public String getHeaderPrefer() { return headerPrefer; } public void setHeaderPrefer(String headerPrefer) { this.headerPrefer = headerPrefer; } public String getHeaderPreferValue() { return headerPreferValue; } public void setHeaderPreferValue(String headerPreferValue) { this.headerPreferValue = headerPreferValue; } public int getRequestTimeOutMsConnect() { return requestTimeOutMsConnect; } public void setRequestTimeOutMsConnect(int requestTimeOutMsConnect) { this.requestTimeOutMsConnect = requestTimeOutMsConnect; } public int getRequestTimeoutMsread() { return requestTimeoutMsread; } public void setRequestTimeoutMsread(int requestTimeoutMsread) { this.requestTimeoutMsread = requestTimeoutMsread; } public int getRequestTimeoutMsConnMgr() { return requestTimeoutMsConnMgr; } public void setRequestTimeoutMsConnMgr(int requestTimeoutMsConnMgr) { this.requestTimeoutMsConnMgr = requestTimeoutMsConnMgr; } public int getRequestRetryCount() { return requestRetryCount; } public void setRequestRetryCount(int requestRetryCount) { this.requestRetryCount = requestRetryCount; } public int getRequestRetryCountIntervalMs() { return requestRetryCountIntervalMs; } public void setRequestRetryCountIntervalMs(int requestRetryCountIntervalMs) { this.requestRetryCountIntervalMs = requestRetryCountIntervalMs; } public int getConnectionPoolMaxRequest() { return connectionPoolMaxRequest; } public void setConnectionPoolMaxRequest(int connectionPoolMaxRequest) { this.connectionPoolMaxRequest = connectionPoolMaxRequest; } public int getConnectionPoolMaxRequestPerRoute() { return connectionPoolMaxRequestPerRoute; } public void setConnectionPoolMaxRequestPerRoute(int connectionPoolMaxRequestPerRoute) { this.connectionPoolMaxRequestPerRoute = connectionPoolMaxRequestPerRoute; } public List<String> getSubscribedTaskStatuses() { return subscribedTaskStatuses; } public void setSubscribedTaskStatuses(List<String> subscribedTaskStatuses) { this.subscribedTaskStatuses = subscribedTaskStatuses; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskStatusPublisher.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskStatusPublisher.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; import java.io.IOException; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.core.dal.ExecutionDAOFacade; import com.netflix.conductor.core.listener.TaskStatusListener; import com.netflix.conductor.model.TaskModel; @Singleton public class TaskStatusPublisher implements TaskStatusListener { private static final Logger LOGGER = LoggerFactory.getLogger(TaskStatusPublisher.class); private static final Integer QDEPTH = Integer.parseInt( System.getenv().getOrDefault("ENV_TASK_NOTIFICATION_QUEUE_SIZE", "50")); private BlockingQueue<TaskModel> blockingQueue = new LinkedBlockingDeque<>(QDEPTH); private RestClientManager rcm; private ExecutionDAOFacade executionDAOFacade; private List<String> subscribedTaskStatusList; class ExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { LOGGER.info("An exception has been captured\n"); LOGGER.info("Thread: {}\n", t.getName()); LOGGER.info("Exception: {}: {}\n", e.getClass().getName(), e.getMessage()); LOGGER.info("Stack Trace: \n"); e.printStackTrace(System.out); LOGGER.info("Thread status: {}\n", t.getState()); new ConsumerThread().start(); } } class ConsumerThread extends Thread { public void run() { this.setUncaughtExceptionHandler(new ExceptionHandler()); String tName = Thread.currentThread().getName(); LOGGER.info("{}: Starting consumer thread", tName); TaskModel task = null; TaskNotification taskNotification = null; while (true) { try { task = blockingQueue.take(); taskNotification = new TaskNotification(task.toTask()); String jsonTask = taskNotification.toJsonString(); LOGGER.info("Publishing TaskNotification: {}", jsonTask); if (taskNotification.getTaskType().equals("SUB_WORKFLOW")) { LOGGER.info( "Skip task '{}' notification. Task type is SUB_WORKFLOW.", taskNotification.getTaskId()); continue; } publishTaskNotification(taskNotification); LOGGER.debug("Task {} publish is successful.", taskNotification.getTaskId()); Thread.sleep(5); } catch (Exception e) { if (taskNotification != null) { LOGGER.error( "Error while publishing task. Hence updating elastic search index taskId {} taskname {}", task.getTaskId(), task.getTaskDefName()); // TBD executionDAOFacade.indexTask(task); } else { LOGGER.error("Failed to publish task: Task is NULL"); } LOGGER.error("Error on publishing ", e); } } } } @Inject public TaskStatusPublisher( RestClientManager rcm, ExecutionDAOFacade executionDAOFacade, List<String> subscribedTaskStatuses) { this.rcm = rcm; this.executionDAOFacade = executionDAOFacade; this.subscribedTaskStatusList = subscribedTaskStatuses; validateSubscribedTaskStatuses(subscribedTaskStatuses); ConsumerThread consumerThread = new ConsumerThread(); consumerThread.start(); } private void validateSubscribedTaskStatuses(List<String> subscribedTaskStatuses) { for (String taskStausType : subscribedTaskStatuses) { if (!taskStausType.equals("SCHEDULED")) { LOGGER.error( "Task Status Type {} will only push notificaitons when updated through the API. Automatic notifications only work for SCHEDULED type.", taskStausType); } } } private void enqueueTask(TaskModel task) { try { blockingQueue.put(task); } catch (Exception e) { LOGGER.debug( "Failed to enqueue task: Id {} Type {} of workflow {} ", task.getTaskId(), task.getTaskType(), task.getWorkflowInstanceId()); LOGGER.debug(e.toString()); } } @Override public void onTaskScheduled(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.SCHEDULED.name())) { enqueueTask(task); } } @Override public void onTaskCanceled(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.CANCELED.name())) { enqueueTask(task); } } @Override public void onTaskCompleted(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.COMPLETED.name())) { enqueueTask(task); } } @Override public void onTaskCompletedWithErrors(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.COMPLETED_WITH_ERRORS.name())) { enqueueTask(task); } } @Override public void onTaskFailed(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.FAILED.name())) { enqueueTask(task); } } @Override public void onTaskFailedWithTerminalError(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.FAILED_WITH_TERMINAL_ERROR.name())) { enqueueTask(task); } } @Override public void onTaskInProgress(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.IN_PROGRESS.name())) { enqueueTask(task); } } @Override public void onTaskSkipped(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.SKIPPED.name())) { enqueueTask(task); } } @Override public void onTaskTimedOut(TaskModel task) { if (subscribedTaskStatusList.contains(TaskModel.Status.TIMED_OUT.name())) { enqueueTask(task); } } private void publishTaskNotification(TaskNotification taskNotification) throws IOException { String jsonTask = taskNotification.toJsonStringWithInputOutput(); rcm.postNotification( RestClientManager.NotificationType.TASK, jsonTask, taskNotification.getTaskId(), null); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/StatusNotifier.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/StatusNotifier.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; public class StatusNotifier { private String url; private String endpointTask; private String endpointWorkflow; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getEndpointTask() { return endpointTask; } public void setEndpointTask(String endpointTask) { this.endpointTask = endpointTask; } public String getEndpointWorkflow() { return endpointWorkflow; } public void setEndpointWorkflow(String endpointWorkflow) { this.endpointWorkflow = endpointWorkflow; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskStatusPublisherConfiguration.java
task-status-listener/src/main/java/com/netflix/conductor/contribs/listener/TaskStatusPublisherConfiguration.java
/* * Copyright 2024 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.contribs.listener; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.conductor.core.dal.ExecutionDAOFacade; import com.netflix.conductor.core.listener.TaskStatusListener; @Configuration @EnableConfigurationProperties(StatusNotifierNotificationProperties.class) @ConditionalOnProperty(name = "conductor.task-status-listener.type", havingValue = "task_publisher") public class TaskStatusPublisherConfiguration { @Bean public TaskStatusListener getTaskStatusListener( RestClientManager rcm, ExecutionDAOFacade executionDAOFacade, StatusNotifierNotificationProperties config) { return new TaskStatusPublisher(rcm, executionDAOFacade, config.getSubscribedTaskStatuses()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueueTest.java
awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueueTest.java
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.eventqueue; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.stubbing.Answer; import com.netflix.conductor.core.events.queue.Message; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.util.concurrent.Uninterruptibles; import rx.Observable; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; import software.amazon.awssdk.services.sqs.model.ListQueuesResponse; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SQSObservableQueueTest { @Test public void test() { List<Message> messages = new LinkedList<>(); Observable.range(0, 10) .forEach((Integer x) -> messages.add(new Message("" + x, "payload: " + x, null))); assertEquals(10, messages.size()); SQSObservableQueue queue = mock(SQSObservableQueue.class); when(queue.getOrCreateQueue()).thenReturn("junit_queue_url"); Answer<?> answer = (Answer<List<Message>>) invocation -> Collections.emptyList(); when(queue.receiveMessages()).thenReturn(messages).thenAnswer(answer); when(queue.isRunning()).thenReturn(true); when(queue.getOnSubscribe()).thenCallRealMethod(); when(queue.observe()).thenCallRealMethod(); List<Message> found = new LinkedList<>(); Observable<Message> observable = queue.observe(); assertNotNull(observable); observable.subscribe(found::add); Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS); assertEquals(messages.size(), found.size()); assertEquals(messages, found); } @Test public void testException() { software.amazon.awssdk.services.sqs.model.Message message = software.amazon.awssdk.services.sqs.model.Message.builder() .messageId("test") .body("") .receiptHandle("receiptHandle") .build(); Answer<?> answer = (Answer<ReceiveMessageResponse>) invocation -> ReceiveMessageResponse.builder().build(); SqsClient client = mock(SqsClient.class); when(client.listQueues(any(ListQueuesRequest.class))) .thenReturn(ListQueuesResponse.builder().queueUrls("junit_queue_url").build()); when(client.receiveMessage(any(ReceiveMessageRequest.class))) .thenThrow(new RuntimeException("Error in SQS communication")) .thenReturn(ReceiveMessageResponse.builder().messages(message).build()) .thenAnswer(answer); SQSObservableQueue queue = new SQSObservableQueue.Builder().withQueueName("junit").withClient(client).build(); queue.start(); List<Message> found = new LinkedList<>(); Observable<Message> observable = queue.observe(); assertNotNull(observable); observable.subscribe(found::add); Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS); assertEquals(1, found.size()); } @Test public void testPolicyJsonFormat() throws Exception { // Mock SQS client SqsClient client = mock(SqsClient.class); when(client.listQueues(any(ListQueuesRequest.class))) .thenReturn( ListQueuesResponse.builder() .queueUrls( "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue") .build()); when(client.getQueueAttributes(any(GetQueueAttributesRequest.class))) .thenReturn( GetQueueAttributesResponse.builder() .attributesWithStrings( Collections.singletonMap( "QueueArn", "arn:aws:sqs:us-east-1:123456789012:test-queue")) .build()); // Create queue instance using reflection to access private getPolicy method SQSObservableQueue queue = new SQSObservableQueue.Builder() .withQueueName("test-queue") .withClient(client) .build(); // Use reflection to call private getPolicy method Method getPolicyMethod = SQSObservableQueue.class.getDeclaredMethod("getPolicy", List.class); getPolicyMethod.setAccessible(true); List<String> accountIds = Arrays.asList("111122223333", "444455556666"); String policyJson = (String) getPolicyMethod.invoke(queue, accountIds); // Parse the JSON and verify structure ObjectMapper mapper = new ObjectMapper(); JsonNode policyNode = mapper.readTree(policyJson); // Verify top-level fields have correct capitalization assertTrue("Policy must have 'Version' field", policyNode.has("Version")); assertTrue("Policy must have 'Statement' field", policyNode.has("Statement")); assertEquals("2012-10-17", policyNode.get("Version").asText()); // Verify Statement array JsonNode statementArray = policyNode.get("Statement"); assertTrue("Statement must be an array", statementArray.isArray()); assertEquals(1, statementArray.size()); // Verify Statement object fields JsonNode statement = statementArray.get(0); assertTrue("Statement must have 'Effect' field", statement.has("Effect")); assertTrue("Statement must have 'Principal' field", statement.has("Principal")); assertTrue("Statement must have 'Action' field", statement.has("Action")); assertTrue("Statement must have 'Resource' field", statement.has("Resource")); assertEquals("Allow", statement.get("Effect").asText()); assertEquals("sqs:SendMessage", statement.get("Action").asText()); assertEquals( "arn:aws:sqs:us-east-1:123456789012:test-queue", statement.get("Resource").asText()); // Verify Principal object JsonNode principal = statement.get("Principal"); assertTrue("Principal must have 'AWS' field", principal.has("AWS")); JsonNode awsArray = principal.get("AWS"); assertTrue("AWS must be an array", awsArray.isArray()); assertEquals(2, awsArray.size()); assertEquals("111122223333", awsArray.get(0).asText()); assertEquals("444455556666", awsArray.get(1).asText()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/DefaultEventQueueProcessorTest.java
awssqs-event-queue/src/test/java/com/netflix/conductor/sqs/eventqueue/DefaultEventQueueProcessorTest.java
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.eventqueue; import java.util.*; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.core.events.queue.DefaultEventQueueProcessor; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.core.execution.WorkflowExecutor; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.model.TaskModel.Status; import com.netflix.conductor.model.WorkflowModel; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.util.concurrent.Uninterruptibles; import static com.netflix.conductor.common.metadata.tasks.TaskType.TASK_TYPE_WAIT; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class DefaultEventQueueProcessorTest { private static SQSObservableQueue queue; private static WorkflowExecutor workflowExecutor; private DefaultEventQueueProcessor defaultEventQueueProcessor; @Autowired private ObjectMapper objectMapper; private static final List<Message> messages = new LinkedList<>(); private static final List<TaskResult> updatedTasks = new LinkedList<>(); @BeforeClass public static void setupMocks() { queue = mock(SQSObservableQueue.class); when(queue.getOrCreateQueue()).thenReturn("junit_queue_url"); when(queue.isRunning()).thenReturn(true); when(queue.receiveMessages()) .thenAnswer( (Answer<List<Message>>) invocation -> { List<Message> copy = new ArrayList<>(messages); messages.clear(); return copy; }); when(queue.getOnSubscribe()).thenCallRealMethod(); when(queue.observe()).thenCallRealMethod(); when(queue.getName()).thenReturn(Status.COMPLETED.name()); doAnswer( invocation -> { List<Message> msgs = invocation.getArgument(0); messages.addAll(msgs); return null; }) .when(queue) .publish(any()); workflowExecutor = mock(WorkflowExecutor.class); assertNotNull(workflowExecutor); TaskModel task0 = createTask("t0", TASK_TYPE_WAIT, Status.IN_PROGRESS); WorkflowModel workflow0 = createWorkflow("v_0", task0); doReturn(workflow0).when(workflowExecutor).getWorkflow(eq("v_0"), anyBoolean()); TaskModel task2 = createTask("t2", TASK_TYPE_WAIT, Status.IN_PROGRESS); WorkflowModel workflow2 = createWorkflow("v_2", task2); doReturn(workflow2).when(workflowExecutor).getWorkflow(eq("v_2"), anyBoolean()); doAnswer( invocation -> { TaskResult result = invocation.getArgument(0); updatedTasks.add(result); return null; }) .when(workflowExecutor) .updateTask(any(TaskResult.class)); } @Before public void initProcessor() { messages.clear(); updatedTasks.clear(); Map<Status, ObservableQueue> queues = new HashMap<>(); queues.put(Status.COMPLETED, queue); defaultEventQueueProcessor = new DefaultEventQueueProcessor(queues, workflowExecutor, objectMapper); } @Test public void shouldUpdateTaskByReferenceName() throws Exception { defaultEventQueueProcessor.updateByTaskRefName( "v_0", "t0", new HashMap<>(), Status.COMPLETED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); assertTrue(updatedTasks.stream().anyMatch(task -> "t0".equals(task.getTaskId()))); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionForUnknownWorkflow() throws Exception { defaultEventQueueProcessor.updateByTaskRefName( "v_1", "t1", new HashMap<>(), Status.CANCELED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); } @Test public void shouldUpdateTaskByTaskId() throws Exception { defaultEventQueueProcessor.updateByTaskId("v_2", "t2", new HashMap<>(), Status.COMPLETED); Uninterruptibles.sleepUninterruptibly(1_000, TimeUnit.MILLISECONDS); assertTrue(updatedTasks.stream().anyMatch(task -> "t2".equals(task.getTaskId()))); } private static TaskModel createTask(String taskId, String type, Status status) { TaskModel task = new TaskModel(); task.setTaskId(taskId); task.setTaskType(type); task.setStatus(status); task.setReferenceTaskName(taskId); return task; } private static WorkflowModel createWorkflow(String workflowId, TaskModel task) { WorkflowModel workflow = new WorkflowModel(); workflow.setWorkflowId(workflowId); workflow.getTasks().add(task); return workflow; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueue.java
awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/eventqueue/SQSObservableQueue.java
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.eventqueue; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.metrics.Monitors; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Scheduler; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.BatchResultErrorEntry; import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResponse; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; import software.amazon.awssdk.services.sqs.model.ListQueuesResponse; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesResponse; public class SQSObservableQueue implements ObservableQueue { private static final Logger LOGGER = LoggerFactory.getLogger(SQSObservableQueue.class); private static final String QUEUE_TYPE = "sqs"; private final String queueName; private final int visibilityTimeoutInSeconds; private final int batchSize; private final SqsClient client; private final long pollTimeInMS; private final String queueURL; private final Scheduler scheduler; private volatile boolean running; private SQSObservableQueue( String queueName, SqsClient client, int visibilityTimeoutInSeconds, int batchSize, long pollTimeInMS, List<String> accountsToAuthorize, Scheduler scheduler) { this.queueName = queueName; this.client = client; this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds; this.batchSize = batchSize; this.pollTimeInMS = pollTimeInMS; this.queueURL = getOrCreateQueue(); this.scheduler = scheduler; addPolicy(accountsToAuthorize); } @Override public Observable<Message> observe() { OnSubscribe<Message> subscriber = getOnSubscribe(); return Observable.create(subscriber); } @Override public List<String> ack(List<Message> messages) { return delete(messages); } @Override public void publish(List<Message> messages) { publishMessages(messages); } @Override public long size() { try { GetQueueAttributesRequest request = GetQueueAttributesRequest.builder() .queueUrl(queueURL) .attributeNames(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES) .build(); GetQueueAttributesResponse response = client.getQueueAttributes(request); String sizeAsStr = response.attributes().get(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES); return Long.parseLong(sizeAsStr); } catch (Exception e) { return -1; } } @Override public void setUnackTimeout(Message message, long unackTimeout) { int unackTimeoutInSeconds = (int) (unackTimeout / 1000); ChangeMessageVisibilityRequest request = ChangeMessageVisibilityRequest.builder() .queueUrl(queueURL) .receiptHandle(message.getReceipt()) .visibilityTimeout(unackTimeoutInSeconds) .build(); client.changeMessageVisibility(request); } @Override public String getType() { return QUEUE_TYPE; } @Override public String getName() { return queueName; } @Override public String getURI() { return queueURL; } public long getPollTimeInMS() { return pollTimeInMS; } public int getBatchSize() { return batchSize; } public int getVisibilityTimeoutInSeconds() { return visibilityTimeoutInSeconds; } @Override public void start() { LOGGER.info("Started listening to {}:{}", getClass().getSimpleName(), queueName); running = true; } @Override public void stop() { LOGGER.info("Stopped listening to {}:{}", getClass().getSimpleName(), queueName); running = false; } @Override public boolean isRunning() { return running; } public static class Builder { private String queueName; private int visibilityTimeout = 30; // seconds private int batchSize = 5; private long pollTimeInMS = 100; private SqsClient client; private List<String> accountsToAuthorize = new LinkedList<>(); private Scheduler scheduler; public Builder withQueueName(String queueName) { this.queueName = queueName; return this; } /** * @param visibilityTimeout Visibility timeout for the message in SECONDS * @return builder instance */ public Builder withVisibilityTimeout(int visibilityTimeout) { this.visibilityTimeout = visibilityTimeout; return this; } public Builder withBatchSize(int batchSize) { this.batchSize = batchSize; return this; } public Builder withClient(SqsClient client) { this.client = client; return this; } public Builder withPollTimeInMS(long pollTimeInMS) { this.pollTimeInMS = pollTimeInMS; return this; } public Builder withAccountsToAuthorize(List<String> accountsToAuthorize) { this.accountsToAuthorize = accountsToAuthorize; return this; } public Builder addAccountToAuthorize(String accountToAuthorize) { this.accountsToAuthorize.add(accountToAuthorize); return this; } public Builder withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } public SQSObservableQueue build() { return new SQSObservableQueue( queueName, client, visibilityTimeout, batchSize, pollTimeInMS, accountsToAuthorize, scheduler); } } // Private methods String getOrCreateQueue() { List<String> queueUrls = listQueues(queueName); if (queueUrls == null || queueUrls.isEmpty()) { CreateQueueRequest createQueueRequest = CreateQueueRequest.builder().queueName(queueName).build(); CreateQueueResponse result = client.createQueue(createQueueRequest); return result.queueUrl(); } else { return queueUrls.get(0); } } private String getQueueARN() { GetQueueAttributesRequest request = GetQueueAttributesRequest.builder() .queueUrl(queueURL) .attributeNames(QueueAttributeName.QUEUE_ARN) .build(); GetQueueAttributesResponse response = client.getQueueAttributes(request); return response.attributes().get(QueueAttributeName.QUEUE_ARN); } private void addPolicy(List<String> accountsToAuthorize) { if (accountsToAuthorize == null || accountsToAuthorize.isEmpty()) { LOGGER.info("No additional security policies attached for the queue " + queueName); return; } LOGGER.info("Authorizing " + accountsToAuthorize + " to the queue " + queueName); Map<QueueAttributeName, String> attributes = new HashMap<>(); attributes.put(QueueAttributeName.POLICY, getPolicy(accountsToAuthorize)); SetQueueAttributesRequest request = SetQueueAttributesRequest.builder() .queueUrl(queueURL) .attributes(attributes) .build(); SetQueueAttributesResponse result = client.setQueueAttributes(request); LOGGER.info("policy attachment result: " + result); LOGGER.info("policy attachment result: status=" + result.sdkHttpResponse().statusCode()); } private String getPolicy(List<String> accountIds) { if (accountIds == null || accountIds.isEmpty()) { return null; } try { SqsPolicy policy = new SqsPolicy(); policy.setVersion("2012-10-17"); SqsStatement statement = new SqsStatement(); statement.setEffect("Allow"); statement.setAction("sqs:SendMessage"); statement.setResource(getQueueARN()); SqsPrincipal principal = new SqsPrincipal(); principal.setAws(new ArrayList<>(accountIds)); statement.setPrincipal(principal); policy.setStatement(List.of(statement)); ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(policy); } catch (JsonProcessingException e) { LOGGER.error("Failed to generate SQS policy for accounts: {}", accountIds, e); throw new RuntimeException("Failed to generate SQS policy", e); } } private List<String> listQueues(String queueName) { ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(queueName).build(); ListQueuesResponse resultList = client.listQueues(listQueuesRequest); return resultList.queueUrls().stream() .filter(queueUrl -> queueUrl.contains(queueName)) .collect(Collectors.toList()); } private void publishMessages(List<Message> messages) { LOGGER.debug("Sending {} messages to the SQS queue: {}", messages.size(), queueName); List<SendMessageBatchRequestEntry> entries = messages.stream() .map( msg -> SendMessageBatchRequestEntry.builder() .id(msg.getId()) .messageBody(msg.getPayload()) .build()) .collect(Collectors.toList()); SendMessageBatchRequest batch = SendMessageBatchRequest.builder().queueUrl(queueURL).entries(entries).build(); LOGGER.debug("sending {} messages in batch", entries.size()); SendMessageBatchResponse result = client.sendMessageBatch(batch); LOGGER.debug("send result: {} for SQS queue: {}", result.failed().toString(), queueName); } List<Message> receiveMessages() { try { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueURL) .visibilityTimeout(visibilityTimeoutInSeconds) .maxNumberOfMessages(batchSize) .build(); ReceiveMessageResponse result = client.receiveMessage(receiveMessageRequest); List<Message> messages = result.messages().stream() .map( msg -> new Message( msg.messageId(), msg.body(), msg.receiptHandle())) .collect(Collectors.toList()); Monitors.recordEventQueueMessagesProcessed(QUEUE_TYPE, this.queueName, messages.size()); return messages; } catch (Exception e) { LOGGER.error("Exception while getting messages from SQS", e); Monitors.recordObservableQMessageReceivedErrors(QUEUE_TYPE); } return new ArrayList<>(); } OnSubscribe<Message> getOnSubscribe() { return subscriber -> { Observable<Long> interval = Observable.interval(pollTimeInMS, TimeUnit.MILLISECONDS); interval.flatMap( (Long x) -> { if (!isRunning()) { LOGGER.debug( "Component stopped, skip listening for messages from SQS"); return Observable.from(Collections.emptyList()); } List<Message> messages = receiveMessages(); return Observable.from(messages); }) .subscribe(subscriber::onNext, subscriber::onError); }; } private List<String> delete(List<Message> messages) { if (messages == null || messages.isEmpty()) { return null; } List<DeleteMessageBatchRequestEntry> entries = messages.stream() .map( m -> DeleteMessageBatchRequestEntry.builder() .id(m.getId()) .receiptHandle(m.getReceipt()) .build()) .collect(Collectors.toList()); DeleteMessageBatchRequest batch = DeleteMessageBatchRequest.builder().queueUrl(queueURL).entries(entries).build(); DeleteMessageBatchResponse result = client.deleteMessageBatch(batch); List<String> failures = result.failed().stream() .map(BatchResultErrorEntry::id) .collect(Collectors.toList()); LOGGER.debug("Failed to delete messages from queue: {}: {}", queueName, failures); return failures; } private static class SqsPolicy { @JsonProperty("Version") private String version; @JsonProperty("Statement") private List<SqsStatement> statement; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<SqsStatement> getStatement() { return statement; } public void setStatement(List<SqsStatement> statement) { this.statement = statement; } } private static class SqsStatement { @JsonProperty("Effect") private String effect; @JsonProperty("Principal") private SqsPrincipal principal; @JsonProperty("Action") private String action; @JsonProperty("Resource") private String resource; public String getEffect() { return effect; } public void setEffect(String effect) { this.effect = effect; } public SqsPrincipal getPrincipal() { return principal; } public void setPrincipal(SqsPrincipal principal) { this.principal = principal; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } } private static class SqsPrincipal { @JsonProperty("AWS") private List<String> aws; public List<String> getAws() { return aws; } public void setAws(List<String> aws) { this.aws = aws; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProperties.java
awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProperties.java
/* * Copyright 2020 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.config; import java.time.Duration; import java.time.temporal.ChronoUnit; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.convert.DurationUnit; @ConfigurationProperties("conductor.event-queues.sqs") public class SQSEventQueueProperties { /** The maximum number of messages to be fetched from the queue in a single request */ private int batchSize = 1; /** The polling interval (in milliseconds) */ private Duration pollTimeDuration = Duration.ofMillis(100); /** The visibility timeout (in seconds) for the message on the queue */ @DurationUnit(ChronoUnit.SECONDS) private Duration visibilityTimeout = Duration.ofSeconds(60); /** The prefix to be used for the default listener queues */ private String listenerQueuePrefix = ""; /** The AWS account Ids authorized to send messages to the queues */ private String authorizedAccounts = ""; /** The endpoint to use to connect to a local SQS server for testing */ private String endpoint = ""; public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public Duration getPollTimeDuration() { return pollTimeDuration; } public void setPollTimeDuration(Duration pollTimeDuration) { this.pollTimeDuration = pollTimeDuration; } public Duration getVisibilityTimeout() { return visibilityTimeout; } public void setVisibilityTimeout(Duration visibilityTimeout) { this.visibilityTimeout = visibilityTimeout; } public String getListenerQueuePrefix() { return listenerQueuePrefix; } public void setListenerQueuePrefix(String listenerQueuePrefix) { this.listenerQueuePrefix = listenerQueuePrefix; } public String getAuthorizedAccounts() { return authorizedAccounts; } public void setAuthorizedAccounts(String authorizedAccounts) { this.authorizedAccounts = authorizedAccounts; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueConfiguration.java
awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueConfiguration.java
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.config; import java.net.URI; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.model.TaskModel.Status; import com.netflix.conductor.sqs.eventqueue.SQSObservableQueue.Builder; import rx.Scheduler; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.SqsClientBuilder; @Configuration @EnableConfigurationProperties(SQSEventQueueProperties.class) @ConditionalOnProperty(name = "conductor.event-queues.sqs.enabled", havingValue = "true") public class SQSEventQueueConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(SQSEventQueueConfiguration.class); @Autowired private SQSEventQueueProperties sqsProperties; @Bean AwsCredentialsProvider createAWSCredentialsProvider() { return DefaultCredentialsProvider.create(); } @ConditionalOnMissingBean @Bean public SqsClient getSQSClient(AwsCredentialsProvider credentialsProvider) { SqsClientBuilder builder = SqsClient.builder().credentialsProvider(credentialsProvider); // Set region - try to get from environment or properties String region = System.getenv("AWS_REGION"); if (region != null && !region.isEmpty()) { builder.region(Region.of(region)); } else { // Fallback to default region if not specified builder.region(Region.US_EAST_1); } if (!sqsProperties.getEndpoint().isEmpty()) { LOGGER.info("Setting custom SQS endpoint to {}", sqsProperties.getEndpoint()); builder.endpointOverride(URI.create(sqsProperties.getEndpoint())); } return builder.build(); } @Bean public EventQueueProvider sqsEventQueueProvider( SqsClient sqsClient, SQSEventQueueProperties properties, Scheduler scheduler) { return new SQSEventQueueProvider(sqsClient, properties, scheduler); } @ConditionalOnProperty( name = "conductor.default-event-queue.type", havingValue = "sqs", matchIfMissing = true) @Bean public Map<Status, ObservableQueue> getQueues( ConductorProperties conductorProperties, SQSEventQueueProperties properties, SqsClient sqsClient) { String stack = ""; if (conductorProperties.getStack() != null && conductorProperties.getStack().length() > 0) { stack = conductorProperties.getStack() + "_"; } Status[] statuses = new Status[] {Status.COMPLETED, Status.FAILED}; Map<Status, ObservableQueue> queues = new HashMap<>(); for (Status status : statuses) { String queuePrefix = StringUtils.isBlank(properties.getListenerQueuePrefix()) ? conductorProperties.getAppId() + "_sqs_notify_" + stack : properties.getListenerQueuePrefix(); String queueName = queuePrefix + status.name(); Builder builder = new Builder().withClient(sqsClient).withQueueName(queueName); String auth = properties.getAuthorizedAccounts(); String[] accounts = auth.split(","); for (String accountToAuthorize : accounts) { accountToAuthorize = accountToAuthorize.trim(); if (accountToAuthorize.length() > 0) { builder.addAccountToAuthorize(accountToAuthorize.trim()); } } ObservableQueue queue = builder.build(); queues.put(status, queue); } return queues; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProvider.java
awssqs-event-queue/src/main/java/com/netflix/conductor/sqs/config/SQSEventQueueProvider.java
/* * Copyright 2022 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.sqs.config; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.lang.NonNull; import com.netflix.conductor.core.events.EventQueueProvider; import com.netflix.conductor.core.events.queue.ObservableQueue; import com.netflix.conductor.sqs.eventqueue.SQSObservableQueue; import rx.Scheduler; import software.amazon.awssdk.services.sqs.SqsClient; public class SQSEventQueueProvider implements EventQueueProvider { private final Map<String, ObservableQueue> queues = new ConcurrentHashMap<>(); private final SqsClient client; private final int batchSize; private final long pollTimeInMS; private final int visibilityTimeoutInSeconds; private final Scheduler scheduler; public SQSEventQueueProvider( SqsClient client, SQSEventQueueProperties properties, Scheduler scheduler) { this.client = client; this.batchSize = properties.getBatchSize(); this.pollTimeInMS = properties.getPollTimeDuration().toMillis(); this.visibilityTimeoutInSeconds = (int) properties.getVisibilityTimeout().getSeconds(); this.scheduler = scheduler; } @Override public String getQueueType() { return "sqs"; } @Override @NonNull public ObservableQueue getQueue(String queueURI) { return queues.computeIfAbsent( queueURI, q -> new SQSObservableQueue.Builder() .withBatchSize(this.batchSize) .withClient(client) .withPollTimeInMS(this.pollTimeInMS) .withQueueName(queueURI) .withVisibilityTimeout(this.visibilityTimeoutInSeconds) .withScheduler(scheduler) .build()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false