### Transparent Activity Utilities (Main Process) Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for starting transparent Activities in the main process. ```java start: 启动主线程的透明 Activity ``` -------------------------------- ### Transparent Activity Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for starting transparent Activities, useful for overlaying UI elements. ```java start: 启动随当前线程的透明 Activity ``` -------------------------------- ### Application Management API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Provides methods for managing application status, installation, uninstallation, and retrieving application information. ```APIDOC AppUtils: registerAppStatusChangedListener(listener: OnAppStatusChangedListener): void Registers an app status changed listener. unregisterAppStatusChangedListener(listener: OnAppStatusChangedListener): void Unregisters an app status changed listener. installApp(filePath: String, intentFilter: String): boolean Installs an app (supports 8.0). uninstallApp(packageName: String): boolean Uninstalls an app. isAppInstalled(packageName: String): boolean Checks if an app is installed. isAppRoot(): boolean Checks if the app has root permission. isAppDebug(): boolean Checks if the app is a debug version. isAppSystem(): boolean Checks if the app is a system app. isAppForeground(): boolean Checks if the app is in the foreground. isAppRunning(packageName: String): boolean Checks if an app is running. launchApp(packageName: String): void Launches an app. relaunchApp(): void Relaunches the current app. launchAppDetailsSettings(): void Launches the app details settings. exitApp(): void Exits the app. getAppIcon(packageName: String): Drawable Gets the app icon. getAppPackageName(): String Gets the app package name. getAppName(packageName: String): String Gets the app name. getAppPath(packageName: String): String Gets the app path. getAppVersionName(packageName: String): String Gets the app version name. getAppVersionCode(packageName: String): Int Gets the app version code. getAppMinSdkVersion(packageName: String): Int Gets the app minimum supported SDK version. getAppTargetSdkVersion(packageName: String): Int Gets the app target SDK version. getAppSignatures(packageName: String): Array Gets the app signatures. getAppSignaturesSHA1(packageName: String): String Gets the SHA1 value of the app signature. getAppSignaturesSHA256(packageName: String): String Gets the SHA256 value of the app signature. getAppSignaturesMD5(packageName: String): String Gets the MD5 value of the app signature. getAppInfo(packageName: String): AppInfo Gets app information. getAppsInfo(): List Gets information for all installed apps. getApkInfo(filePath: String): ApkInfo Gets Apk information. isFirstTimeInstalled(packageName: String): boolean Checks if the app is installed for the first time. ``` -------------------------------- ### App Management API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing application status, installation, uninstallation, launching, and retrieving app information. ```APIDOC AppUtils: registerAppStatusChangedListener(listener: Application.ActivityLifecycleCallbacks) Registers a listener for application status changes. unregisterAppStatusChangedListener(listener: Application.ActivityLifecycleCallbacks) Unregisters a previously registered application status listener. installApp(filePath: String) Installs an application from the given file path. installApp(file: File) Installs an application from the given File object. uninstallApp(packageName: String) Uninstalls the application with the specified package name. uninstallApp(packageName: String, flags: Int) Uninstalls the application with the specified package name and flags. isAppInstalled(packageName: String): boolean Checks if an application with the given package name is installed. isAppRoot(): boolean Checks if the application is running with root privileges. isAppDebug(): boolean Checks if the application is a debug build. isAppSystem(): boolean Checks if the application is a system application. isAppForeground(): boolean Checks if the application is currently in the foreground. isAppRunning(packageName: String): boolean Checks if the application with the given package name is running. launchApp(packageName: String) Launches the application with the specified package name. launchApp(intent: Intent) Launches an application using the provided Intent. relaunchApp() Relaunches the current application. launchAppDetailsSettings() Launches the application's details settings screen. exitApp() Exits the current application. getAppIcon(packageName: String): Drawable Gets the application icon for the specified package name. getAppPackageName(): String Gets the package name of the current application. getAppName(): String Gets the name of the current application. getAppPath(): String Gets the path of the current application's APK file. getAppVersionName(): String Gets the version name of the current application. getAppVersionCode(): Int Gets the version code of the current application. getAppMinSdkVersion(): Int Gets the minimum SDK version targeted by the application. getAppTargetSdkVersion(): Int Gets the target SDK version of the application. getAppSignatures(): Array Gets the signatures of the current application. getAppSignaturesSHA1(): String Gets the SHA1 signature of the current application. getAppSignaturesSHA256(): String Gets the SHA256 signature of the current application. getAppSignaturesMD5(): String Gets the MD5 signature of the current application. getAppInfo(): AppUtils.AppInfo Gets detailed information about the current application. getAppsInfo(): List Gets detailed information about all installed applications. getApkInfo(filePath: String): AppUtils.ApkInfo Gets information about an APK file from the given path. getApkInfo(file: File): AppUtils.ApkInfo Gets information about an APK file from the given File object. ``` -------------------------------- ### AndroidUtilCode Activity Transition (Main Process) Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utility for starting activities, specifically designed for the main process. This might be used for inter-process communication or specific activity launching scenarios. ```java start ``` -------------------------------- ### Path Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates path utility functions in a Kotlin Activity. This would show how to get and use various application-specific file paths. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating path operations. // For example: // val cachePath = PathUtils.getInternalAppCachePath() // LogUtils.d("Cache Path: $cachePath") ``` -------------------------------- ### BusUtils Registration via Reflection Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Demonstrates how to register a method with BusUtils using reflection. This is used in the test setup to simulate the AOP injection process. ```java @Before public void setUp() throws Exception { // 这一步是在 AOP 的时候注入的,这里通过反射来注入 busUtilsFun 事件,效果是一样的。 ReflectUtils getInstance = ReflectUtils.reflect(BusUtils.class).method("getInstance"); getInstance.method("registerBus", "busUtilsFun", BusUtilsVsEventBusTest.class.getName(), "busUtilsFun", String.class.getName(), "param", false, "POSTING"); } ``` -------------------------------- ### API Instance Retrieval API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Provides a method to get an instance of an API. ```APIDOC ApiUtils: getApi(): Any Gets an instance of the API. ``` -------------------------------- ### AndroidUtilCode Activity Transition Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md A general utility for starting activities within an Android application. This simplifies the process of navigating between different screens. ```java start ``` -------------------------------- ### ServiceUtils Java Documentation Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utility class for managing Android services, including starting, stopping, and checking the status of services. ```java package com.blankj.utilcode.util; import android.app.ActivityManager; import android.app.Service; import android.content.Context; import android.content.Intent; /** * Utility class for service operations. */ public final class ServiceUtils { private ServiceUtils() { throw new UnsupportedOperationException("u can't create me..."); } /** * Start service. * * @param cls The service class. */ public static void startService(final Class cls) { Utils.getApp().startService(new Intent(Utils.getApp(), cls)); } /** * Stop service. * * @param cls The service class. */ public static void stopService(final Class cls) { Utils.getApp().stopService(new Intent(Utils.getApp(), cls)); } /** * Check whether the service is running. * * @param className The name of the service class. * @return {@code true} if the service is running, {@code false} otherwise. */ public static boolean isServiceRunning(final String className) { ActivityManager activityManager = (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo serviceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) { if (serviceInfo.service.getClassName().equals(className)) { return true; } } return false; } // Other methods for service operations... } ``` -------------------------------- ### Service Management Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing Android services. Includes methods for starting, stopping, and checking the status of services. ```java com.blankj.utilcode.util.ServiceUtils ``` -------------------------------- ### Example of Injected Code in init() Source: https://github.com/blankj/androidutilcode/blob/master/plugin/api-gradle-plugin/README.md This snippet illustrates the resulting code that would be injected into the 'init()' method by the API plugin, demonstrating the registration of an implementation class. ```java private void init() { this.registerImpl(MainApiImpl.class); } ``` -------------------------------- ### App Store Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/subutil/README-CN.md Provides functionality to interact with the device's app store, such as getting intents to open the store page for an app. ```java getAppStoreIntent: 获取跳转应用商店意图 ``` -------------------------------- ### BusUtils Event List Schema (__bus__.json) Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Example JSON schema for `__bus__.json`, generated by BusUtils, detailing event tags, associated methods, and thread modes. Demonstrates compile-time checks for parameter count mismatches. ```json { "BusUtilsClass": "com.blankj.utilcode.util.BusUtils", "rightBus": { "noParamFun": "{ desc: com.blankj.utilcode.pkg.feature.bus.BusActivity#noParamFun(), threadMode: POSTING }", "oneParamFun": "{ desc: com.blankj.utilcode.pkg.feature.bus.BusActivity#oneParamFun(java.lang.String param), threadMode: POSTING }" }, "wrongBus": {} } ``` -------------------------------- ### Activity Management API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Provides methods for managing Android Activities, including lifecycle callbacks, starting activities, finishing activities, and retrieving activity information. ```APIDOC ActivityUtils: addActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks): void Adds an Activity lifecycle callback. removeActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks): void Removes an Activity lifecycle callback. getAliveActivityByContext(context: Context): Activity Gets the alive Activity by context. getActivityByContext(context: Context): Activity Gets the Activity by context. isActivityExists(cls: Class): boolean Checks if an Activity of the specified class exists. startActivity(cls: Class): void Starts an Activity. startActivityForResult(cls: Class, requestCode: Int): void Starts an Activity for result. startActivities(intents: Array): void Starts multiple Activities. startHomeActivity(): void Starts the home Activity. getActivityList(): List Gets the list of Activities in the stack. getLauncherActivity(): ComponentName Gets the launcher Activity. getMainActivities(): List Gets the main Activities. getTopActivity(): Activity Gets the top Activity in the stack. isActivityAlive(activity: Activity): boolean Checks if an Activity is alive. isActivityExistsInStack(cls: Class): boolean Checks if an Activity of the specified class exists in the stack. finishActivity(activity: Activity): void Finishes an Activity. finishToActivity(cls: Class, isInclude: Boolean): void Finishes activities up to a specified Activity. finishOtherActivities(cls: Class): void Finishes all other Activities except the specified one. finishAllActivities(): void Finishes all Activities. finishAllActivitiesExceptNewest(): void Finishes all Activities except the newest one. ``` -------------------------------- ### Implement Custom Base Transform Plugin Source: https://github.com/blankj/androidutilcode/blob/master/plugin/lib/base-transform/README.md This example demonstrates how to create a custom plugin by extending the BaseTransformPlugin class. It includes methods for plugin naming, scan lifecycle events, and class file processing. ```java class ApiPlugin extends BaseTransformPlugin { @Override String getPluginName() { // 获取插件名 } @Override void onScanStarted() { // 扫描开始的处理 } @Override boolean isIgnoreScan(JarInput input) { // 对 jar 包进行过滤扫描, // 工程中的 module 就是以 : 开头的 jar 包 // 远端仓库也是 jar 包 } @Override void scanClassFile(File classFile, String className, File originScannedJarOrDir) { // 扫描到类文件的处理 } @Override void onScanFinished() { // 扫描结束的处理 } } ``` -------------------------------- ### Service Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for managing Android services, including starting, stopping, binding, unbinding, and checking if a service is running. ```java getAllRunningServices: 获取所有运行的服务 startService : 启动服务 stopService : 停止服务 bindService : 绑定服务 unbindService : 解绑服务 isServiceRunning : 判断服务是否运行 ``` -------------------------------- ### API Versioning Example Source: https://github.com/blankj/androidutilcode/blob/master/plugin/api-gradle-plugin/README.md Illustrates API evolution by adding a new parameter to an existing method while maintaining backward compatibility. This follows Android SDK's approach to API updates. ```java // old public abstract class MainApi extends ApiUtils.BaseApi { public abstract MainResult startMainActivity(Context context, MainParam param); } // good public abstract class MainApi extends ApiUtils.BaseApi { public abstract MainResult startMainActivity(Context context, MainParam param); public abstract MainResult startMainActivity(Context context, MainParam param, UserInfo info); } // don't public abstract class MainApi extends ApiUtils.BaseApi { public abstract MainResult startMainActivity(Context context, MainParam param, UserInfo info); } ``` -------------------------------- ### Activity Management API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides methods for managing Android Activities, including lifecycle callbacks, activity retrieval, starting activities, and finishing activities within stacks. ```APIDOC ActivityUtils: addActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) Adds a callback to listen for activity lifecycle events. removeActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks) Removes a previously added activity lifecycle callback. getAliveActivityByContext(context: Context): Activity Retrieves the alive Activity instance associated with the given context. getActivityByContext(context: Context): Activity Retrieves the Activity instance associated with the given context, regardless of its alive state. isActivityExists(activity: Activity): boolean Checks if the specified Activity instance is currently alive. startActivity(cls: Class) Starts a new Activity of the specified class. startActivity(intent: Intent) Starts a new Activity based on the provided Intent. startActivityForResult(cls: Class, requestCode: Int) Starts a new Activity and expects a result back with the given request code. startActivityForResult(intent: Intent, requestCode: Int) Starts a new Activity based on the Intent and expects a result back. startActivities(intents: Array, requestCode: Int) Starts multiple Activities sequentially. startHomeActivity(): boolean Starts the main launcher activity of the application. getActivityList(): List Returns a list of all currently alive Activity instances. getLauncherActivity(): ComponentName Gets the component name of the launcher activity. getMainActivities(): List Gets a list of all main activities. getTopActivity(): Activity Gets the top-most Activity in the current task. isActivityAlive(activity: Activity): boolean Checks if the specified Activity instance is currently alive. isActivityExistsInStack(activity: Activity): boolean Checks if the specified Activity instance exists in the current activity stack. finishActivity(activity: Activity) Finishes the specified Activity. finishToActivity(activity: Activity, isIncludeActivity: Boolean) Finishes activities up to the specified Activity in the stack. finishOtherActivities(activity: Activity, isIncludeActivity: Boolean) Finishes all activities except the specified one. finishAllActivities() Finishes all currently running activities. finishAllActivitiesExceptNewest() Finishes all activities except the newest one. ``` -------------------------------- ### Define MainApi Interface Source: https://github.com/blankj/androidutilcode/blob/master/plugin/api-gradle-plugin/README.md Defines the abstract interface for starting MainActivity with custom parameters and return types. This serves as the contract for inter-module communication. ```java public abstract class MainApi extends ApiUtils.BaseApi { public abstract MainResult startMainActivity(Context context, MainParam param); } public class MainParam { private String name; public MainParam(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class MainResult { private String name; public MainResult(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` -------------------------------- ### Implement MainApi Source: https://github.com/blankj/androidutilcode/blob/master/plugin/api-gradle-plugin/README.md Provides the concrete implementation for the MainApi interface, including the logic to start MainActivity and return a result. The @ApiUtils.Api annotation is crucial for the plugin to discover and inject this implementation. ```java @ApiUtils.Api public class MainApiImpl extends MainApi { @Override public MainResult startMainActivity(Context context, MainParam param) { MainActivity.start(context, param); return new MainResult("result"); } } ``` -------------------------------- ### Activity Management Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for managing Android Activities, including starting, finishing, and checking activity states. Provides functionalities for activity lifecycle management and navigation. ```java package com.blankj.utilcode.util; public final class ActivityUtils { private ActivityUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } // ... methods for activity management } ``` -------------------------------- ### Process Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Offers functionalities for managing and querying process information, including getting the foreground process name, killing background processes, and checking if the current process is the main one. ```java getForegroundProcessName : 获取前台线程包名 killAllBackgroundProcesses: 杀死所有的后台服务进程 killBackgroundProcesses : 杀死后台服务进程 isMainProcess : 判断是否运行在主进程 getCurrentProcessName : 获取当前进程名称 ``` -------------------------------- ### Process Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates process utility functions in a Kotlin Activity. This would show how to interact with the application's process. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating process management. // For example: // if (ProcessUtils.isMainProcess()) { // LogUtils.d("Running in main process") // } ``` -------------------------------- ### Gson Utility Functions Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides utility methods for working with Gson, including setting delegates, getting Gson instances, and converting objects to and from JSON strings. It also offers methods to get specific Java types like List, Set, Map, and Array for generic type handling. ```java setGsonDelegate setGson getGson toJson fromJson getListType getSetType getMapType getArrayType getType ``` -------------------------------- ### Volume Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for getting and setting device volume levels. ```java getVolume : 获取音量 setVolume : 设置音量 getMaxVolume: 获取最大音量 getMinVolume: 获取最小音量 ``` -------------------------------- ### API Utility API Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides a method to get API information. ```APIDOC ApiUtils: getApi(): String Returns API information. ``` -------------------------------- ### BusUtils Best Practices Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Provides recommendations for organizing event tags, ensuring method visibility, and handling beans with ProGuard. ```java // Example of a well-defined tag: public static final String UPDATE_AVATAR_STICKY_MAIN_INFO = "update_avatar_sticky_main_info"; // Ensure event handler methods are public: @BusUtils.Bus(tag = "someTag") public void handleEvent(MyEventBean bean) { /* ... */ } // ProGuard rule for event beans: // -keep class com.yourpackage.MyEventBean { *; } ``` -------------------------------- ### AndroidUtilCode onMethodExit Logic Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md This Java code snippet demonstrates the `onMethodExit` method, which is part of an Android utility. It iterates through a map of bus entries, checks conditions related to the number of bus info entries and parameter size, and then generates bytecode instructions using `mv` (presumably a MethodVisitor) to register a bus. The registration process includes passing various details like key, class name, function name, parameter information, sticky status, and thread mode. ```java @Override protected void onMethodExit(int opcode) { super.onMethodExit(opcode); for (Map.Entry> busEntry : mBusMap.entrySet()) { List infoList = busEntry.getValue(); if (infoList.size() != 1) continue; BusInfo busInfo = infoList.get(0); if (!busInfo.isParamSizeNoMoreThanOne) continue; mv.visitVarInsn(ALOAD, 0); mv.visitLdcInsn(busEntry.getKey()); mv.visitLdcInsn(busInfo.className); mv.visitLdcInsn(busInfo.funName); if (busInfo.paramsInfo.size() == 1) { mv.visitLdcInsn(busInfo.paramsInfo.get(0).className); mv.visitLdcInsn(busInfo.paramsInfo.get(0).name); } else { mv.visitLdcInsn(""); mv.visitLdcInsn(""); } mv.visitInsn(busInfo.sticky ? ICONST_1 : ICONST_0); mv.visitLdcInsn(busInfo.threadMode); mv.visitMethodInsn(INVOKESPECIAL, mBusUtilsClass, "registerBus", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLjava/lang/String;)V", false); } } }; ``` -------------------------------- ### Resource Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates resource utility functions in a Kotlin Activity. This would show how to read files from the assets folder or access other resources. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating resource loading. // For example: // val fileContent = ResourceUtils.readAssets2String("config.json") // LogUtils.d("File Content: $fileContent") ``` -------------------------------- ### Path Manipulation Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Contains a comprehensive set of utilities for accessing and manipulating file paths on Android devices. It provides methods to get various internal and external storage paths, including application-specific directories (data, cache, files, databases, shared preferences, etc.), media directories (music, pictures, downloads, etc.), and root paths. It also supports getting paths prioritizing external storage. ```java join getRootPath getDataPath getDownloadCachePath getInternalAppDataPath getInternalAppCodeCacheDir getInternalAppCachePath getInternalAppDbsPath getInternalAppDbPath getInternalAppFilesPath getInternalAppSpPath getInternalAppNoBackupFilesPath getExternalStoragePath getExternalMusicPath getExternalPodcastsPath getExternalRingtonesPath getExternalAlarmsPath getExternalNotificationsPath getExternalPicturesPath getExternalMoviesPath getExternalDownloadsPath getExternalDcimPath getExternalDocumentsPath getExternalAppDataPath getExternalAppCachePath getExternalAppFilesPath getExternalAppMusicPath getExternalAppPodcastsPath getExternalAppRingtonesPath getExternalAppAlarmsPath getExternalAppNotificationsPath getExternalAppPicturesPath getExternalAppMoviesPath getExternalAppDownloadPath getExternalAppDcimPath getExternalAppDocumentsPath getExternalAppObbPath getRootPathExternalFirst getAppDataPathExternalFirst getFilesPathExternalFirst getCachePathExternalFirst ``` -------------------------------- ### MetaData Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates reading meta-data in a Kotlin Activity. This snippet would show how to retrieve configuration values from the manifest. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating meta-data retrieval. // For example: // val metaDataValue = MetaDataUtils.getAppMetaData("api_key") ``` -------------------------------- ### ScreenUtils Java Documentation Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Provides utility methods for screen-related operations in Android, such as getting screen dimensions and density. ```java package com.blankj.utilcode.util; import android.content.Context; import android.graphics.Point; import android.view.Display; import android.view.WindowManager; /** * Utility class for screen operations. */ public final class ScreenUtils { private ScreenUtils() { throw new UnsupportedOperationException("u can't create me..."); } /** * Return the width of screen, in pixels. * * @return the width of screen, in pixels */ public static int getScreenWidth() { WindowManager windowManager = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); Point size = new Point(); display.getgetSize(size); return size.x; } /** * Return the height of screen, in pixels. * * @return the height of screen, in pixels */ public static int getScreenHeight() { WindowManager windowManager = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE); Display display = windowManager.getDefaultDisplay(); Point size = new Point(); display.getgetSize(size); return size.y; } // Other methods for screen operations... } ``` -------------------------------- ### BusUtils DSL Configuration Options Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Details the available configuration options within the 'bus' DSL block for the Gradle plugin. ```groovy bus { abortOnError boolean // Default: true busUtilsClass String // Default: 'com.blankj.utilcode.util.BusUtils' onlyScanLibRegex String jumpScanLibRegex String } ``` -------------------------------- ### Basic BusUtils Usage Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Demonstrates the fundamental usage of BusUtils for registering, unregistering, and posting events with and without parameters. ```java public static final String TAG_NO_PARAM = "TagNoParam"; public static final String TAG_ONE_PARAM = "TagOneParam"; @BusUtils.Bus(tag = TAG_NO_PARAM) public void noParamFun() {/* Do something */} @BusUtils.Bus(tag = TAG_ONE_PARAM) public void oneParamFun(String param) {/* Do something */} @Override public void onStart() { super.onStart(); BusUtils.register(this); } @Override public void onStop() { super.onStop(); BusUtils.unregister(this); } BusUtils.post(TAG_NO_PARAM); BusUtils.post(TAG_ONE_PARAM, "param"); ``` -------------------------------- ### Sticky Events with BusUtils Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Illustrates how to use sticky events with BusUtils, allowing events to be received after registration. ```java public static final String TAG_NO_PARAM_STICKY = "TagNoParamSticky"; @BusUtils.Bus(tag = TAG_NO_PARAM_STICKY, sticky = true) public void noParamStickyFun() {/* Do something */} BusUtils.postSticky(TAG_NO_PARAM_STICKY); BusUtils.register(xxx); BusUtils.removeSticky(TAG_NO_PARAM_STICKY); BusUtils.unregister(xxx); ``` -------------------------------- ### Screen Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing the device screen. Includes methods for getting screen dimensions, brightness, and taking screenshots. ```java com.blankj.utilcode.util.ScreenUtils ``` -------------------------------- ### Posting an Event Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Initiates the event posting process. It retrieves `BusInfo` based on the tag, finds the corresponding method using reflection, and then invokes the method on the registered bus objects. ```java public static void post(final String tag) { post(tag, NULL); } public static void post(final String tag, final Object arg) { getInstance().postInner(tag, arg); } private void postInner(final String tag, final Object arg) { postInner(tag, arg, false); } private void postInner(final String tag, final Object arg, final boolean sticky) { BusInfo busInfo = mTag_BusInfoMap.get(tag); if (busInfo == null) { Log.e(TAG, "The bus of tag <" + tag + "> is not exists."); return; } if (busInfo.method == null) { Method method = getMethodByBusInfo(busInfo); if (method == null) { return; } busInfo.method = method; } invokeMethod(tag, arg, busInfo, sticky); } ``` -------------------------------- ### Path Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides utilities for working with file paths, including getting application-specific directories and managing path strings. ```java PathUtils.java: https://github.com/Blankj/AndroidUtilCode/blob/master/lib/utilcode/src/main/java/com/blankj/utilcode/util/PathUtils.java ``` -------------------------------- ### Phone Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates phone utility functions in a Kotlin Activity. This would showcase retrieving device information or initiating phone calls. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating phone-related operations. // For example: // val deviceModel = PhoneUtils.getModel() // LogUtils.d("Device Model: $deviceModel") ``` -------------------------------- ### Brightness Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utilities for controlling and adjusting the screen brightness of an Android device. Includes methods to get, set, and manage brightness levels. ```java package com.blankj.utilcode.util; public final class BrightnessUtils { private BrightnessUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } // ... methods for brightness utilities } ``` -------------------------------- ### Cache Disk Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing disk cache in Android applications. Includes methods for putting, getting, and removing cached data. ```java public class CacheDiskUtils { private static volatile CacheDiskUtils INSTANCE; private CacheDiskUtils() { } public static CacheDiskUtils getInstance() { if (INSTANCE == null) { synchronized (CacheDiskUtils.class) { if (INSTANCE == null) { INSTANCE = new CacheDiskUtils(); } } } return INSTANCE; } public void put(String key, String value) { // Implementation for putting data into disk cache } public String get(String key) { // Implementation for getting data from disk cache return null; } public void remove(String key) { // Implementation for removing data from disk cache } } ``` -------------------------------- ### Log Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates the logging utility functions in a Kotlin context. This would show how to log various types of messages and data structures. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating logging. // For example: // LogUtils.v("Verbose Log") ``` -------------------------------- ### AndroidUtilCode Vibrate Control Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for controlling device vibration, including starting and cancelling vibration patterns. This allows for haptic feedback in the application. ```java vibrate cancel ``` -------------------------------- ### Notification Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates notification utility functions in a Kotlin Activity. This would show how to create and manage notifications programmatically. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating notification creation. // For example: // val notification = NotificationUtils.buildNotification("Title", "Content") // NotificationUtils.notify(notification, 1) ``` -------------------------------- ### SDCardUtils Java Documentation Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Utility class for SD card operations, including checking for SD card availability and getting SD card paths. ```java package com.blankj.utilcode.util; import android.os.Environment; import android.os.StatFs; import java.io.File; /** * Utility class for SD card operations. */ public final class SDCardUtils { private SDCardUtils() { throw new UnsupportedOperationException("u can't create me..."); } /** * Check whether the SD card is available. * * @return {@code true} if SD card is available, {@code false} otherwise. */ public static boolean isSDCardEnable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } /** * Get the path of SD card. * * @return the path of SD card */ public static String getSDCardPath() { return Environment.getExternalStorageDirectory().getPath() + File.separator; } // Other methods for SD card operations... } ``` -------------------------------- ### ROM Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates ROM utility functions in a Kotlin Activity. This would show how to check for specific device ROMs or retrieve ROM details. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating ROM detection. // For example: // if (RomUtils.isXiaomi()) { // LogUtils.d("Device is Xiaomi") // } ``` -------------------------------- ### SPUtils for SharedPreferences Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Instance-based utility class for SharedPreferences operations, providing methods to get an instance and perform put/get operations for various data types. ```java getInstance : 获取 SP 实例 Instance.put : SP 中写入数据 Instance.getString : SP 中读取 String Instance.getInt : SP 中读取 int Instance.getLong : SP 中读取 long Instance.getFloat : SP 中读取 float Instance.getBoolean: SP 中读取 boolean Instance.getAll : SP 中获取所有键值对 Instance.contains : SP 中是否存在该 key Instance.remove : SP 中移除该 key Instance.clear : SP 中清除所有数据 ``` -------------------------------- ### Registering an Event Bus Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Stores event information (tag, class name, method name, parameter type, thread mode) in a map for later retrieval. This is the initial step in setting up an event. ```java private void registerBus(String tag, String className, String funName, String paramType, String paramName, boolean sticky, String threadMode) { mTag_BusInfoMap.put(tag, new BusInfo(className, funName, paramType, paramName, sticky, threadMode)); } ``` -------------------------------- ### Process Management Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing application processes. Includes methods to get the current process name, kill processes, and check if a process is running. ```java com.blankj.utilcode.util.ProcessUtils ``` -------------------------------- ### Language Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates the language utility functions within a Kotlin Activity. This would show practical application of language switching in an Android UI. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating language change functionality. // For example: // LanguageUtils.applyLanguage(Locale.CHINA) ``` -------------------------------- ### Network Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides utilities for network operations, including checking network connectivity, getting IP addresses, and monitoring network state changes. ```java NetworkUtils.java: https://github.com/Blankj/AndroidUtilCode/blob/master/lib/utilcode/src/main/java/com/blankj/utilcode/util/NetworkUtils.java ``` ```kotlin NetworkActivity.kt: https://github.com/Blankj/AndroidUtilCode/blob/master/feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/network/NetworkActivity.kt ``` -------------------------------- ### AndroidUtilCode Volume Control Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for managing the device's audio volume. This includes getting, setting, and retrieving the maximum and minimum volume levels. ```java getVolume setVolume getMaxVolume getMinVolume ``` -------------------------------- ### ColorUtils: Color Manipulation Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Utilities for color manipulation, including getting and setting color components, converting between color formats, and generating random colors. ```java getColor setAlphaComponent setRedComponent setGreenComponent setBlueComponent string2Int int2RgbString int2ArgbString getRandomColor isLightColor ``` -------------------------------- ### Configure BusUtils Plugin Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Adds the 'bus' plugin to your project's root build.gradle file and applies it to the application module. ```groovy buildscript { dependencies { ... classpath 'com.blankj:bus-gradle-plugin:latest.release' } } apply plugin: "com.blankj.bus" ``` -------------------------------- ### AppStoreUtils API Source: https://github.com/blankj/androidutilcode/blob/master/lib/subutil/README.md Provides methods to interact with the app store, such as retrieving intents to open the app store page for the current application. ```APIDOC AppStoreUtils: getAppStoreIntent(): Intent Description: Returns an Intent to open the app store page for the current application. Returns: An Intent that can be used to launch the app store. Example: startActivity(AppStoreUtils.getAppStoreIntent()) ``` -------------------------------- ### SPStaticUtils for SharedPreferences Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Static utility class for SharedPreferences operations, including putting and getting various data types, checking for keys, removing, and clearing data. ```java setDefaultSPUtils: 设置默认 SP 实例 put : SP 中写入数据 getString : SP 中读取 String getInt : SP 中读取 int getLong : SP 中读取 long getFloat : SP 中读取 float getBoolean : SP 中读取 boolean getAll : SP 中获取所有键值对 contains : SP 中是否存在该 key remove : SP 中移除该 key clear : SP 中清除所有数据 ``` -------------------------------- ### SD Card Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides utilities for interacting with the SD card. Includes methods for checking SD card availability, getting paths, and reading/writing files. ```java com.blankj.utilcode.util.SDCardUtils ``` -------------------------------- ### Permission Utility Demo in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates permission utility functions in a Kotlin Activity. This would show how to request and handle user permissions for sensitive operations. ```kotlin // This snippet would typically be part of an Activity or Fragment // demonstrating permission requests. // For example: // PermissionUtils.permission(Manifest.permission.CAMERA) // .onGranted { LogUtils.d("Camera permission granted") } // .onDenied { LogUtils.e("Camera permission denied") } // .request() ``` -------------------------------- ### Map Utilities Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README.md Provides utility methods for working with Map data structures, including operations like checking for empty maps, getting values, and iterating. ```java MapUtils.java: https://github.com/Blankj/AndroidUtilCode/blob/master/lib/utilcode/src/main/java/com/blankj/utilcode/util/MapUtils.java ``` ```java MapUtilsTest.java: https://github.com/Blankj/AndroidUtilCode/blob/master/lib/utilcode/src/test/java/com/blankj/utilcode/util/MapUtilsTest.java ``` -------------------------------- ### Event and BusUtils Method Definitions Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Defines sample methods for EventBus and BusUtils. These methods are empty implementations used for performance testing to measure the speed of event delivery. ```java @Subscribe public void eventBusFun(String param) { } @BusUtils.Bus(tag = "busUtilsFun") public void busUtilsFun(String param) { } ``` -------------------------------- ### Keyboard Utility in Kotlin Source: https://github.com/blankj/androidutilcode/blob/master/lib/utilcode/README-CN.md Demonstrates the usage of keyboard utility functions in Kotlin. This snippet likely showcases how to show, hide, or manipulate the soft keyboard. ```kotlin import com.blankj.utilcode.util.KeyboardUtils // Example usage: // KeyboardUtils.showSoftInput(view) // KeyboardUtils.hideSoftInput(view) // KeyboardUtils.toggleSoftInput() ``` -------------------------------- ### Test Case: Register 10000 Subscribers Source: https://github.com/blankj/androidutilcode/blob/master/plugin/bus-gradle-plugin/README.md Compares the time taken to register 10,000 subscribers using EventBus and BusUtils. The test runs 10 times and calculates the average. ```java /** * 注册 10000 个订阅者,共执行 10 次取平均值 */ @Test public void compareRegister10000Times() { final List eventBusTests = new ArrayList<>(); final List busUtilsTests = new ArrayList<>(); compareWithEventBus("Register 10000 times.", 10, 10000, new CompareCallback() { @Override public void runEventBus() { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); EventBus.getDefault().register(test); eventBusTests.add(test); } @Override public void runBusUtils() { BusUtilsVsEventBusTest test = new BusUtilsVsEventBusTest(); BusUtils.register(test); busUtilsTests.add(test); } @Override public void restState() { for (BusUtilsVsEventBusTest test : eventBusTests) { EventBus.getDefault().unregister(test); } eventBusTests.clear(); for (BusUtilsVsEventBusTest test : busUtilsTests) { BusUtils.unregister(test); } busUtilsTests.clear(); } }); } ``` -------------------------------- ### ASM Method Visitor for Code Injection Source: https://github.com/blankj/androidutilcode/blob/master/plugin/api-gradle-plugin/README.md This code snippet shows how to use ASM's AdviceAdapter to inject code into the 'init' method. It iterates through the collected API implementations and calls 'registerImpl' for each. ```java @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { if (!"init".equals(name)) { return super.visitMethod(access, name, descriptor, signature, exceptions); } // 往 init() 函数中写入 if (cv == null) return null; MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions); mv = new AdviceAdapter(Opcodes.ASM5, mv, access, name, descriptor) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return super.visitAnnotation(desc, visible); } @Override protected void onMethodEnter() { super.onMethodEnter(); } @Override protected void onMethodExit(int opcode) { super.onMethodExit(opcode); for (Map.Entry apiImplEntry : mApiImplMap.entrySet()) { mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitLdcInsn(Type.getType("L" + apiImplEntry.getValue().implApiClass + ";")); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, mApiUtilsClass, "registerImpl", "(Ljava/lang/Class;)V", false); } } }; return mv; } ```