├── publishingTemp ├── consumer-rules.pro ├── src │ └── main │ │ └── AndroidManifest.xml ├── proguard-rules.pro └── build.gradle.kts ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── keystore.properties ├── app ├── src │ ├── main │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── drawable │ │ │ │ ├── round_rectangle.xml │ │ │ │ ├── sh_divider_line.xml │ │ │ │ ├── btn_round_rectangle.xml │ │ │ │ ├── sh_2_btn_alert_bg.xml │ │ │ │ ├── launcher_splash.xml │ │ │ │ ├── tab_indicator.xml │ │ │ │ ├── v_next.xml │ │ │ │ ├── v_back.xml │ │ │ │ └── ic_launcher_background.xml │ │ │ ├── drawable-v24 │ │ │ │ ├── float_drag_btn_bg.xml │ │ │ │ ├── float_drag_btn_bg_pressed.xml │ │ │ │ ├── float_drag_btn_selector.xml │ │ │ │ └── ic_launcher_foreground.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── layout │ │ │ │ ├── float_drag_btn.xml │ │ │ │ ├── layout_popup_window.xml │ │ │ │ ├── layout_tablayout_viewpage2.xml │ │ │ │ └── dialog_2_btn_alert.xml │ │ │ └── xml │ │ │ │ └── share_dir.xml │ │ ├── java │ │ │ ├── template │ │ │ │ ├── TextWatcherAdapter.java │ │ │ │ ├── BottomSheetDialogTheme.java │ │ │ │ ├── MultipleClicksController.java │ │ │ │ ├── ControlAdapter.java │ │ │ │ ├── fragment_activity │ │ │ │ │ ├── BlankFragment.java │ │ │ │ │ └── FragmentActivity.java │ │ │ │ ├── FingerprintUtils.java │ │ │ │ ├── SingleClickController.java │ │ │ │ ├── SdcardFragment.java │ │ │ │ ├── ToastUtils.java │ │ │ │ ├── RxJava3Templates.java │ │ │ │ ├── RecyclerViewItem.java │ │ │ │ ├── ProgressHUD.java │ │ │ │ ├── recyclerview_group │ │ │ │ │ ├── SectionRVAdapter.java │ │ │ │ │ ├── SectionRVTestFragment.java │ │ │ │ │ └── SectionItemDecoration.java │ │ │ │ ├── CircleProgressView.java │ │ │ │ ├── BottomNavigationFragment.java │ │ │ │ ├── UDP.java │ │ │ │ ├── ThumbnailImage.java │ │ │ │ ├── FloatDragBtnActivity.java │ │ │ │ ├── ImagePickActivity.java │ │ │ │ ├── TranslucentBarActivity.java │ │ │ │ ├── DownloadUtils.java │ │ │ │ ├── FileMultipleSelectionFragment.java │ │ │ │ ├── AlertDialogTheme.java │ │ │ │ └── CalendarAndAlarmClock.java │ │ │ └── utils │ │ │ │ ├── get_context_no_dependence_anything │ │ │ │ ├── AndroidHacks.java │ │ │ │ └── Applications.java │ │ │ │ └── encryption │ │ │ │ └── aes │ │ │ │ └── AES.java │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── min │ │ │ └── test │ │ │ └── android_app_template │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── min │ │ └── test │ │ └── android_app_template │ │ └── ExampleInstrumentedTest.kt ├── proguard-rules.pro └── build.gradle.kts ├── settings.gradle.kts ├── gradle.properties ├── gradlew.bat ├── 厂商推送服务端关键字段.txt ├── .gitignore ├── gradlew └── README.md /publishingTemp/consumer-rules.pro: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /keystore.properties: -------------------------------------------------------------------------------- 1 | storePassword=myStorePassword 2 | keyPassword=mykeyPassword 3 | keyAlias=myKeyAlias 4 | storeFile=e:\\xxx\\xxx.keystore -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mxmhao/Android_App_Template/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Android_App_Template 4 | 5 | -------------------------------------------------------------------------------- /publishingTemp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/round_rectangle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/float_drag_btn_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/float_drag_btn_bg_pressed.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/sh_divider_line.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/btn_round_rectangle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/sh_2_btn_alert_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/float_drag_btn_selector.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/launcher_splash.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 23 15:24:47 CST 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | # must use *-all.zip, if not use, gradle sync will download gradle's src 5 | #distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip 6 | distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.10.2-all.zip 7 | zipStoreBase=GRADLE_USER_HOME 8 | zipStorePath=wrapper/dists 9 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/tab_indicator.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/test/java/min/test/android_app_template/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package min.test.android_app_template 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable/v_next.xml: -------------------------------------------------------------------------------- 1 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/v_back.xml: -------------------------------------------------------------------------------- 1 | 7 | 9 | 10 | 12 | -------------------------------------------------------------------------------- /app/src/main/java/template/TextWatcherAdapter.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.text.Editable; 4 | import android.text.TextWatcher; 5 | 6 | public class TextWatcherAdapter implements TextWatcher { 7 | 8 | @Override 9 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 10 | 11 | @Override 12 | public void onTextChanged(CharSequence s, int start, int before, int count) {} 13 | 14 | @Override 15 | public void afterTextChanged(Editable s) {} 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/res/layout/float_drag_btn.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_popup_window.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/xml/share_dir.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/min/test/android_app_template/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package min.test.android_app_template 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("min.test.android_app_template", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /publishingTemp/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/main/java/template/BottomSheetDialogTheme.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.content.Context; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | 7 | import com.google.android.material.bottomsheet.BottomSheetDialog; 8 | 9 | import min.test.android_app_template.R; 10 | 11 | public class BottomSheetDialogTheme { 12 | 13 | /* 主要是看R.style.BottomSheetBgNullTheme和AppTheme中的bottomSheetDialogTheme */ 14 | public static void test(Context context) { 15 | //去掉BottomSheetDialog的背景,方便自定义视图添加圆角什么的 16 | final BottomSheetDialog bsd = new BottomSheetDialog(context, R.style.BottomSheetBgNullTheme); 17 | View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null, false); 18 | View.OnClickListener clickListener = new View.OnClickListener() { 19 | @Override 20 | public void onClick(View v) { 21 | bsd.dismiss(); 22 | } 23 | }; 24 | bsd.setContentView(view); 25 | bsd.show(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/java/template/MultipleClicksController.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.os.SystemClock; 4 | import android.view.View; 5 | 6 | /** 7 | * 谷歌工程师的多击代码 8 | * 和SingleClickController一样的形式包装 9 | * view.setOnClickListener(new MultipleClicksController(3, new View.OnClickListener(){...})) 10 | */ 11 | public class MultipleClicksController implements View.OnClickListener { 12 | public long intervals = 500;//间隔时间ms 13 | private final long[] hits; 14 | 15 | public View.OnClickListener vocListener; 16 | 17 | //clicks表示多击次数 18 | public MultipleClicksController(int clicks, View.OnClickListener vocListener) { 19 | this.vocListener = vocListener; 20 | hits = new long[clicks]; 21 | } 22 | 23 | @Override 24 | public void onClick(View v) { 25 | System.arraycopy(hits, 1, hits, 0, hits.length - 1); 26 | hits[hits.length - 1] = SystemClock.uptimeMillis(); 27 | if (hits[0] >= (SystemClock.uptimeMillis() - intervals)) {//这上面三行是关键 28 | vocListener.onClick(v);//这里是多击完成的逻辑 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /app/src/main/java/template/ControlAdapter.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.view.View; 4 | import android.view.ViewGroup; 5 | 6 | import androidx.annotation.NonNull; 7 | import androidx.recyclerview.widget.RecyclerView; 8 | 9 | // ViewPager2 使用的 Adapter 10 | public class ControlAdapter extends RecyclerView.Adapter { 11 | 12 | public View[] views; 13 | 14 | public ControlAdapter(View[] views) { 15 | this.views = views; 16 | } 17 | 18 | @Override 19 | public int getItemViewType(int position) { 20 | return position; 21 | } 22 | 23 | @NonNull 24 | @Override 25 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 26 | return new ViewHolder(views[viewType]); 27 | } 28 | 29 | @Override 30 | public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) { 31 | } 32 | 33 | @Override 34 | public int getItemCount() { 35 | return null == views ? 0 : views.length; 36 | } 37 | 38 | public static class ViewHolder extends RecyclerView.ViewHolder { 39 | public ViewHolder(View view) { 40 | super(view); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_tablayout_viewpage2.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 18 | 23 | 24 | 29 | 30 | 35 | 36 | 37 | 42 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | maven ( url = "https://maven.aliyun.com/repository/gradle-plugin/") 4 | // 有些源没有及时同步国外的源,导致有些库文件还是会从国外源下载,所以多配几个国内源,降低这种概率,说不定总有一个源及时同步了 5 | maven ( url = "https://maven.aliyun.com/repository/public/") 6 | maven ( url = "https://maven.aliyun.com/repository/google/") 7 | maven ( url = "https://repo.huaweicloud.com/repository/maven/") 8 | maven ( url = "https://maven.pkg.jetbrains.space/public/p/compose/dev") 9 | google { 10 | content { 11 | includeGroupByRegex("com\\.android.*") 12 | includeGroupByRegex("com\\.google.*") 13 | includeGroupByRegex("androidx.*") 14 | } 15 | } 16 | mavenCentral() 17 | gradlePluginPortal() 18 | } 19 | } 20 | dependencyResolutionManagement { 21 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 22 | repositories { 23 | // 有些源没有及时同步国外的源,导致有些库文件还是会从国外源下载,所以多配几个国内源,降低这种概率,说不定总有一个源及时同步了 24 | // 建议用 Android Studio 内的按钮去同步下载第三方库,不要用 gradlew build 等命令去同步下载第三方库, 25 | // 因为奇怪的JDK环境可能导致一些奇奇怪怪的问题导致同步失败。第一次同步最好打开 Android Studio 的 build 视图, 26 | // 查看 Download info,及时发现哪些库会最终使用国外源,可及时打开代理或者VPN等 27 | maven ( url = "https://maven.aliyun.com/repository/public/") 28 | maven ( url = "https://maven.aliyun.com/repository/google/") 29 | maven ( url = "https://repo.huaweicloud.com/repository/maven/") 30 | maven ( url = "https://maven.pkg.jetbrains.space/public/p/compose/dev") 31 | maven ( url = "https://jitpack.io") 32 | maven ( url = uri("./LocalMavenRepo")) 33 | google() 34 | mavenCentral() 35 | // 本地 libs 36 | flatDir { 37 | dirs("libs") 38 | } 39 | } 40 | } 41 | 42 | rootProject.name = "Android_App_Template" 43 | include(":app") 44 | include(":publishingTemp") 45 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. For more details, visit 12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true 24 | 25 | android.enableJetifier = true 26 | 27 | # ?????JDK?????????????????????????????????????? 28 | #org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk-17.0.4.1.jdk/Contents/Home 29 | #org.gradle.java.home=/Applications/Android Studio.app/Contents/jbr/Contents/Home 30 | 31 | # ????? Maven ????3??????url 32 | systemProp.gradle.repository.mavenCentral=http://maven.aliyun.com/nexus/content/repositories/central/ 33 | systemProp.gradle.repository.google=https://maven.aliyun.com/repository/google/ 34 | #systemProp.gradle.repository.jcenter=https://maven.aliyun.com/repository/jcenter/ -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 20 | 22 | 23 | 24 | 25 | 26 | 31 | 32 | 33 | 38 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /app/src/main/java/template/fragment_activity/BlankFragment.java: -------------------------------------------------------------------------------- 1 | package template.fragment_activity; 2 | 3 | 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.os.Bundle; 7 | import android.util.Log; 8 | import android.view.LayoutInflater; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | 12 | import androidx.fragment.app.Fragment; 13 | 14 | 15 | public class BlankFragment extends Fragment { 16 | private final String TAG = "BlankFragment"; 17 | 18 | public static final String PARAM1 = "PARAM1"; 19 | 20 | public BlankFragment() { 21 | } 22 | 23 | @Override 24 | public void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | } 27 | 28 | @Override 29 | public void onAttach(Context context) { 30 | super.onAttach(context); 31 | //获取传递的参数,根据传递的方式,对应下面2种方式获取 32 | Log.e(TAG, "onAttach: " + ((Activity)context).getIntent().getStringExtra(PARAM1)); 33 | // Log.e(TAG, "onAttach: " + getArguments().getString(PARAM1));// 34 | } 35 | 36 | @Override 37 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 38 | Bundle savedInstanceState) { 39 | View view = inflater.inflate(android.R.layout.simple_list_item_1, container, false); 40 | 41 | return view; 42 | } 43 | 44 | public void push() {//在当前activity跳转到另一个Fragment 45 | getFragmentManager() 46 | .beginTransaction() 47 | .add(android.R.id.content, new BlankFragment()) 48 | .addToBackStack(null) 49 | .commit(); 50 | } 51 | 52 | //返回 53 | public void pop() { 54 | getFragmentManager().popBackStack(); 55 | } 56 | 57 | public void popToRoot() { 58 | //直接推出全部的返回栈 59 | // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 60 | getActivity().finish();//或者直接关掉activity 61 | } 62 | 63 | @Override 64 | public void onDestroy() {//保存数据 65 | Log.e(TAG, "onDestroy: " + num); 66 | num++; 67 | super.onDestroy(); 68 | } 69 | 70 | static int num = 0; 71 | } 72 | -------------------------------------------------------------------------------- /app/src/main/java/template/FingerprintUtils.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import java.io.FileInputStream; 4 | import java.security.KeyStore; 5 | import java.security.MessageDigest; 6 | import java.security.cert.Certificate; 7 | 8 | public class FingerprintUtils { 9 | public static void main(String[] args) { 10 | try { 11 | // 设定 KeyStore 文件路径、密码以及别名 12 | String keystorePath = "./test111.keystore"; 13 | String keystorePassword = "123456"; 14 | String alias = "111111"; 15 | 16 | // 读取 KeyStore 17 | FileInputStream fis = new FileInputStream(keystorePath); 18 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 19 | keyStore.load(fis, keystorePassword.toCharArray()); 20 | 21 | // 获取证书 22 | Certificate cert = keyStore.getCertificate(alias); 23 | if (cert == null) { 24 | throw new RuntimeException("Certificate not found for alias: " + alias); 25 | } 26 | 27 | // 计算并打印指纹 28 | System.out.println("MD5: " + getFingerprint(cert, "MD5")); 29 | System.out.println("SHA-1: " + getFingerprint(cert, "SHA-1")); 30 | System.out.println("SHA-256: " + getFingerprint(cert, "SHA-256")); 31 | 32 | } catch (Exception e) { 33 | e.printStackTrace(); 34 | } 35 | } 36 | 37 | private static String getFingerprint(Certificate cert, String algorithm) { 38 | try { 39 | MessageDigest md = MessageDigest.getInstance(algorithm); 40 | byte[] certBytes = cert.getEncoded(); 41 | byte[] digest = md.digest(certBytes); 42 | return bytesToHex(digest); 43 | } catch (Exception e) { 44 | throw new RuntimeException("Error calculating fingerprint", e); 45 | } 46 | } 47 | 48 | private static String bytesToHex(byte[] bytes) { 49 | StringBuilder sb = new StringBuilder(); 50 | for (byte b : bytes) { 51 | sb.append(String.format("%02X:", b)); 52 | } 53 | // Remove the trailing colon 54 | if (sb.length() > 0) { 55 | sb.setLength(sb.length() - 1); 56 | } 57 | return sb.toString(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/template/SingleClickController.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.os.SystemClock; 4 | import android.view.View; 5 | 6 | /** 7 | * 单击时间间隔控制,使用的是聚合模式,避免了单继承的限制;此类可以添加多个继承接口,按照下面模板的方式控制 8 | * view.setOnClickListener(new SingleClickController(new View.OnClickListener(){...})) 9 | */ 10 | public class SingleClickController implements View.OnClickListener, 11 | YourClickListener, YourClickListener_Next { 12 | //-------全局一个----------- 13 | public long intervals = 800;//间隔时间ms 14 | private long lastTime = 0; 15 | //------------------------ 16 | 17 | //------------View.OnClickListener模板------------ 18 | public View.OnClickListener vocListener; 19 | public SingleClickController(View.OnClickListener vocListener) { 20 | this.vocListener = vocListener; 21 | } 22 | @Override 23 | public final void onClick(View v) { 24 | if (SystemClock.elapsedRealtime() - lastTime < intervals) return; 25 | if (vocListener == null) throw new NullPointerException("vocListener == null"); 26 | vocListener.onClick(v); 27 | lastTime = SystemClock.elapsedRealtime(); 28 | } 29 | //------------View.OnClickListener模板end--------- 30 | 31 | 32 | public YourClickListener yourListener; 33 | public SingleClickController(YourClickListener yourListener) { 34 | this.yourListener = yourListener; 35 | } 36 | @Override 37 | public final void yourClick() { 38 | if (SystemClock.elapsedRealtime() - lastTime < intervals) return; 39 | if (yourListener == null) throw new NullPointerException("yourListener == null"); 40 | yourListener.yourClick(); 41 | lastTime = SystemClock.elapsedRealtime(); 42 | } 43 | 44 | public YourClickListener_Next yourListener_next; 45 | public SingleClickController(YourClickListener_Next yourListener_next) { 46 | this.yourListener_next = yourListener_next; 47 | } 48 | @Override 49 | public final void yourClick_next() { 50 | if (SystemClock.elapsedRealtime() - lastTime < intervals) return; 51 | if (yourListener_next == null) throw new NullPointerException("yourListener_next == null"); 52 | yourListener_next.yourClick_next(); 53 | lastTime = SystemClock.elapsedRealtime(); 54 | } 55 | } 56 | 57 | interface YourClickListener { 58 | void yourClick(); 59 | } 60 | 61 | interface YourClickListener_Next { 62 | void yourClick_next(); 63 | } 64 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.8.0" 3 | kotlin = "1.9.24" 4 | coreKtx = "1.15.0" 5 | junit = "4.13.2" 6 | junitVersion = "1.2.1" 7 | espressoCore = "3.6.1" 8 | appcompat = "1.7.0" 9 | material = "1.12.0" 10 | activity = "1.10.0" 11 | constraintlayout = "2.2.0" 12 | recyclerview = "1.4.0" 13 | okhttp = "4.12.0" 14 | metricsPerformance = "1.0.0-beta01" 15 | exifinterface = "1.3.7" 16 | rxjava = "3.1.10" 17 | rxandroid = "3.0.2" 18 | benchmarkMacroJunit4 = "1.4.0-alpha08" 19 | uiautomator = "2.3.0" 20 | 21 | [libraries] 22 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } 23 | junit = { group = "junit", name = "junit", version.ref = "junit" } 24 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } 25 | androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } 26 | androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } 27 | androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" } 28 | material = { group = "com.google.android.material", name = "material", version.ref = "material" } 29 | androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" } 30 | androidx-recyclerview = { group = "androidx.recyclerview", name = "recyclerview", version.ref = "recyclerview" } 31 | okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } 32 | androidx-metrics-performance = { group = "androidx.metrics", name = "metrics-performance", version.ref = "metricsPerformance" } 33 | androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" } 34 | rxjava = { group = "io.reactivex.rxjava3", name = "rxjava", version.ref = "rxjava" } 35 | rxandroid = { group = "io.reactivex.rxjava3", name = "rxandroid", version.ref = "rxandroid" } 36 | androidx-benchmark-macro-junit4 = { group = "androidx.benchmark", name = "benchmark-macro-junit4", version.ref = "benchmarkMacroJunit4" } 37 | androidx-uiautomator = { group = "androidx.test.uiautomator", name = "uiautomator", version.ref = "uiautomator" } 38 | 39 | [plugins] 40 | android-application = { id = "com.android.application", version.ref = "agp" } 41 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 42 | android-library = { id = "com.android.library", version.ref = "agp" } 43 | 44 | -------------------------------------------------------------------------------- /publishingTemp/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.android.library) 3 | // 插件必须要 4 | `maven-publish` 5 | } 6 | 7 | android { 8 | namespace = "min.test.publishingtemp" 9 | compileSdk = 35 10 | 11 | defaultConfig { 12 | minSdk = 26 13 | 14 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 15 | consumerProguardFiles("consumer-rules.pro") 16 | } 17 | 18 | buildTypes { 19 | release { 20 | isMinifyEnabled = false 21 | proguardFiles( 22 | getDefaultProguardFile("proguard-android-optimize.txt"), 23 | "proguard-rules.pro" 24 | ) 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility = JavaVersion.VERSION_11 29 | targetCompatibility = JavaVersion.VERSION_11 30 | } 31 | 32 | publishing { 33 | // 这个必须配置,否则 components["release"] 会报错 34 | singleVariant("release") { 35 | withSourcesJar() 36 | } 37 | } 38 | } 39 | 40 | dependencies { 41 | 42 | implementation(libs.androidx.appcompat) 43 | implementation(libs.material) 44 | // 引入本地库 45 | // implementation("$localGroup:$localArtifactId:$versionName") 46 | 47 | testImplementation(libs.junit) 48 | androidTestImplementation(libs.androidx.junit) 49 | androidTestImplementation(libs.androidx.espresso.core) 50 | } 51 | 52 | val localGroup = "test.mxm.local" 53 | val localArtifactId = "xxxAndroid" 54 | val versionName = "1.0.0" 55 | val localMavenRepoUrl = "../LocalMavenRepo" 56 | 57 | /* 58 | 此模块只是演示 maven-publish 发布发到本地的 build.gradle.kts 写法。 59 | 官方详细教程: https://developer.android.google.cn/build/publish-library?hl=zh-cn 60 | 把本地aar依赖库发布到本地 maven 源,以下代码必须放在 module 的 build.gradle 文件中, 61 | 否则 Android Studio 的 gradle 工具中看不到 publishing 任务, 62 | 双击 publishing 任务中的 publish 即可发布到本地,然后就可以看到 app 文件夹的平级文件夹 LocalMavenRepo 63 | 如果需要引入 LocalMavenRepo 源中的库,请在 settings.gradle.kts 的 repositories 中加入 maven ( url = uri("./LocalMavenRepo")) 64 | */ 65 | publishing { 66 | repositories { 67 | maven { 68 | //上传到项目本地仓库 69 | url = uri(localMavenRepoUrl) 70 | } 71 | } 72 | 73 | publications { 74 | register("release") { 75 | groupId = localGroup 76 | artifactId = localArtifactId 77 | version = versionName 78 | afterEvaluate { 79 | from(components["release"]) 80 | } 81 | } 82 | } 83 | } -------------------------------------------------------------------------------- /app/src/main/java/template/SdcardFragment.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | 4 | import android.app.Activity; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.net.Uri; 8 | import android.os.Environment; 9 | import android.util.Log; 10 | import android.view.View; 11 | 12 | import androidx.fragment.app.Fragment; 13 | 14 | import java.io.File; 15 | 16 | /** 17 | * 获取外置SD卡的绝对路径模板 18 | */ 19 | public class SdcardFragment extends Fragment { 20 | private final String TAG = "SdcardFragment"; 21 | 22 | public SdcardFragment() { 23 | // Required empty public constructor 24 | } 25 | 26 | /** 27 | * 必须在Android4.4以上版本使用 28 | * OEM厂商需要适配https://source.android.com/devices/storage/config-example.html 29 | * 否则getExternalFilesDirs获取不到SD卡的路径 30 | * https://codeday.me/bug/20180924/264484.html 31 | */ 32 | @Override 33 | public void onAttach(Context context) { 34 | super.onAttach(context); 35 | 36 | File[] files = context.getExternalFilesDirs(null);// 传参Environment.MEDIA_MOUNTED ? 37 | if (files.length < 2) return;//没有外置SD卡 38 | 39 | for (File f: files) { 40 | Log.e(TAG, "choose: " + f.getPath()); 41 | } 42 | 43 | String sdcard = files[1].getPath();//如果有多张外置SD卡,下标就是1,2,3,4,..... 44 | //这个就是外置SD卡的绝对路径 45 | sdcard = sdcard.substring(0, sdcard.indexOf("/Android")); 46 | File sdFile = new File(sdcard); 47 | Log.e(TAG, "sdcard: " + sdcard 48 | + " : " + Environment.getExternalStorageState(sdFile) 49 | + " : " + Environment.isExternalStorageRemovable(sdFile) 50 | + " : " + Environment.isExternalStorageEmulated(sdFile)); 51 | } 52 | 53 | public void choose(View view) { 54 | //这种方式可以获取到外置SD卡的URI, 55 | Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); 56 | startActivityForResult(intent, 1); 57 | } 58 | 59 | @Override 60 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 61 | super.onActivityResult(requestCode, resultCode, data); 62 | if (resultCode != Activity.RESULT_OK || data == null) { 63 | return; 64 | } 65 | 66 | Uri fileUri = data.getData(); 67 | Log.e(TAG, "onActivityResult: " + fileUri.getPath() 68 | + " : " + fileUri.getAuthority() 69 | + " : " + fileUri.getScheme()); 70 | //把Uri转换成文件的绝对路径,Google,也可参考FileMultipleSelectionFragment.java中的转换 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /app/src/main/res/layout/dialog_2_btn_alert.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 18 | 21 | 34 | 38 | 44 | 53 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /app/src/main/java/utils/get_context_no_dependence_anything/AndroidHacks.java: -------------------------------------------------------------------------------- 1 | package utils.get_context_no_dependence_anything; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.util.Log; 6 | 7 | import androidx.annotation.NonNull; 8 | 9 | import java.lang.reflect.Method; 10 | 11 | /** 12 | * 借用的源码: 13 | * https://github.com/kaedea/Feya/blob/master/feya/applications/droid.feya/src/main/java/me/kaede/feya/context/AndroidHacks.java 14 | */ 15 | @SuppressWarnings("WeakerAccess") 16 | public class AndroidHacks { 17 | private static final String TAG = "AndroidHacks"; 18 | private static Object sActivityThread; 19 | 20 | @NonNull 21 | public static Object getActivityThread() { 22 | if (sActivityThread != null) return sActivityThread; 23 | synchronized (AndroidHacks.class) { 24 | if (sActivityThread != null) return sActivityThread; 25 | 26 | if (Looper.getMainLooper() == Looper.myLooper()) { 27 | sActivityThread = getActivityThreadFromUIThread(); 28 | if (sActivityThread != null) return sActivityThread; 29 | } 30 | Handler handler = new Handler(Looper.getMainLooper()); 31 | synchronized (AndroidHacks.class) { 32 | handler.post(new Runnable() { 33 | @Override 34 | public void run() { 35 | sActivityThread = getActivityThreadFromUIThread(); 36 | synchronized (AndroidHacks.class) { 37 | AndroidHacks.class.notifyAll(); 38 | } 39 | } 40 | }); 41 | try { 42 | while (sActivityThread == null) { 43 | AndroidHacks.class.wait(); 44 | } 45 | } catch (InterruptedException e) { 46 | Log.e(TAG, "Waiting notification from UI thread error.", e); 47 | } 48 | } 49 | } 50 | return sActivityThread; 51 | } 52 | 53 | private static Object getActivityThreadFromUIThread() { 54 | Object activityThread = null; 55 | try { 56 | Method method = Class.forName("android.app.ActivityThread").getMethod("currentActivityThread"); 57 | method.setAccessible(true); 58 | activityThread = method.invoke(null); 59 | } catch (final Exception e) { 60 | Log.e(TAG, "Failed to get ActivityThread from ActivityThread#currentActivityThread. " + 61 | "In some case, this method return null in worker thread.", e); 62 | } 63 | return activityThread; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /app/src/main/java/template/ToastUtils.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.content.Context; 4 | import android.graphics.Color; 5 | import android.graphics.drawable.GradientDrawable; 6 | import android.util.TypedValue; 7 | import android.view.Gravity; 8 | import android.widget.TextView; 9 | import android.widget.Toast; 10 | 11 | import androidx.annotation.StringRes; 12 | 13 | public class ToastUtils { 14 | 15 | private static Toast toast; 16 | public static void show(Context context, CharSequence text, int duration) { 17 | if (null == toast) { 18 | toast = Toast.makeText(context, text, duration); 19 | } else { 20 | toast.setText(text); 21 | toast.setDuration(duration); 22 | } 23 | toast.show(); 24 | } 25 | public static void show(Context context, @StringRes int resId, int duration) { 26 | show(context, context.getResources().getText(resId), duration); 27 | } 28 | 29 | private static Toast centerToast; 30 | public static void showCenter(Context context, CharSequence text, int duration) { 31 | if (null == centerToast) { 32 | centerToast = Toast.makeText(context, text, duration); 33 | centerToast.setGravity(Gravity.CENTER, 0, 0); 34 | } else { 35 | centerToast.setText(text); 36 | centerToast.setDuration(duration); 37 | } 38 | centerToast.show(); 39 | } 40 | public static void showCenter(Context context, @StringRes int resId, int duration) { 41 | showCenter(context, context.getResources().getText(resId), duration); 42 | } 43 | 44 | private static Toast blackToast; 45 | private static TextView textView; 46 | public static void showBlack(Context context, CharSequence text, int duration) { 47 | if (null == blackToast) { 48 | blackToast = new Toast(context); 49 | blackToast.setGravity(Gravity.CENTER, 0, 0); 50 | 51 | GradientDrawable drawable = new GradientDrawable(); 52 | drawable.setShape(GradientDrawable.RECTANGLE); 53 | drawable.setColor(Color.argb(185, 0, 0, 0)); 54 | drawable.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, context.getResources().getDisplayMetrics())); 55 | 56 | textView = new TextView(context); 57 | textView.setBackground(drawable); 58 | textView.setTextSize(17); 59 | textView.setTextColor(Color.WHITE); 60 | int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, context.getResources().getDisplayMetrics()); 61 | textView.setPadding(padding, padding, padding, padding); 62 | blackToast.setView(textView); 63 | } 64 | blackToast.setDuration(duration); 65 | textView.setText(text); 66 | blackToast.show(); 67 | } 68 | public static void showBlack(Context context, @StringRes int resId, int duration) { 69 | showBlack(context, context.getResources().getText(resId), duration); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /app/src/main/java/template/RxJava3Templates.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.util.Log; 5 | 6 | import androidx.annotation.NonNull; 7 | 8 | import io.reactivex.rxjava3.core.Observable; 9 | import io.reactivex.rxjava3.core.ObservableEmitter; 10 | import io.reactivex.rxjava3.core.ObservableOnSubscribe; 11 | import io.reactivex.rxjava3.functions.Consumer; 12 | import io.reactivex.rxjava3.functions.Function; 13 | import io.reactivex.rxjava3.schedulers.Schedulers; 14 | 15 | // 详细教程:https://blog.csdn.net/ezconn/article/details/133844948 16 | public class RxJava3Templates { 17 | 18 | private static final String TAG = "RxJava3Templates"; 19 | 20 | // 线程切换示例 21 | @SuppressLint("CheckResult") 22 | public void test1() { 23 | // 详细请看: https://zhuanlan.zhihu.com/p/346694377 24 | Observable.create(new ObservableOnSubscribe() { 25 | // .subscribeOn() 改变发射源头的执行线程,也就是这里的执行线程 26 | @Override 27 | public void subscribe(@NonNull ObservableEmitter emitter) throws Throwable { 28 | Log.e(TAG, "apply0: " + Thread.currentThread().getName()); 29 | emitter.onNext(""); 30 | emitter.onComplete(); 31 | } 32 | }) 33 | // 切换下面map的执行线程 34 | .observeOn(Schedulers.io()) 35 | .map(new Function() { 36 | @Override 37 | public Integer apply(String s) throws Throwable { 38 | Log.e(TAG, "apply1: " + Thread.currentThread().getName()); 39 | Thread.sleep(1000); 40 | return 1; 41 | } 42 | }) 43 | // 切换下面map的执行线程 44 | .observeOn(Schedulers.computation()) 45 | .map(new Function() { 46 | @Override 47 | public String apply(Integer integer) throws Throwable { 48 | Log.e(TAG, "apply2: " + Thread.currentThread().getName()); 49 | return ""; 50 | } 51 | }) 52 | // 切换下面map的执行线程 53 | .observeOn(Schedulers.single()) 54 | .map(new Function() { 55 | @Override 56 | public Float apply(String s) throws Throwable { 57 | Log.e(TAG, "apply3: " + Thread.currentThread().getName()); 58 | return 0f; 59 | } 60 | }) 61 | // 切换下面subscribe的执行线程 62 | .subscribeOn(Schedulers.computation()) 63 | .subscribe(new Consumer() { 64 | @Override 65 | public void accept(Float aFloat) throws Throwable { 66 | Log.e(TAG, "apply4: " + Thread.currentThread().getName()); 67 | } 68 | }); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /app/src/main/java/template/fragment_activity/FragmentActivity.java: -------------------------------------------------------------------------------- 1 | package template.fragment_activity; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.os.Bundle; 6 | import android.os.SystemClock; 7 | import android.util.Log; 8 | import android.util.LongSparseArray; 9 | 10 | import androidx.appcompat.app.AppCompatActivity; 11 | import androidx.fragment.app.Fragment; 12 | 13 | //使用final后,编译器会有方法内联优化 14 | public final class FragmentActivity extends AppCompatActivity { 15 | 16 | private static final String FRAGMENT_CLASS = "FragmentClass"; 17 | private static final String FRAGMENT_OBJECT = "FragmentObject"; 18 | private static final String TAG = "FragmentActivity"; 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | 24 | try { 25 | long key = getIntent().getLongExtra(FRAGMENT_OBJECT, Long.MIN_VALUE); 26 | Fragment fragment = fragmentMap.get(key); 27 | fragmentMap.remove(key); 28 | 29 | if (fragment == null) { 30 | Class fs = Class.forName(getIntent().getStringExtra(FRAGMENT_CLASS)); 31 | fragment = (Fragment) fs.newInstance(); 32 | } 33 | 34 | //这里作为root view不加入到返回栈中,使back键可以关闭Activity 35 | getSupportFragmentManager() 36 | .beginTransaction() 37 | .add(android.R.id.content, fragment) 38 | .commit(); 39 | } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { 40 | Log.e(TAG, "", e); 41 | } 42 | } 43 | 44 | /** 45 | * 直接启动activity 46 | * @param context Context 47 | * @param cls Class extends Fragment 48 | */ 49 | public static void startFragment(Context context, Class cls) { 50 | context.startActivity(new Intent(context, FragmentActivity.class).putExtra(FRAGMENT_CLASS, cls.getName())); 51 | } 52 | 53 | private static final LongSparseArray fragmentMap = new LongSparseArray<>(2); 54 | public static void startFragment(Context context, Fragment fragment) { 55 | long key = SystemClock.elapsedRealtime(); 56 | fragmentMap.put(key, fragment); 57 | context.startActivity(new Intent(context, FragmentActivity.class).putExtra(FRAGMENT_OBJECT, key)); 58 | } 59 | 60 | /** 61 | * 获取启动的Intent,用户设置一些传递参数,然后用户自己启动 62 | * @param context Context 63 | * @param cls Class extends Fragment 64 | * @return Intent 65 | */ 66 | public static Intent getStartIntent(Context context, Class cls) { 67 | return new Intent(context, FragmentActivity.class).putExtra(FRAGMENT_CLASS, cls.getName()); 68 | } 69 | 70 | public static Intent getStartIntent(Context context, Fragment fragment) { 71 | long key = SystemClock.elapsedRealtime(); 72 | fragmentMap.put(key, fragment); 73 | return new Intent(context, FragmentActivity.class).putExtra(FRAGMENT_OBJECT, key); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /app/src/main/java/template/RecyclerViewItem.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.os.SystemClock; 4 | import android.view.ContextMenu; 5 | import android.view.LayoutInflater; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.widget.TextView; 9 | 10 | import androidx.annotation.NonNull; 11 | import androidx.recyclerview.widget.RecyclerView; 12 | 13 | import java.util.ArrayList; 14 | import java.util.WeakHashMap; 15 | 16 | /** 17 | * 给RecyclerView的Item添加上下文菜单,和点击事件 18 | */ 19 | public class RecyclerViewItem extends RecyclerView.Adapter implements View.OnCreateContextMenuListener, View.OnClickListener { 20 | 21 | ArrayList datas; 22 | 23 | //已选中的位置,划重点 24 | int selectedPosition = RecyclerView.NO_POSITION; 25 | //保存映射,划重点 26 | WeakHashMap item2Holder = new WeakHashMap<>(10); 27 | 28 | ItemInterface itemInterface;//用于传递Item的点击事件 29 | 30 | @NonNull 31 | @Override 32 | public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 33 | View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false); 34 | view.setOnCreateContextMenuListener(this);//划重点,上下文菜单 35 | view.setOnClickListener(this);//划重点,点击事件 36 | return new MyViewHolder(view); 37 | } 38 | 39 | @Override 40 | public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { 41 | //先做好映射 42 | item2Holder.put(holder.itemView, holder);//划重点 43 | //再绑定数据 44 | } 45 | 46 | @Override 47 | public int getItemCount() { 48 | return null == datas? 0 : datas.size(); 49 | } 50 | 51 | /* 52 | 在Activity 或者Fragment中重写上下文菜单点击方法 53 | @Override 54 | public boolean onContextItemSelected(MenuItem item) { 55 | if (item.getItemId() == ContextMenu.FIRST 56 | && RecyclerView.NO_POSITION != adapter.selectedPosition) { 57 | deleteData(); 58 | adapter.selectedPosition = RecyclerView.NO_POSITION;//清除位置 59 | } 60 | return super.onContextItemSelected(item); 61 | } 62 | */ 63 | //实现View.OnCreateContextMenuListener 64 | @Override//上下文菜单 65 | public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { 66 | selectedPosition = item2Holder.get(v).getAdapterPosition();//划重点 67 | menu.add(ContextMenu.NONE, ContextMenu.FIRST, ContextMenu.NONE, "删除"); 68 | menu.add(ContextMenu.NONE, ContextMenu.FIRST + 1, ContextMenu.NONE, "收藏"); 69 | } 70 | 71 | //View.OnClickListener 72 | @Override//item点击事件 73 | public void onClick(View v) { 74 | itemInterface.onItemClick(item2Holder.get(v).getAdapterPosition());//划重点 75 | } 76 | 77 | public static interface ItemInterface { 78 | void onItemClick(int position); 79 | void onItemLongClick(int position); 80 | } 81 | } 82 | 83 | class MyViewHolder extends RecyclerView.ViewHolder { 84 | TextView tv1, 85 | tv2, 86 | tv3; 87 | 88 | public MyViewHolder(@NonNull View itemView) { 89 | super(itemView); 90 | // tv1 = itemView.findViewById(R.id.tv1); 91 | // tv2 = itemView.findViewById(R.id.tv2); 92 | // tv3 = itemView.findViewById(R.id.tv3); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /app/src/main/java/template/ProgressHUD.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.content.Context; 6 | import android.graphics.Color; 7 | import android.graphics.drawable.GradientDrawable; 8 | import android.util.TypedValue; 9 | import android.view.Gravity; 10 | import android.view.ViewGroup; 11 | import android.widget.FrameLayout; 12 | import android.widget.ProgressBar; 13 | 14 | import java.lang.ref.WeakReference; 15 | 16 | import min.test.android_app_template.R; 17 | 18 | public class ProgressHUD { 19 | 20 | private static AlertDialog dialog; 21 | 22 | private static ProgressBar initProgressBar(Activity activity) { 23 | ProgressBar bar = new ProgressBar(activity, null, android.R.attr.progressBarStyle); 24 | int padding = dp2px(activity, 20); 25 | bar.setPadding(padding, padding, padding, padding); 26 | 27 | int wh = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, activity.getResources().getDisplayMetrics()); 28 | FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(wh, wh); 29 | flp.gravity = Gravity.CENTER; 30 | bar.setLayoutParams(flp); 31 | 32 | GradientDrawable drawable = new GradientDrawable(); 33 | drawable.setShape(GradientDrawable.RECTANGLE); 34 | // drawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);//配合setColors使用 35 | drawable.setColor(Color.argb(185, 0, 0, 0)); 36 | drawable.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, activity.getResources().getDisplayMetrics())); 37 | bar.setBackground(drawable); 38 | 39 | return bar; 40 | } 41 | 42 | /** 43 | * 进度条显示在整个window上面,下层view无法点击,使用{@link ProgressHUD#dismiss()}移除 44 | * @param activity 45 | * @see ProgressHUD#dismiss() 46 | */ 47 | public static void showOnWindow(Activity activity) { 48 | ProgressBar bar = initProgressBar(activity); 49 | dialog = new AlertDialog.Builder(activity, R.style.NoBackgroundDialog) 50 | .setCancelable(false) 51 | .setView(bar) 52 | .show(); 53 | } 54 | 55 | /** 56 | * @see ProgressHUD#showOnWindow(Activity) 57 | */ 58 | public static void dismiss() { 59 | if (null == dialog) return; 60 | dialog.dismiss(); 61 | dialog = null; 62 | } 63 | 64 | //使用弱引用,可以防止内存泄漏 65 | private static WeakReference wrpb; 66 | /** 67 | * 指示器显示在Activity的DecorView的上面,可以随着Activity的消失而消失, 68 | * 请在Activity销毁前调用{@link ProgressHUD#remove()},否则可能造成内存泄漏 69 | * @param activity 70 | * @see ProgressHUD#remove() 71 | */ 72 | public static void showOnContent(Activity activity) { 73 | ProgressBar pb = initProgressBar(activity); 74 | wrpb = new WeakReference<>(pb); 75 | ViewGroup vg = (ViewGroup) activity.getWindow().getDecorView().findViewById(android.R.id.content); 76 | vg.addView(pb); 77 | } 78 | 79 | /** 80 | * @see ProgressHUD#showOnContent(Activity) 81 | */ 82 | public static void remove() { 83 | if (null == wrpb || wrpb.get() == null) return; 84 | // ((ViewGroup) activity.getWindow().getDecorView() 85 | // .findViewById(android.R.id.content)).removeView(wrpb.get()); 86 | ((ViewGroup) wrpb.get().getParent()).removeView(wrpb.get()); 87 | wrpb = null; 88 | } 89 | 90 | 91 | private static float scale = 0; 92 | private static int dp2px(Context context, float dpValue) { 93 | if (0 == scale) scale = context.getResources().getDisplayMetrics().density; 94 | return (int) (dpValue * scale + 0.5f); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /app/src/main/java/template/recyclerview_group/SectionRVAdapter.java: -------------------------------------------------------------------------------- 1 | package template.recyclerview_group; 2 | 3 | import android.view.LayoutInflater; 4 | import android.view.View; 5 | import android.view.ViewGroup; 6 | import android.widget.TextView; 7 | 8 | import androidx.recyclerview.widget.RecyclerView; 9 | 10 | import java.util.ArrayList; 11 | 12 | public class SectionRVAdapter extends RecyclerView.Adapter { 13 | public int count = 0; 14 | public int sectionFirstItemPosition[]; 15 | 16 | private final ArrayList> mValues; 17 | private final OnItemInteractionListener mListener; 18 | 19 | public SectionRVAdapter(ArrayList> items, OnItemInteractionListener listener) { 20 | mValues = items; 21 | mListener = listener; 22 | } 23 | 24 | @Override 25 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 26 | View view = LayoutInflater.from(parent.getContext()) 27 | .inflate(android.R.layout.simple_list_item_1, parent, false); 28 | return new ViewHolder(view, mListener); 29 | } 30 | 31 | @Override 32 | public final void onBindViewHolder(final ViewHolder holder, int position) { 33 | if (null != sectionFirstItemPosition && position >= sectionFirstItemPosition[0]) {//有多个分组 34 | int groupFirst; 35 | for (int i = sectionFirstItemPosition.length - 1; i > -1; --i) {//倒序循环 36 | groupFirst = sectionFirstItemPosition[i];//从最大的值开始 37 | if (position >= groupFirst) { 38 | onBindViewHolder(holder, i+1, position - groupFirst); 39 | return; 40 | } 41 | } 42 | } else {//第一组 43 | onBindViewHolder(holder, 0, position); 44 | } 45 | } 46 | 47 | public void onBindViewHolder(final ViewHolder holder, int section, int row) { 48 | String mItem = mValues.get(section).get(row); 49 | holder.section = section; 50 | holder.row = row; 51 | } 52 | 53 | @Override 54 | public int getItemCount() { 55 | return count > 0? count : 0; 56 | } 57 | 58 | public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { 59 | public TextView tvTitle; 60 | public int section; 61 | public int row; 62 | public Object data; 63 | private OnItemInteractionListener mListener; 64 | 65 | public ViewHolder(View view, OnItemInteractionListener listener) { 66 | super(view); 67 | // tvTitle = view.findViewById(R.id.) 68 | mListener = listener; 69 | view.setOnClickListener(this); 70 | view.setOnLongClickListener(this); 71 | } 72 | 73 | @Override 74 | public void onClick(View v) { 75 | // getAdapterPosition() 76 | if (null != mListener) { 77 | mListener.OnItemClick(section, row, data); 78 | } 79 | } 80 | 81 | @Override 82 | public boolean onLongClick(View v) { 83 | if (null != mListener) { 84 | mListener.OnItemLongClick(section, row, data); 85 | } 86 | return true; 87 | } 88 | 89 | @Override 90 | public String toString() { 91 | return super.toString() + " '" + tvTitle.getText() + "'"; 92 | } 93 | } 94 | 95 | public interface OnItemInteractionListener { 96 | void OnItemClick(int section, int row, Object data); 97 | void OnItemLongClick(int section, int row, Object data); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /厂商推送服务端关键字段.txt: -------------------------------------------------------------------------------- 1 | 厂商推送与页面跳转、推送测试、无限制推送相关的重要字段 2 | 1、字段详细说明请查官方文档,消息结构差异很大,一定要看官方文档 3 | 2、Android intent 转成 uri 后的固定格式: intent:#Intent;action="action 路径";component="包名"/"Activity 组件路径";S.key1=value1;i.key2=2;end 4 | intent uri 必须以 "intent:#Intent;" 开头,以 ";end" 结尾。 5 | 不允许存在多个 "action=" 字符或 "component=" 字符。 6 | "S.":代表参数值是 String 格式。 7 | "i.":代表参数值是 int 格式。 8 | 3、厂商推送对消息有数量限制,默认只有1~2条,想无限制推送,需要去厂商申请消息分类 9 | 4、有些厂商提供了测试模式,测试模式可以推送多条 10 | 5、tag 和 notify id 一般用于通知栏的覆盖或者撤回,用不到可以不填 11 | 6、被跳转的 Activity 必须设置 android:exported="true" 和 ,某些厂商得这么设置,否则无法打开Activity 12 | 7、一定要防止 Activity 类名打包时被混淆,否则intent里的Activity就对不上了 13 | 14 | 小米 15 | 无测试字段: 16 | restricted_package_name: App的包名,根据需要填。小米的一个AppID可以设置多个包名,此字段在这种情况下就有用了 17 | extra.notify_effect: "2" // 通知栏点击后打开app的任一Activity 18 | extra.intent_uri : "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end" 19 | extra.channel_id : // 与无限制推送有关 20 | tag: // 目前无此参数 21 | notify_id: // 标识符 22 | 无限制推送: 申请消息分类,得到的 channel_id 填到 extra.channel_id 字段 23 | 推送角标由系统控制 24 | 25 | OPPO 26 | 无测试字段:貌似可以先在推送运营后台(配置管理中)添加测试设备,然后被添加的设备貌似就可以无限制推送了(未验证) 27 | click_action_type: 4 // 跳转指定应用内页(全路径类名); 5:跳转Intent scheme URL,要加字段 click_action_url: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end" 28 | click_action_activity: "min.test.TestActivity" 29 | action_parameters: "{\"messageNo\":null,\"title\":\"您的订单已取消\"}" 30 | channel_id :// 与无限制推送有关,旧的 31 | category: // 消息分类,与无限制推送有关,新的 32 | notify_level: // 通知弹窗方式/提醒方式,新的 33 | tag: // 目前无此参数 34 | notify_id: // 标识符 35 | 无限制推送: 申请私信通道权限,要发邮件,通过后要在平台上登记 36 | 推送无角标设置 37 | 38 | vivo 39 | pushMode: 1 // 先在推送运营后台添加测试设备,否则无效;推送模式 0:正式推送;1:测试推送,不填默认0; 40 | category: // 消息分类,与无限制推送有关 41 | skipType: 4 // 打开app内指定页面 42 | skipContent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end" 43 | addBadge: true // 角标,大部分类型的App还未开放,具体看文档或找客服问 44 | clientCustomMap: // 看文档,也许有用 45 | channel_id: // 目前无此参数 46 | tag: // 目前无此参数 47 | notifyId: // 标识符 48 | 无限制推送: 提工单开通 49 | 50 | 华为 51 | target_user_type: 1 // 1:测试消息;0:普通消息;不填默认0;每个应用每日可发送该测试消息500条且不受每日单设备推送数量上限要求 52 | category: // 消息分类,与无限制推送有关,自分类权益 开通哪个填哪个 53 | click_action: { 54 | type: 3, // 打开应用自定义页面 55 | intent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end" 56 | } 57 | badge: { 58 | class: "min.test.TestActivity", // 入口Activity 59 | add_num: 1 // 不填置默认+1 60 | } 61 | channel_id: 62 | tag: // 标识符 63 | notify_id: // 标识符 64 | 无限制推送: 在 推送服务->配置 里开通 自分类权益 65 | 66 | 荣耀 67 | targetUserType: 1 // 1:测试消息;0:普通消息;不填默认0;每个应用每日可发送该测试消息500条且不受每日单设备推送数量上限要求 68 | importance: "NORMAL" // 消息分类,目前与无限制推送有关,以后可能会变动;LOW:资讯营销类消息,NORMAL:服务与通讯类消息;NORMAL无限制推送 69 | clickAction: { 70 | type: 1, // 打开应用自定义页面 71 | intent: "intent:#Intent;action=min.test.myaction;component=min.test/min.test.TestActivity;S.key1=value;i.key2=2;S.key3={\"messageNo\":null,\"title\":\"您的订单已取消\"};end" 72 | } 73 | badge: { 74 | badgeClass: "min.test.TestActivity", // 入口Activity 75 | addNum: 1 // 不填置默认+1 76 | } 77 | channel_id: // 目前无此参数 78 | tag: // 标识符 79 | notifyId: // 标识符 80 | 无限制推送: 目前参考 importance 81 | 82 | FCM 83 | restricted_package_name: App的包名。根据需要填。注册令牌必须匹配的应用程序的包名称才能接收消息。 84 | data: json object // 传参 85 | click_action: "min.test.TestActivity" // 可以是 Activity 全名(貌似这种方式无效),也可以是 action name 86 | color: "#FF0000" // 通知的图标颜色,以#rrggbb 格式表示。如果app内部没有默认值,最好填一个 87 | notification_count: 1 // 角标,不填置默认+1 88 | channel_id: 89 | tag: // 标识符 90 | notify_id: // 目前无此参数 91 | -------------------------------------------------------------------------------- /app/src/main/java/template/CircleProgressView.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.animation.ValueAnimator; 4 | import android.content.Context; 5 | import android.graphics.Canvas; 6 | import android.graphics.Color; 7 | import android.graphics.Paint; 8 | import android.graphics.RectF; 9 | import android.util.AttributeSet; 10 | import android.util.TypedValue; 11 | import android.view.View; 12 | import android.view.animation.LinearInterpolator; 13 | 14 | import androidx.annotation.NonNull; 15 | import androidx.annotation.Nullable; 16 | 17 | import java.util.Optional; 18 | 19 | public class CircleProgressView extends View { 20 | 21 | private Paint circlePaint; 22 | private Paint circleBgPaint; 23 | private float strokeWidth; 24 | private float radius; 25 | private float centerX; 26 | private float centerY; 27 | private RectF rectF; 28 | private float sweepAngle; 29 | private ValueAnimator animator; 30 | 31 | public CircleProgressView(Context context, @Nullable AttributeSet attrs) { 32 | super(context, attrs); 33 | init(); 34 | } 35 | 36 | public CircleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 37 | super(context, attrs, defStyleAttr); 38 | init(); 39 | } 40 | 41 | public CircleProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 42 | super(context, attrs, defStyleAttr, defStyleRes); 43 | init(); 44 | } 45 | 46 | public CircleProgressView(Context context) { 47 | super(context); 48 | init(); 49 | } 50 | 51 | private void init() { 52 | sweepAngle = 0; 53 | strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, 54 | getResources().getDisplayMetrics()); 55 | // 动画环画笔 56 | circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 57 | circlePaint.setColor(Color.BLUE); 58 | circlePaint.setStyle(Paint.Style.STROKE); 59 | circlePaint.setStrokeCap(Paint.Cap.ROUND); 60 | circlePaint.setStrokeWidth(strokeWidth); 61 | 62 | // 背景环画笔 63 | circleBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 64 | circleBgPaint.setColor(Color.GRAY); 65 | circleBgPaint.setStyle(Paint.Style.STROKE); 66 | circleBgPaint.setStrokeCap(Paint.Cap.ROUND); 67 | circleBgPaint.setStrokeWidth(strokeWidth); 68 | } 69 | 70 | @Override 71 | protected void onSizeChanged(int w, int h, int oldw, int oldh) { 72 | super.onSizeChanged(w, h, oldw, oldh); 73 | float minSize = Math.min(getHeight(), getWidth()); 74 | radius = (minSize - strokeWidth) / 2; 75 | centerX = getWidth() / 2.0f; 76 | centerY = getHeight() / 2.0f; 77 | rectF = new RectF(); 78 | rectF.left = 0 + strokeWidth/2; 79 | rectF.top = 0 + strokeWidth/2; 80 | rectF.right = minSize - strokeWidth/2; 81 | rectF.bottom = minSize - strokeWidth/2; 82 | } 83 | 84 | @Override 85 | protected void onDraw(@NonNull Canvas canvas) { 86 | super.onDraw(canvas); 87 | 88 | // 绘制圆环 89 | canvas.drawCircle(centerX, centerY, radius, circleBgPaint); 90 | // canvas.drawArc(rectF, 0, 360, false, circleBgPaint); 91 | canvas.drawArc(rectF, -90, sweepAngle, false, circlePaint); 92 | } 93 | 94 | /** 95 | * 开始动画 96 | * @param totalTime 总时间 97 | * @param remainingTime 剩余时间 98 | */ 99 | public void startAnim(long totalTime, long remainingTime) { 100 | Optional.ofNullable(animator).ifPresent(ValueAnimator::cancel); 101 | 102 | animator = ValueAnimator.ofFloat(-360.0f * remainingTime / totalTime, 0); 103 | animator.setDuration(remainingTime); 104 | animator.setInterpolator(new LinearInterpolator()); 105 | animator.addUpdateListener(animation -> { 106 | sweepAngle = (Float) animation.getAnimatedValue(); 107 | invalidate(); 108 | }); 109 | animator.start(); 110 | } 111 | 112 | public void stopAnim() { 113 | if (null != animator) { 114 | animator.cancel(); 115 | animator = null; 116 | } 117 | sweepAngle = 0; 118 | invalidate(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /app/src/main/java/template/BottomNavigationFragment.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.os.Bundle; 5 | import android.view.LayoutInflater; 6 | import android.view.MenuItem; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import androidx.annotation.NonNull; 11 | import androidx.annotation.Nullable; 12 | import androidx.fragment.app.Fragment; 13 | 14 | import com.google.android.material.bottomnavigation.BottomNavigationItemView; 15 | import com.google.android.material.bottomnavigation.BottomNavigationMenuView; 16 | import com.google.android.material.bottomnavigation.BottomNavigationView; 17 | import com.google.android.material.bottomnavigation.LabelVisibilityMode; 18 | 19 | //https://www.jianshu.com/p/24278f3259b3 20 | //https://stackoverflow.com/questions/40176244/how-to-disable-bottomnavigationview-shift-mode 21 | public class BottomNavigationFragment extends Fragment { 22 | 23 | private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener 24 | = new BottomNavigationView.OnNavigationItemSelectedListener() { 25 | 26 | @Override 27 | public boolean onNavigationItemSelected(@NonNull MenuItem item) { 28 | switch (item.getItemId()) { 29 | } 30 | return false; 31 | } 32 | }; 33 | 34 | /* 35 | 布局文件 36 | 48 | */ 49 | 50 | @Nullable 51 | @Override 52 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 53 | 54 | /* 55 | BottomNavigationView的item移动的原因有两个: 56 | 1、选中的item显示title,而未选中的不显示; 57 | 解决方案:1.设置所有item不显示title 58 | 2.设置所有item显示title,这也是产生移动的第二个原因 59 | 2、item有2个TextView,分别显示选中和未选中的title,但他们的textSize不一样 60 | 解决方案:1.覆盖这两个textSize,设置成一样 61 | */ 62 | BottomNavigationView navigation = new BottomNavigationView(container.getContext()); 63 | navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); 64 | //解决移动的第1个原因,此属性貌似在安卓8.0以后才有, 65 | //也可在布局文件中设置app:labelVisibilityMode="labeled" 66 | // navigation.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); 67 | /* 68 | 解决移动的第2个原因 69 | 然后把下面两个拷贝到dimens.xml文件中,注意:这两行的值要完全相等,以保证选中和未选中状态的字体大小一样 70 | 12sp 71 | 12sp 72 | 73 | //禁止item平移,但textSize不一样时,会有上下移动 74 | app:itemHorizontalTranslationEnabled="false" 75 | 76 | 如果要设置icon距离上边距的距离,也可以通过重新定义R.dimen.design_bottom_navigation_margin来实现, 77 | 也就是 78 | 12dp 79 | */ 80 | 81 | //使用了上面两种方法,这个就不用了 82 | // removeShiftMode(navigation); 83 | return null; 84 | } 85 | 86 | @SuppressLint("RestrictedApi") 87 | static void removeShiftMode(BottomNavigationView view) { 88 | BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); 89 | for (int i = 0; i < menuView.getChildCount(); i++) { 90 | BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); 91 | //noinspection RestrictedApi 92 | item.setShifting(false);//Android8.0以前不是这个方法,而且要用反射 93 | item.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); 94 | 95 | // set once again checked value, so view will be updated 96 | //noinspection RestrictedApi 97 | item.setChecked(item.getItemData().isChecked()); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /app/src/main/java/utils/get_context_no_dependence_anything/Applications.java: -------------------------------------------------------------------------------- 1 | package utils.get_context_no_dependence_anything; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.Application; 5 | import android.util.Log; 6 | 7 | import androidx.annotation.NonNull; 8 | 9 | import java.lang.reflect.Field; 10 | import java.lang.reflect.Method; 11 | 12 | /** 13 | * 借用的源码: 14 | * https://github.com/kaedea/Feya/blob/master/feya/applications/droid.feya/src/main/java/me/kaede/feya/context/Applications.java 15 | */ 16 | @SuppressWarnings({"WeakerAccess", "unused"}) 17 | public class Applications { 18 | private static final String TAG = "Applications"; 19 | 20 | /** 21 | * Access a global {@link Application} context from anywhere, such as getting a context in a Library 22 | * module without attaching it from App module. 23 | *

24 | * Note that this method may return null in some cases, such as working with a hotfix framework 25 | * or access when the App is terminated. 26 | *

27 | * 此context只用来获取资源,不要用来启动Activity和Service 28 | */ 29 | @NonNull 30 | public static Application context() { 31 | if (CURRENT != null) { 32 | return CURRENT; 33 | } 34 | if (sAttached != null) { 35 | Log.w(TAG, "Seems CURRENT is null here, you may call Applications#context() before or " + 36 | "inside Application#attachBaseContext(Context), which is not recommended."); 37 | return sAttached; 38 | } 39 | throw new IllegalStateException("Please make sure you do not call Applications#context() " + 40 | "before or inside Application#attachBaseContext(Context). " + 41 | "If you have to, please call Applications#attach(Application) first."); 42 | } 43 | 44 | @SuppressLint("StaticFieldLeak") 45 | private static final Application CURRENT; 46 | @SuppressLint("StaticFieldLeak") 47 | private static Application sAttached; 48 | 49 | static { 50 | /* 51 | * The following 'Magic Code' is going to access the Application context from ActivityThread. 52 | * For now, it works only after Applications#attach(Application). 53 | * 54 | * Note that if you call this method before or inside Applications#attach(Application), 55 | * {@link Applications#CURRENT} will always be null. 56 | */ 57 | try { 58 | Object app = autoAttach(); 59 | if (app == null) { 60 | throw new IllegalStateException("Can not get Application context, " + 61 | "pls make sure that you didn't call this method before or inner " + 62 | "Application#attachBaseContext(Context)"); 63 | } 64 | CURRENT = (Application) app; 65 | 66 | //noinspection ConstantConditions 67 | if (CURRENT == null) { 68 | throw new IllegalStateException("Can not access Application context from ActivityThread, " + 69 | "please make sure that you did not call this method before or inside Application#attachBaseContext(Context)."); 70 | } 71 | } catch (Throwable e) { 72 | throw new IllegalStateException("Can not access Application context by magic code, boom!", e); 73 | } 74 | } 75 | 76 | private static Object autoAttach() throws ReflectiveOperationException { 77 | Object activityThread = AndroidHacks.getActivityThread(); 78 | Class activityThreadClass = Class.forName("android.app.ActivityThread"); 79 | Method method = activityThreadClass.getMethod("getApplication"); 80 | method.setAccessible(true); 81 | Object app = method.invoke(activityThread); 82 | method.setAccessible(false); 83 | 84 | if (app == null) { 85 | Field field = activityThreadClass.getField("mInitialApplication"); 86 | field.setAccessible(true); 87 | app = field.get(activityThread); 88 | field.setAccessible(false); 89 | } 90 | return app; 91 | } 92 | 93 | /** 94 | * Manually attach an Application context for {@link Applications#sAttached}. If the above 95 | * Magic Code works, this method is not necessary. 96 | * 97 | * @see #autoAttach() 98 | */ 99 | public static void attach(@NonNull Application app) { 100 | if (sAttached == null) { 101 | sAttached = app; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | // https://developer.android.google.cn/studio/projects/android-library 2 | import java.util.Properties 3 | 4 | plugins { 5 | alias(libs.plugins.android.application) 6 | alias(libs.plugins.kotlin.android) 7 | } 8 | 9 | // 上面要 import 10 | val keystoreProperties = Properties() 11 | // 自定义keystore本地配置。放在项目根目录下 12 | val file = rootProject.file("keystore.properties"); 13 | if (file.exists()) { 14 | file.inputStream().use { keystoreProperties.load(it) } 15 | } 16 | 17 | android { 18 | namespace = "min.test.android_app_template" 19 | compileSdk = 35 20 | 21 | defaultConfig { 22 | applicationId = "min.test.android_app_template" 23 | minSdk = 26 24 | targetSdk = 35 25 | versionCode = 1 26 | versionName = "1.0" 27 | // 自定义打包名称,不完全自定义,后面自动会加上${buildType.name} 28 | base.archivesName = "Template-v$versionName-$versionCode-" + (Math.floor(Math.random() * 1000000) + 1).toInt() 29 | // 替换值 30 | manifestPlaceholders += mapOf( 31 | "AAA" to "1111", 32 | ) 33 | ndk.abiFilters += mutableSetOf("arm64-v8a", "armeabi-v7a", "x86_64") 34 | /*splits { 35 | // 根据像素密度生成多个单一apk 36 | density { 37 | isEnable = true 38 | reset() 39 | include("hdpi", "xhdpi", "xxhdpi", "xxxhdpi") 40 | } 41 | // 根据ABI生成多个单一apk 42 | abi { 43 | // Enables building multiple APKs per ABI. 44 | isEnable = true 45 | 46 | // By default all ABIs are included, so use reset() and include to specify that we only 47 | // want APKs for x86 and x86_64. 48 | 49 | // Resets the list of ABIs that Gradle should create APKs for to none. 50 | reset() 51 | 52 | // 不能与 ndk.abiFilters 同时配置,否则报错 53 | // Specifies a list of ABIs that Gradle should create APKs for. 54 | include("arm64-v8a", "armeabi-v7a")//"x86", "x86_64" 55 | 56 | // Specifies that we do not want to also generate a universal APK that includes all ABIs. 57 | isUniversalApk = false 58 | } 59 | }*/ 60 | 61 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 62 | } 63 | // 必须放在 buildTypes 上面 64 | signingConfigs { 65 | // release 不存在要自己创建 66 | create("release") { 67 | // keyAlias = keystoreProperties["keyAlias"] as String 68 | // keyPassword = keystoreProperties["keyPassword"] as String 69 | // storeFile = keystoreProperties["storeFile"]?.let { file(it) } 70 | // storePassword = keystoreProperties["storePassword"] as String 71 | } 72 | // debug 本身就有 73 | getByName("debug") { 74 | // keyAlias = keystoreProperties["keyAlias"] as String 75 | // keyPassword = keystoreProperties["keyPassword"] as String 76 | // storeFile = keystoreProperties["storeFile"]?.let { file(it) } 77 | // storePassword = keystoreProperties["storePassword"] as String 78 | } 79 | } 80 | 81 | buildTypes { 82 | release { 83 | isMinifyEnabled = false 84 | proguardFiles( 85 | getDefaultProguardFile("proguard-android-optimize.txt"), 86 | "proguard-rules.pro" 87 | ) 88 | signingConfig = signingConfigs.getByName("release") 89 | } 90 | } 91 | compileOptions { 92 | sourceCompatibility = JavaVersion.VERSION_11 93 | targetCompatibility = JavaVersion.VERSION_11 94 | } 95 | kotlinOptions { 96 | jvmTarget = "11" 97 | } 98 | buildFeatures { 99 | // compose = true 100 | // 支持视图绑定 101 | viewBinding = true 102 | } 103 | } 104 | 105 | dependencies { 106 | 107 | implementation(libs.androidx.core.ktx) 108 | implementation(libs.androidx.appcompat) 109 | // implementation(libs.androidx.activity) 110 | implementation(libs.material) 111 | implementation(libs.androidx.constraintlayout) 112 | implementation(libs.androidx.recyclerview) 113 | implementation(libs.okhttp) 114 | // 跟踪和报告应用的各种运行时指标 115 | implementation(libs.androidx.metrics.performance) 116 | // 读取和写入图片文件 EXIF 标记 117 | implementation(libs.androidx.exifinterface) 118 | implementation(libs.rxjava) 119 | implementation(libs.rxandroid) 120 | // fileTree 写法 121 | implementation(fileTree("libs") { 122 | include("*.aar", "*.jar") 123 | }) 124 | 125 | // 在 Android Studio 中准确衡量代码性能, 性能测试框架 126 | androidTestImplementation(libs.androidx.benchmark.macro.junit4) 127 | // 远程测试框架 128 | androidTestImplementation(libs.androidx.uiautomator) 129 | 130 | testImplementation(libs.junit) 131 | androidTestImplementation(libs.androidx.junit) 132 | androidTestImplementation(libs.androidx.espresso.core) 133 | } -------------------------------------------------------------------------------- /app/src/main/java/template/recyclerview_group/SectionRVTestFragment.java: -------------------------------------------------------------------------------- 1 | package template.recyclerview_group; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | 10 | import androidx.fragment.app.Fragment; 11 | import androidx.recyclerview.widget.LinearLayoutManager; 12 | import androidx.recyclerview.widget.RecyclerView; 13 | 14 | import java.util.ArrayList; 15 | import java.util.LinkedList; 16 | 17 | public class SectionRVTestFragment extends Fragment implements SectionRVAdapter.OnItemInteractionListener { 18 | 19 | private Context context; 20 | private String titles[]; 21 | private ArrayList> tasks; 22 | private ArrayList loadingTasks; 23 | private ArrayList doneTasks; 24 | private ArrayList errorTasks; 25 | 26 | private SectionItemDecoration titleDecoration; 27 | private SectionRVAdapter adapter; 28 | 29 | @Override 30 | public void onCreate(Bundle savedInstanceState) { 31 | super.onCreate(savedInstanceState); 32 | 33 | tasks = new ArrayList<>(3); 34 | loadingTasks = new ArrayList<>(3); 35 | doneTasks = new ArrayList<>(3); 36 | errorTasks = new ArrayList<>(3); 37 | // titles = context.getResources().getStringArray(R.array.permission); 38 | titles = new String[]{"正在下载", "下载完成", "下载失败"}; 39 | 40 | loadingTasks.add("task0-1"); 41 | loadingTasks.add("task0-2"); 42 | loadingTasks.add("task0-3"); 43 | loadingTasks.add("task0-4"); 44 | loadingTasks.add("task0-5"); 45 | loadingTasks.add("task0-6"); 46 | loadingTasks.add("task0-7"); 47 | loadingTasks.add("task0-8"); 48 | loadingTasks.add("task0-9"); 49 | loadingTasks.add("task0-10"); 50 | loadingTasks.add("task0-11"); 51 | loadingTasks.add("task0-12"); 52 | 53 | doneTasks.add("task1-1"); 54 | doneTasks.add("task1-2"); 55 | doneTasks.add("task1-3"); 56 | doneTasks.add("task1-4"); 57 | doneTasks.add("task1-5"); 58 | doneTasks.add("task1-6"); 59 | doneTasks.add("task1-7"); 60 | doneTasks.add("task1-8"); 61 | doneTasks.add("task1-9"); 62 | doneTasks.add("task1-10"); 63 | doneTasks.add("task1-11"); 64 | doneTasks.add("task1-12"); 65 | 66 | errorTasks.add("task2-1"); 67 | errorTasks.add("task2-2"); 68 | errorTasks.add("task2-3"); 69 | errorTasks.add("task2-4"); 70 | errorTasks.add("task2-5"); 71 | errorTasks.add("task2-6"); 72 | errorTasks.add("task2-7"); 73 | errorTasks.add("task2-8"); 74 | errorTasks.add("task2-9"); 75 | errorTasks.add("task2-10"); 76 | errorTasks.add("task2-11"); 77 | errorTasks.add("task2-12"); 78 | } 79 | 80 | @Override 81 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 82 | Bundle savedInstanceState) { 83 | // View view = inflater.inflate(android.R.layout.list_content, container, false); 84 | View view = new RecyclerView(container.getContext());//这里换成自己的视图 85 | if (view instanceof RecyclerView) { 86 | Context context = view.getContext(); 87 | RecyclerView recyclerView = (RecyclerView) view; 88 | recyclerView.setLayoutManager(new LinearLayoutManager(context)); 89 | 90 | adapter = new SectionRVAdapter(tasks, this); 91 | recyclerView.setAdapter(adapter); 92 | 93 | titleDecoration = new SectionItemDecoration(context); 94 | titleDecoration.titleDocksAtTheTop = true; 95 | recyclerView.addItemDecoration(titleDecoration); 96 | sortGroup(); 97 | } 98 | return view; 99 | } 100 | 101 | 102 | @Override 103 | public void onAttach(Context context) { 104 | super.onAttach(context); 105 | this.context = context; 106 | } 107 | 108 | @Override 109 | public void onStart() { 110 | super.onStart(); 111 | } 112 | 113 | @Override 114 | public void onDetach() { 115 | super.onDetach(); 116 | context = null; 117 | } 118 | 119 | private void sortGroup() { 120 | tasks.clear(); 121 | //重新排列数据和标题 122 | LinkedList list = new LinkedList<>(); 123 | if (loadingTasks.size() > 0) { 124 | tasks.add(loadingTasks); 125 | list.add(titles[0]); 126 | } 127 | if (doneTasks.size() > 0) { 128 | tasks.add(doneTasks); 129 | list.add(titles[1]); 130 | } 131 | if (errorTasks.size() > 0) { 132 | tasks.add(errorTasks); 133 | list.add(titles[2]); 134 | } 135 | 136 | SectionItemDecoration.setGroup(titleDecoration, adapter, list, tasks); 137 | adapter.notifyDataSetChanged(); 138 | } 139 | 140 | @Override 141 | public void OnItemClick(int section, int row, Object data) { 142 | Log.e("OnItemClick", section + "," + row); 143 | } 144 | @Override 145 | public void OnItemLongClick(int section, int row, Object data) { 146 | Log.e("OnItemLongClick", section + "," + row); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /app/src/main/java/template/UDP.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.content.Context; 4 | 5 | import java.io.IOException; 6 | import java.net.DatagramPacket; 7 | import java.net.DatagramSocket; 8 | import java.net.InetAddress; 9 | import java.net.InetSocketAddress; 10 | import java.net.SocketException; 11 | import java.net.SocketTimeoutException; 12 | 13 | //发送者 14 | class UDPSender { 15 | private String IPv4; 16 | private DatagramSocket socket; 17 | 18 | /** 19 | * //获取WiFi的ip 20 | WifiInfo wifiInfo = ((WifiManager)context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo(); 21 | int ipAddress = wifiInfo.getIpAddress(); 22 | String IPv4 = ((ipAddress & 0xff) + "." + (ipAddress>>8 & 0xff) + "." + 23 | (ipAddress>>16 & 0xff) + "." + (ipAddress>>24 & 0xff)); 24 | */ 25 | 26 | public static UDPSender getInstance(Context context) throws SocketException { 27 | // DatagramSocket socket = new DatagramSocket(port);//这么写会导致端口一直占用 28 | DatagramSocket socket = new DatagramSocket(null);//这里设置为null,setReuseAddress才会有效 29 | socket.setReuseAddress(true);//可复用,地址或者端口号 30 | socket.setBroadcast(true);//允许发送广播 31 | //socket不用绑定任何IP或端口号也能发送UDP广播,因为系统会自动分配端口 32 | 33 | return new UDPSender(socket, "IPv4"); 34 | } 35 | 36 | private UDPSender(DatagramSocket socket, String IPv4) { 37 | this.IPv4 = IPv4; 38 | this.socket = socket; 39 | } 40 | 41 | private int port = 1234;//对方接收的端口 42 | public void send() { 43 | try { 44 | //要发送的数据 45 | byte[] bytes = "hello".getBytes(); 46 | //广播地址255.255.255.255 47 | byte[] broadcast = new byte[]{(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff}; 48 | // InetAddress.getByName(IPv4);//或者对方地址 49 | //组装数据包 50 | DatagramPacket dataPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByAddress(broadcast), port); 51 | socket.send(dataPacket);//发送数据包 52 | 53 | } catch (IOException e) { 54 | // Log.e(TAG, "run: ", e); 55 | } finally { 56 | cancel(); 57 | } 58 | } 59 | 60 | //发送完数据要释放资源 61 | public void cancel() { 62 | if (null != socket) { 63 | socket.close(); 64 | } 65 | socket = null; 66 | } 67 | } 68 | 69 | class UDPReceiver extends Thread { 70 | 71 | private boolean cancelled = false; 72 | private DatagramSocket socket; 73 | private ReceiveListener listener; 74 | 75 | /** 76 | * 77 | * @param port 要监听的本地端口 78 | * @param listener 把收到的数据通过此接口传递出去 79 | * @return 80 | * @throws SocketException 81 | */ 82 | public static UDPReceiver getInstance(int port, ReceiveListener listener) throws SocketException { 83 | // DatagramSocket socket = new DatagramSocket(port);//这么写会导致端口一直占用 84 | DatagramSocket socket = new DatagramSocket(null); 85 | socket.setReuseAddress(true); 86 | socket.bind(new InetSocketAddress(port));//监听指定的端口,若是不指定端口,系统会自动分配端口 87 | socket.setBroadcast(true); 88 | socket.setSoTimeout(15);//设置超时时间 89 | //若是不指定端口,此方法可获取系统自动分配的端口,然后通过某种方式告诉对方(如:广播包中携带此端口号) 90 | // socket.getLocalPort(); 91 | return new UDPReceiver(socket, listener); 92 | } 93 | 94 | private UDPReceiver(DatagramSocket socket, ReceiveListener listener) { 95 | this.socket = socket; 96 | this.listener = listener; 97 | } 98 | 99 | //取消,释放资源 100 | public void cancel() { 101 | if (cancelled) return; 102 | if (null != socket) socket.close(); 103 | 104 | socket = null; 105 | listener = null; 106 | cancelled = true; 107 | } 108 | 109 | @Override 110 | public void run() { 111 | try { 112 | byte[] bytes; 113 | DatagramPacket dataPacket; 114 | while (!cancelled) { 115 | bytes = new byte[1024]; 116 | dataPacket = new DatagramPacket(bytes, bytes.length);//存放数据的盒子 117 | socket.receive(dataPacket);//接收数据包 118 | new ParseThread(dataPacket, listener).start();//开线程去解析收到的数据,我这里简单粗暴了点 119 | } 120 | } catch (SocketTimeoutException e) { 121 | //超时不用管 122 | } catch (IOException e) { 123 | // Log.e(TAG, "run: ", e); 124 | } finally { 125 | cancel(); 126 | } 127 | } 128 | 129 | //用线程去解析数据 130 | static class ParseThread extends Thread { 131 | private DatagramPacket dataPacket; 132 | private ReceiveListener listener; 133 | 134 | public ParseThread(DatagramPacket dataPacket, ReceiveListener listener) { 135 | this.dataPacket = dataPacket; 136 | this.listener = listener; 137 | } 138 | 139 | @Override 140 | public void run() { 141 | //把收到的数据转成字符串 142 | String message = new String(dataPacket.getData(), dataPacket.getOffset(), dataPacket.getLength()); 143 | //解析message成你要的数据 144 | //把数据传递出去 145 | listener.receive(message); 146 | 147 | dataPacket = null; 148 | listener = null; 149 | } 150 | } 151 | 152 | public interface ReceiveListener { 153 | void receive(String message); 154 | } 155 | } 156 | 157 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Non-project-specific build files: 2 | build.xml 3 | /app/gradlew 4 | /app/gradlew.bat 5 | /app/gradle 6 | map.txt 7 | release-signing.properties 8 | debug-signing.properties 9 | # Ant builds 10 | ant-build 11 | ant-gen 12 | # Eclipse builds 13 | gen 14 | out 15 | # Gradle build artifacts 16 | .gradletasknamecache 17 | gradle-app.setting 18 | 19 | #================== Android.gitignore ================== 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | release/ 24 | 25 | # Local configuration file (sdk path, etc) 26 | local.properties 27 | 28 | # Log/OS Files 29 | *.log 30 | 31 | # Android Studio generated files and folders 32 | captures/ 33 | .externalNativeBuild/ 34 | .cxx/ 35 | *.aab 36 | *.apk 37 | output.json 38 | output-metadata.json 39 | 40 | # IntelliJ 41 | *.iml 42 | .idea/ 43 | misc.xml 44 | deploymentTargetDropDown.xml 45 | render.experimental.xml 46 | 47 | # Keystore files 48 | *.jks 49 | *.keystore 50 | 51 | # Google Services (e.g. APIs or Firebase) 52 | google-services.json 53 | agconnect-services.json 54 | 55 | # Android Profiling 56 | *.hprof 57 | 58 | #================== JetBrains.gitignore ================== 59 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 60 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 61 | 62 | # User-specific stuff 63 | .idea/**/workspace.xml 64 | .idea/**/tasks.xml 65 | .idea/**/usage.statistics.xml 66 | .idea/**/dictionaries 67 | .idea/**/shelf 68 | 69 | # AWS User-specific 70 | .idea/**/aws.xml 71 | 72 | # Generated files 73 | .idea/**/contentModel.xml 74 | 75 | # Sensitive or high-churn files 76 | .idea/**/dataSources/ 77 | .idea/**/dataSources.ids 78 | .idea/**/dataSources.local.xml 79 | .idea/**/sqlDataSources.xml 80 | .idea/**/dynamic.xml 81 | .idea/**/uiDesigner.xml 82 | .idea/**/dbnavigator.xml 83 | 84 | # Gradle 85 | .idea/**/gradle.xml 86 | .idea/**/libraries 87 | 88 | # Gradle and Maven with auto-import 89 | # When using Gradle or Maven with auto-import, you should exclude module files, 90 | # since they will be recreated, and may cause churn. Uncomment if using 91 | # auto-import. 92 | # .idea/artifacts 93 | # .idea/compiler.xml 94 | # .idea/jarRepositories.xml 95 | # .idea/modules.xml 96 | # .idea/*.iml 97 | # .idea/modules 98 | # *.iml 99 | # *.ipr 100 | 101 | # CMake 102 | cmake-build-*/ 103 | 104 | # Mongo Explorer plugin 105 | .idea/**/mongoSettings.xml 106 | 107 | # File-based project format 108 | *.iws 109 | 110 | # IntelliJ 111 | out/ 112 | 113 | # mpeltonen/sbt-idea plugin 114 | .idea_modules/ 115 | 116 | # JIRA plugin 117 | atlassian-ide-plugin.xml 118 | 119 | # Cursive Clojure plugin 120 | .idea/replstate.xml 121 | 122 | # SonarLint plugin 123 | .idea/sonarlint/ 124 | 125 | # Crashlytics plugin (for Android Studio and IntelliJ) 126 | com_crashlytics_export_strings.xml 127 | crashlytics.properties 128 | crashlytics-build.properties 129 | fabric.properties 130 | 131 | # Editor-based Rest Client 132 | .idea/httpRequests 133 | 134 | # Android studio 3.1+ serialized cache file 135 | .idea/caches/build_file_checksums.ser 136 | 137 | #================== macOS.gitignore ================== 138 | # General 139 | .DS_Store 140 | .AppleDouble 141 | .LSOverride 142 | 143 | # Icon must end with two \r 144 | Icon 145 | 146 | # Thumbnails 147 | ._* 148 | 149 | # Files that might appear in the root of a volume 150 | .DocumentRevisions-V100 151 | .fseventsd 152 | .Spotlight-V100 153 | .TemporaryItems 154 | .Trashes 155 | .VolumeIcon.icns 156 | .com.apple.timemachine.donotpresent 157 | 158 | # Directories potentially created on remote AFP share 159 | .AppleDB 160 | .AppleDesktop 161 | Network Trash Folder 162 | Temporary Items 163 | .apdisk 164 | 165 | #================== Linux.gitignore ================== 166 | *~ 167 | 168 | # temporary files which can be created if a process still has a handle open of a deleted file 169 | .fuse_hidden* 170 | 171 | # KDE directory preferences 172 | .directory 173 | 174 | # Linux trash folder which might appear on any partition or disk 175 | .Trash-* 176 | 177 | # .nfs files are created when an open file is removed but is still being accessed 178 | .nfs* 179 | 180 | #================== Windows.gitignore ================== 181 | # Windows thumbnail cache files 182 | Thumbs.db 183 | Thumbs.db:encryptable 184 | ehthumbs.db 185 | ehthumbs_vista.db 186 | 187 | # Dump file 188 | *.stackdump 189 | 190 | # Folder config file 191 | [Dd]esktop.ini 192 | 193 | # Recycle Bin used on file shares 194 | $RECYCLE.BIN/ 195 | 196 | # Windows Installer files 197 | *.cab 198 | *.msi 199 | *.msix 200 | *.msm 201 | *.msp 202 | 203 | # Windows shortcuts 204 | *.lnk 205 | 206 | #================== Vim.gitignore ================== 207 | # Swap 208 | [._]*.s[a-v][a-z] 209 | !*.svg # comment out if you don't need vector files 210 | [._]*.sw[a-p] 211 | [._]s[a-rt-v][a-z] 212 | [._]ss[a-gi-z] 213 | [._]sw[a-p] 214 | 215 | # Session 216 | Session.vim 217 | Sessionx.vim 218 | 219 | # Temporary 220 | .netrwhist 221 | *~ 222 | # Auto-generated tag files 223 | tags 224 | # Persistent undo 225 | [._]*.un~ 226 | 227 | #================== Vim.gitignore ================== 228 | .vscode/* 229 | !.vscode/settings.json 230 | !.vscode/tasks.json 231 | !.vscode/launch.json 232 | !.vscode/extensions.json 233 | !.vscode/*.code-snippets 234 | 235 | # Local History for Visual Studio Code 236 | .history/ 237 | 238 | # Built Visual Studio Code Extensions 239 | *.vsix -------------------------------------------------------------------------------- /app/src/main/java/template/ThumbnailImage.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.Context; 5 | import android.database.Cursor; 6 | import android.graphics.Bitmap; 7 | import android.graphics.BitmapFactory; 8 | import android.net.Uri; 9 | import android.os.AsyncTask; 10 | import android.provider.MediaStore; 11 | import android.util.Base64; 12 | import android.widget.ImageView; 13 | 14 | import androidx.fragment.app.Fragment; 15 | 16 | import java.io.ByteArrayOutputStream; 17 | import java.io.File; 18 | 19 | public class ThumbnailImage extends Fragment { 20 | 21 | private Context mContext; 22 | ContentResolver cr; 23 | private ImageView imageView; 24 | 25 | @Override 26 | public void onAttach(Context context) { 27 | super.onAttach(context); 28 | this.mContext = context; 29 | cr = mContext.getContentResolver(); 30 | imageView = null; 31 | } 32 | 33 | //测试获取缩略图 34 | public void test() { 35 | File file = new File(""); 36 | String path = file.getAbsolutePath(); 37 | //1、根据文件路径获取缩略图的id 38 | if (isPhoto(path)) { 39 | long id = getMediaId(cr, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, path); 40 | 41 | LoadThumbnailsAsyncTask ltat = new LoadThumbnailsAsyncTask(cr); 42 | ltat.execute(imageView, id, 1); 43 | } else if (isVideo(path)) { 44 | long id = getMediaId(cr, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, path); 45 | 46 | LoadThumbnailsAsyncTask ltat = new LoadThumbnailsAsyncTask(cr); 47 | ltat.execute(imageView, id, 2); 48 | } 49 | } 50 | 51 | private static final String WHERE = MediaStore.MediaColumns.DATA + "=?";//文件的绝对路径 52 | private static final String[] COLUMNS = new String[]{MediaStore.MediaColumns._ID};//图片id 53 | 54 | private static long getMediaId(ContentResolver cr, Uri content_uri, String path) { 55 | Cursor cursor = cr.query(content_uri, COLUMNS, WHERE, new String[]{path}, null); 56 | if (cursor.moveToFirst()) { 57 | long id = cursor.getLong(0); 58 | cursor.close(); 59 | return id; 60 | } 61 | 62 | return -1; 63 | } 64 | 65 | public boolean isPhoto(String path) { 66 | return path.endsWith(".png"); 67 | } 68 | 69 | public boolean isVideo(String path) { 70 | return path.endsWith(".mp4"); 71 | } 72 | 73 | //异步获取缩略图 74 | static class LoadThumbnailsAsyncTask extends AsyncTask { 75 | private ImageView imageView; 76 | ContentResolver cr; 77 | 78 | public LoadThumbnailsAsyncTask(ContentResolver cr) { 79 | this.cr = cr; 80 | } 81 | 82 | @Override 83 | protected Bitmap doInBackground(Object... params) { 84 | //这是在后台子线程中执行的 85 | imageView = (ImageView) params[0]; 86 | int id = (int) params[1]; 87 | int type = (int) params[2]; 88 | Bitmap bitmap = null; 89 | //2、根据缩略图id获取缩略图 90 | if (1 == type) { 91 | bitmap = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null); 92 | } else if (2 == type) { 93 | bitmap = MediaStore.Video.Thumbnails.getThumbnail(cr, id, MediaStore.Video.Thumbnails.MINI_KIND, null); 94 | } 95 | return bitmap; 96 | } 97 | 98 | @Override 99 | protected void onPostExecute(Bitmap bitmap) { 100 | super.onPostExecute(bitmap); 101 | //当任务执行完成是调用,在UI线程 102 | //取消后这里不会执行 103 | imageView.setImageBitmap(bitmap); 104 | imageView.setTag(null); 105 | imageView = null; 106 | } 107 | 108 | @Override 109 | protected void onCancelled() { 110 | super.onCancelled(); 111 | imageView = null; 112 | } 113 | 114 | @Override 115 | protected void onCancelled(Bitmap bitmap) { 116 | super.onCancelled(bitmap); 117 | imageView = null; 118 | } 119 | } 120 | 121 | //根据base64图片创建缩略图 122 | public static void createThumbImage(Context context, String base64) { 123 | byte[] decode = Base64.decode(base64.getBytes(), Base64.DEFAULT); 124 | //缩略图 125 | if (decode.length > 32 * 1024) { 126 | Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0, decode.length); 127 | int width = bmp.getWidth(); 128 | int height = bmp.getHeight(); 129 | Bitmap thumbBmp = null; 130 | int baseLength = 150; 131 | if (width > height) { 132 | thumbBmp = Bitmap.createScaledBitmap(bmp, baseLength, bmp.getHeight() / (bmp.getWidth() / baseLength), true); 133 | } else { 134 | thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.getWidth() / (bmp.getHeight() / baseLength), baseLength, true); 135 | } 136 | bmp.recycle(); 137 | 138 | //缩略图转成字节数组 139 | ByteArrayOutputStream output = new ByteArrayOutputStream(); 140 | thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, output); 141 | thumbBmp.recycle(); 142 | byte[] result = output.toByteArray(); 143 | try { 144 | output.close(); 145 | } catch (Exception e) { 146 | e.printStackTrace(); 147 | } 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /app/src/main/java/template/FloatDragBtnActivity.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.res.Resources; 5 | import android.graphics.Color; 6 | import android.os.Bundle; 7 | import android.util.Log; 8 | import android.view.MotionEvent; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.TextView; 12 | 13 | import androidx.appcompat.app.AppCompatActivity; 14 | 15 | import min.test.android_app_template.R; 16 | 17 | public class FloatDragBtnActivity extends AppCompatActivity { 18 | 19 | public static final String TAG = "FloatDragBtnActivity"; 20 | private static final int STILLNESS = 24; 21 | 22 | @SuppressLint("ClickableViewAccessibility, InflateParams") 23 | @Override 24 | protected void onCreate(Bundle savedInstanceState) { 25 | super.onCreate(savedInstanceState); 26 | 27 | //以下为全部悬浮拖动按钮内容,使用的是setOnTouchListener,而非继承类 28 | View textView = getLayoutInflater().inflate(R.layout.float_drag_btn, null); 29 | textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 30 | textView.setOnClickListener(v -> { 31 | Log.e(TAG, "onCreate: "); 32 | ((TextView)v).setTextColor(Color.GREEN); 33 | }); 34 | textView.setY(900); 35 | textView.setX(Resources.getSystem().getDisplayMetrics().widthPixels - 200); 36 | textView.setOnTouchListener(new View.OnTouchListener() { 37 | private int touchX = 0; 38 | private int touchY = 0; 39 | private int beginX = 0; 40 | private int beginY = 0; 41 | private int w = 0; 42 | private int h = 0; 43 | private int dx = 0; 44 | private int dy = 0; 45 | private int parentW = 0; 46 | private int parentH = 0; 47 | private int navigationBarH = 0; 48 | private int statusBarH = 0; 49 | 50 | @SuppressLint("InternalInsetResource") 51 | @Override 52 | public boolean onTouch(View v, MotionEvent event) { 53 | switch (event.getAction()) { 54 | case MotionEvent.ACTION_DOWN: 55 | Resources resources = v.getContext().getResources(); 56 | int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); 57 | navigationBarH = getResources().getDimensionPixelSize(resourceId); 58 | Log.e(TAG, "onTouch: navigation_bar_height " + navigationBarH); 59 | resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); 60 | statusBarH = getResources().getDimensionPixelSize(resourceId); 61 | Log.e(TAG, "onTouch: status_bar_height " + statusBarH); 62 | w = v.getWidth(); 63 | h = v.getHeight(); 64 | View view = (View) v.getParent(); 65 | parentW = view.getWidth(); 66 | parentH = view.getHeight(); 67 | v.setPressed(true); 68 | touchX = (int) v.getX(); 69 | touchY = (int) v.getY(); 70 | beginX = touchX; 71 | beginY = touchY; 72 | // 点击事件起始位置到原点的距离 73 | dx = (int) (event.getRawX() - beginX); 74 | dy = (int) (event.getRawY() - beginY); 75 | break; 76 | case MotionEvent.ACTION_MOVE: 77 | touchX = (int)event.getRawX();// x轴拖动的绝对距离 78 | touchY = (int)event.getRawY();// y轴拖动的绝对距离 79 | touchX -= dx; 80 | touchY -= dy; 81 | if (Math.abs(touchX - beginX) < STILLNESS && Math.abs(touchY - beginY) < STILLNESS) { 82 | break; 83 | } 84 | if (touchX < 0) { 85 | touchX = 0; 86 | } 87 | if (touchY < statusBarH) { 88 | touchY = statusBarH; 89 | } 90 | if (touchX + w > parentW) { 91 | touchX = parentW - w; 92 | } 93 | if (touchY + h > parentH - navigationBarH) { 94 | touchY = parentH - h - navigationBarH; 95 | } 96 | v.setX(touchX); 97 | v.setY(touchY); 98 | break; 99 | case MotionEvent.ACTION_UP: 100 | Log.e(TAG, "onTouch: ACTION_UP " + Math.abs(touchX - beginX) + ", " + Math.abs(touchY - beginY)); 101 | // 以下5行代码必须这个么写,先后顺序不能颠倒,否则无法触发 Click 事件 102 | if (Math.abs(touchX - beginX) < STILLNESS && Math.abs(touchY - beginY) < STILLNESS) { 103 | v.onTouchEvent(event); 104 | } 105 | v.setPressed(false); 106 | return true; 107 | default: break; 108 | } 109 | return false; 110 | } 111 | }); 112 | 113 | ((ViewGroup)(getWindow().getDecorView())).addView(textView); 114 | } 115 | } -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 14 | 15 | 16 | 32 | 33 | 47 | 48 | 55 | 56 | 59 | 63 | 64 | 87 | 88 | 99 | 100 | 105 | 106 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android_App_Template 2 | [国内链接gitee](https://gitee.com/maoxm/Android_App_Template) 3 | 安卓App工具类和模板代码,工具类一般可以直接使用,模板类主要用来参考,引入到自己的项目时可能会报错,请自行修改。 4 | 开发安卓前,请去了解 JetpackHilt,能使你的开发方便很多。 5 | 6 | ## [工具类,在“/app/src/main/java/utils/”目录下](/app/src/main/java/utils) 7 | 1. [获取全局Context的工具类,无须传入Context;get_context_no_dependence_anything/](/app/src/main/java/utils/get_context_no_dependence_anything) 8 | 2. [Utils工具;Utils.java](/app/src/main/java/utils/Utils.java) 9 | 包含:获取MIME类型、判断字符串是否为IP地址(模板)、分享到第三方(不用集成第三方SDK)、WiFi连接判断、获取其他语言的字符串、HarmonyOS判断、HarmonyOS系统版本号获取、判断activity是否正在显示 10 | 3. [AES加解密,字节数组与16进制字符串互转;aes/](/app/src/main/java/utils/encryption/aes)、[Android 加密工具](https://developer.android.google.cn/guide/topics/security/cryptography)、[Android 密钥库系统](https://developer.android.google.cn/training/articles/keystore) 11 | 4. [App启动icon不显示在 Launcher 上的方法:在启动 Activity 的 intent-filter 中加点料](/app/src/main/AndroidManifest.xml) 12 | 5. [获取视频文件的第一帧,远程或本地视频都可](/app/src/main/java/utils/Utils.java#L309) 13 | 6. [判断谷歌Play商店是否安装](/app/src/main/java/utils/Utils.java#L349) 14 | 15 | ## [模板,在“/app/src/main/java/template/”目录下](/app/src/main/java/template) 16 | 1. [RecyclerView分组的模板代码;recyclerview_group/](/app/src/main/java/template/recyclerview_group) 17 | 2. [自定义HUD指示器模板代码,改造AlertDialog,可以禁止用户交互和允许用户交互;ProgressHUD.java](/app/src/main/java/template/ProgressHUD.java) 18 | 3. [获取本地图片或视频的缩略图;ThumbnailImage.java](/app/src/main/java/template/ThumbnailImage.java) 19 | 4. [安卓8.0官方BottomNavigationView使用的问题;BottomNavigationFragment.java](/app/src/main/java/template/BottomNavigationFragment.java) 20 | 5. [Fragment的壳Activity,主要是想App就用这一个Activity就够了,其他的都用Fragment;fragment_activity/](/app/src/main/java/template/fragment_activity) 21 | 6. [使用系统的文件多选,文件夹(目录)选择器;FileMultipleSelectionFragment.java,已过时,最新方法请参考第32条](/app/src/main/java/template/FileMultipleSelectionFragment.java) 22 | 7. [自定义改造Toast;ToastUtils.java](/app/src/main/java/template/ToastUtils.java) 23 | 8. [Okhttp3上传或者下载文件的模板;OkHttp3UploadDownload.java](/app/src/main/java/template/OkHttp3UploadDownload.java) 24 | 9. [WebView常用设置,文件选择适配;WebViewActivity.java](/app/src/main/java/template/WebViewActivity.java) 25 | 10. [UDP模板;UDP.java](/app/src/main/java/template/UDP.java) 26 | 11. [给RecyclerView的Item添加上下文菜单(ContextMenu)和点击事件(onClick)模板,极简;RecyclerViewItem.java](/app/src/main/java/template/RecyclerViewItem.java) 27 | 12. [获取外置SD卡(TF卡)的绝对路径;SdcardFragment.java](/app/src/main/java/template/SdcardFragment.java) 28 | 13. [修改AlertDialog的主题;AlertDialogTheme.java](/app/src/main/java/template/AlertDialogTheme.java)、[R.style.AlertDialog](/app/src/main/res/values/styles.xml) 29 | 14. [仿iOS的弹出框,但API和AlertDialog.Builder一致;AlertDialogTheme.java#Builder](/app/src/main/java/template/AlertDialogTheme.java)、[R.style.AlertDialogTheme](/app/src/main/res/values/styles.xml) 30 | 15. [使用DownloadManager下载APK,并且安装;DownloadUtils.java](/app/src/main/java/template/DownloadUtils.java)、[FileProvider](/app/src/main/res/xml/share_dir.xml) 31 | 16. [BottomSheetDialog去掉背景,方便自定义圆角等;BottomSheetDialogTheme.java](/app/src/main/java/template/BottomSheetDialogTheme.java)、[R.style.BottomSheetBgNullTheme](/app/src/main/res/values/styles.xml) 32 | 17. [仿iOS导航箭头图标,用的矢量图(vector),去掉了系统创建vector的多余的空白;](/app/src/main/res/drawable)[R.drawable.v_back](/app/src/main/res/drawable/v_back.xml)、[R.drawable.v_next](/app/src/main/res/drawable/v_next.xml) 33 | 18. [单击时间间隔控制,使用的是聚合模式,而不是abstract类;SingleClickController.java](/app/src/main/java/template/SingleClickController.java) 34 | 19. [多击(谷歌工程师写的),使用的是聚合模式;MultipleClicksController.java](/app/src/main/java/template/MultipleClicksController.java) 35 | 20. [系统日历事件提醒增删和系统闹钟增删;CalendarAndAlarmClock.java](/app/src/main/java/template/CalendarAndAlarmClock.java) 36 | 21. [透明状态栏,App顶部栏与状态栏(StatusBar)颜色一体化,沉浸(jin)式状态栏;R.style.TranslucentBarTheme](/app/src/main/res/values/styles.xml)、[API>=30透明状态栏,及延长启动页(可当广告页)时间;TranslucentBarActivity.java](/app/src/main/java/template/TranslucentBarActivity.java) 37 | 22. [最简、最省存储的启动页设置;R.style.LauncherTheme](/app/src/main/res/values/styles.xml) 38 | 23. [获取WiFi列表,获取当前链接的WiFi名称,API>=29连接WiFi,扫描WiFi和蓝牙等外设的建议;WiFiActivity.java](/app/src/main/java/template/WiFiActivity.java) 39 | 24. [图片创建缩略图;ThumbnailImage.java#createThumbImage](/app/src/main/java/template/ThumbnailImage.java) 40 | 25. [文字转语音(TTS);UtilTemplates.java#speak](/app/src/main/java/template/UtilTemplates.java#L67) 41 | 26. [获取对应 density 下的原图;UtilTemplates.java#getNoScaledImage](/app/src/main/java/template/UtilTemplates.java#L105) 42 | 27. [获取剪切板的内容;UtilTemplates.java#getClipboardText](/app/src/main/java/template/UtilTemplates.java#L114) 43 | 28. [获取指定文件夹大小;UtilTemplates.java#getDirSize](/app/src/main/java/template/UtilTemplates.java#L138) 44 | 29. [获取存储可用空间大小;UtilTemplates.java#getAvailableSpace](/app/src/main/java/template/UtilTemplates.java#L163) 45 | 30. [各种自建证书加载;UtilTemplates.java#getSSLSocketFactory](/app/src/main/java/template/UtilTemplates.java#L248) 46 | 31. [自定义悬浮可拖动按钮;FloatDragBtnActivity.java](/app/src/main/java/template/FloatDragBtnActivity.java) 47 | 32. [安卓自带图片选择器的正确打开方式;ImagePickActivity.java](/app/src/main/java/template/ImagePickActivity.java) 48 | 33. [EditText输入限制;UtilTemplates.java#editTextLimiter](/app/src/main/java/template/UtilTemplates.java#L378) 49 | 34. [把本地 aar 文件发布到本地 maven 源,可以像远程 maven 库一样引入](/publishingTemp/build.gradle.kts) 50 | 35. [keystore文件的指纹计算方法](/app/src/main/java/template/FingerprintUtils.java) 51 | 36. [RxJava3使用](/app/src/main/java/template/RxJava3Templates.java) 52 | 37. [创建一种不在主线程工作的 Handler,子线程 Handler,非主线程 Handler](/app/src/main/java/template/UtilTemplates.java#L481) 53 | 38. [Java Optional类的用法](/app/src/main/java/template/UtilTemplates.java#L493) 54 | 39. [自定义弹框 PopupWindow ](/app/src/main/java/template/UtilTemplates.java#L537) 55 | 40. [TabLayout + ViewPager2 使用](/app/src/main/java/template/UtilTemplates.java#L551) 56 | 41. [圆环倒计时动画](/app/src/main/java/template/CircleProgressView.java) 57 | 58 | 59 | ## 长见识(自己去搜,去了解,去使用) 60 | 1. 并发:ReentrantLock CountDownLatch CyclicBarrier Phaser ReadWriteLock StampedLock Semaphore Exchanger LockSupport Condition 61 | 2. App内部角标 BadgeDrawable;MediaSession 框架 62 | 3. AndroidUtilCode 非常好的工具类,有些功能不知道怎么实现可以参考,Github上能搜到 63 | 4. WifiManager.WifiLock 的 WIFI_MODE_FULL_HIGH_PERF 模式可以防止WiFi在息屏时休眠 64 | 5. HTTP上传文件的断点续传协议可参考(苹果公司为其NSURLSession上传文件定制的):https://datatracker.ietf.org/doc/draft-ietf-httpbis-resumable-upload/ 65 | 6. Android 官方性能监控和检测,也介绍了要引入的库[https://developer.android.google.cn/topic/performance/inspecting-overview?hl=zh-cn](https://developer.android.google.cn/topic/performance/inspecting-overview?hl=zh-cn) 66 | 7. 自定义指定 JDK Home 路径可以在项目根目录的[gradle.properties](gradle.properties)中添加 org.gradle.java.home 参数 67 | 8. 第三方依赖下载加速,阿里云 Maven 仓库镜像介绍:[https://developer.aliyun.com/mvn/guide](https://developer.aliyun.com/mvn/guide)。 有些源没有及时同步国外的源,导致有些库文件还是会从国外源下载,所以多配几个国内源,降低这种概率,说不定总有一个源及时同步了。建议用 Android Studio 内的按钮去同步下载第三方库,不要用 gradlew build 等命令去同步下载第三方库,因为奇怪的JDK环境可能导致一些奇奇怪怪的问题导致同步失败。第一次同步最好打开 Android Studio 的 build 视图,查看 Download info,及时发现哪些库会最终使用国外源,可及时打开代理或者VPN等。 68 | 9. gradle 下载加速,腾讯云 gradle 下载地址,按需更新链接中的版本号即可:[https://mirrors.cloud.tencent.com/gradle/gradle-7.6.3-all.zip](https://mirrors.cloud.tencent.com/gradle/gradle-7.6.3-all.zip) 。必须使用"-all.zip"文件,否则项目同步还是会下载 gradle 的 src 依赖 -------------------------------------------------------------------------------- /app/src/main/java/template/ImagePickActivity.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.content.Intent; 4 | import android.net.Uri; 5 | import android.os.Bundle; 6 | import android.provider.MediaStore; 7 | 8 | import androidx.activity.result.ActivityResult; 9 | import androidx.activity.result.ActivityResultCallback; 10 | import androidx.activity.result.ActivityResultLauncher; 11 | import androidx.activity.result.PickVisualMediaRequest; 12 | import androidx.activity.result.contract.ActivityResultContracts; 13 | import androidx.appcompat.app.AppCompatActivity; 14 | 15 | import java.util.List; 16 | 17 | public class ImagePickActivity extends AppCompatActivity { 18 | 19 | // registerForActivityResult 可以在构造的时候调用 20 | private ActivityResultLauncher lip = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback() { 21 | @Override 22 | public void onActivityResult(Uri result) { 23 | // 这里拿到的是 文件的uri 24 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 25 | // getContentResolver().openInputStream(result); 26 | } 27 | }); 28 | 29 | // 把文件写到沙盒之外时用的路径选择器,选择器中还可以编辑指定文件名。调用方法:fileExporter.launch("默认的文件名.json") 30 | final ActivityResultLauncher fileExporter = registerForActivityResult( 31 | new ActivityResultContracts.CreateDocument("application/json"), uri -> { 32 | if (uri != null) { // 返回文件完整路径 33 | } 34 | }); 35 | 36 | @Override 37 | protected void onCreate(Bundle savedInstanceState) { 38 | super.onCreate(savedInstanceState); 39 | 40 | // 方式1,这种直接打开的文件选择器,但是经过了 "image/*" 过滤: 41 | ActivityResultLauncher imagePickLauncher1 = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback() { 42 | @Override 43 | public void onActivityResult(Uri result) { 44 | // 这里拿到的是 文件的uri 45 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 46 | // getContentResolver().openInputStream(result); 47 | } 48 | }); 49 | // 使用 50 | imagePickLauncher1.launch("image/*"); 51 | 52 | // 方式2,这种方式会有图片选择器或文件选择器两种方式弹窗提供选择: 53 | ActivityResultLauncher imagePickLauncher2 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback() { 54 | @Override 55 | public void onActivityResult(ActivityResult result) { 56 | if (null == result || result.getResultCode() != RESULT_OK || result.getData() == null || result.getData().getData() == null) return; 57 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 58 | // getContentResolver().openInputStream(result.getData().getData()); 59 | } 60 | }); 61 | // 使用 62 | imagePickLauncher2.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)); 63 | // 这个应该是拍照,还有一些别的参数要设置,另外研究吧 64 | // imagePickLauncher2.launch(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)); 65 | 66 | /* 67 | 方式3:必须是API 33 (安卓13),才能使用 68 | https://developer.android.google.cn/about/versions/13/features/photopicker?hl=zh-cn 69 | */ 70 | ActivityResultLauncher imagePickLauncher3 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { 71 | if (null == result || result.getResultCode() != RESULT_OK || result.getData() == null || result.getData().getData() == null) return; 72 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 73 | // getContentResolver().openInputStream(result.getData().getData()); 74 | }); 75 | // 使用 76 | Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES); 77 | // 默认图片视频都可选,这里可以自己过滤 78 | intent.setType("image/*"); 79 | // intent.setType("video/*"); 80 | imagePickLauncher3.launch(intent); 81 | 82 | /* 83 | 方式4: 84 | 搭载 Android 11(API 级别 30)或更高版本 1.7.0 版或更高版本的 androidx.activity 库 85 | https://developer.android.google.cn/training/data-storage/shared/photopicker?hl=zh-cn 86 | def activity_version = "1.7.0" 87 | // Java language implementation 88 | implementation "androidx.activity:activity:$activity_version" 89 | // Kotlin 90 | implementation "androidx.activity:activity-ktx:$activity_version" 91 | */ 92 | // 选择单个媒体文件 93 | ActivityResultLauncher imagePickLauncher4 = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), new ActivityResultCallback() { 94 | @Override 95 | public void onActivityResult(Uri result) { 96 | // 这里拿到的是 图片的uri 97 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 98 | // getContentResolver().openInputStream(result); 99 | // 默认情况下,系统会授予应用对媒体文件的访问权限,直到设备重启或应用停止运行。如果您的应用执行长时间运行的工作(例如在后台上传大型文件),您可能需要将此访问权限保留更长时间。为此,请调用 100 | getContentResolver().takePersistableUriPermission(result, Intent.FLAG_GRANT_READ_URI_PERMISSION); 101 | } 102 | }); 103 | // 使用 104 | // 只视频 105 | // new PickVisualMediaRequest.Builder().setMediaType(ActivityResultContracts.PickVisualMedia.VideoOnly.INSTANCE).build(); 106 | // 默认是图片和视频都包含 107 | imagePickLauncher4.launch(new PickVisualMediaRequest.Builder().build()); 108 | 109 | // 选择多个媒体项,maxItems为最大可选数量。最大数量查询 MediaStore.getPickImagesMaxLimit() 110 | ActivityResultLauncher imagePickLauncher6 = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(9), new ActivityResultCallback>() { 111 | @Override 112 | public void onActivityResult(List result) { 113 | // 这里拿到的是 图片的uri 114 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 115 | // getContentResolver().openInputStream(result); 116 | } 117 | }); 118 | // 使用 119 | imagePickLauncher6.launch(new PickVisualMediaRequest.Builder().build()); 120 | 121 | // 方式5: 此方式可以指定多个文件类型 122 | ActivityResultLauncher imagePickLauncher5 = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback() { 123 | @Override 124 | public void onActivityResult(Uri result) { 125 | // 这里拿到的是 文件的uri 126 | // 这种方式读取数据是不需要 Manifest.permission.READ_EXTERNAL_STORAGE 权限 127 | // getContentResolver().openInputStream(result); 128 | } 129 | }); 130 | // 使用 131 | imagePickLauncher5.launch(new String[]{"image/*", "video/*", ""}); 132 | 133 | // 方式6: 选择多个文件 134 | ActivityResultLauncher imagePickLauncher7 = registerForActivityResult(new ActivityResultContracts.OpenMultipleDocuments(), new ActivityResultCallback>() { 135 | @Override 136 | public void onActivityResult(List list) { 137 | } 138 | }); 139 | // 使用 140 | imagePickLauncher7.launch(new String[]{"image/*", "video/*", ""}); 141 | 142 | // 还有很多好用的可以自己去发觉 143 | } 144 | } -------------------------------------------------------------------------------- /app/src/main/java/template/TranslucentBarActivity.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.animation.Animator; 4 | import android.animation.AnimatorListenerAdapter; 5 | import android.animation.ObjectAnimator; 6 | import android.os.Build; 7 | import android.os.Bundle; 8 | import android.os.Handler; 9 | import android.os.Looper; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.view.Window; 13 | import android.widget.ImageView; 14 | 15 | import androidx.appcompat.app.AppCompatActivity; 16 | import androidx.core.graphics.Insets; 17 | import androidx.core.view.ViewCompat; 18 | import androidx.core.view.WindowCompat; 19 | import androidx.core.view.WindowInsetsCompat; 20 | 21 | import min.test.android_app_template.R; 22 | 23 | public class TranslucentBarActivity extends AppCompatActivity { 24 | 25 | //R.style.LauncherTheme、R.style.TranslucentBarTheme 这两个里面的介绍很重要 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 30 | Window window = getWindow(); 31 | // 这个会把底部的导航栏的背面也用上,官方注释说可以与WindowInsets.Type.statusBars()等配合,但是没测试出来效果 32 | // window.setDecorFitsSystemWindows(false); 33 | WindowCompat.setDecorFitsSystemWindows(window, false); 34 | // 高亮显示状态栏,字体黑色 35 | // ViewCompat.getWindowInsetsController(window.getDecorView()).setAppearanceLightStatusBars(true); 36 | // 抬高底部方式一: 37 | ViewCompat.setOnApplyWindowInsetsListener(window.getDecorView().findViewById(android.R.id.content), (v, insets) -> { 38 | // displayCutout 是刘海区域 39 | Insets systemInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars() | WindowInsetsCompat.Type.displayCutout()); 40 | v.setPadding(0, 0, 0, systemInsets.bottom); 41 | // 将内容限制在安全区域内,window.getDecorView().findViewById(android.R.id.content) 可能要换成其子视图 42 | // v.setPadding(systemInsets.left, systemInsets.top, systemInsets.right, systemInsets.bottom); 43 | return insets; 44 | }); 45 | // // 高亮显示状态栏,字体黑色 46 | // window.getDecorView().getWindowInsetsController().setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS); 47 | // // 抬高底部方式二: 48 | // // 貌似这样也能获取导航栏高度。Activity的初始创建显示线程内getInsets得到为null,可以放到runOnUiThread()中 49 | // ViewCompat.getRootWindowInsets(window.getDecorView().findViewById(android.R.id.content)).getInsets(WindowInsetsCompat.Type.navigationBars()).bottom; 50 | // // 获取导航栏高度 51 | // int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); 52 | // if (0 != resourceId) { 53 | // int navigation_bar_height = getResources().getDimensionPixelSize(resourceId); 54 | // LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) window.getDecorView().findViewById(android.R.id.content).getLayoutParams(); 55 | // // 防止底部被导航栏遮住 56 | // layoutParams.bottomMargin = navigation_bar_height; 57 | //// window.getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, navigation_bar_height); 58 | // } 59 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 60 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); 61 | } 62 | } 63 | 64 | private Handler handler; 65 | private View splashView; 66 | /** 67 | * 可当广告页 68 | * 在最上层view中加入一个和启动页一样的页面,假装延长启动页的显示时间,等资源加载完成后移除假的启动页: 69 | * 在主题中 有两种设置启动页的方式,选其一: 70 | * android:windowBackground 只能设置 图片资源 或 layer-list等图层的资源文件 71 | * android:windowSplashscreenContent (安卓8.0以上) 能设置 图片资源 或 layer-list等图层资源文件 或 layout 72 | */ 73 | private void initSplash() { 74 | /** 75 | * 使用layout去匹配启动页,layout中的imageview的 底部margin 和 layer-list的图片item bottom的值一样 76 | * 当 android:windowSplashscreenContent 设置的是layout 时,layout加入 android.R.id.content 的view 或 DecorView中 77 | * 都一样,人眼看不出切换差异 78 | * 当 android:windowSplashscreenContent 设置的是layer-list等图层 或图片 时,layout加入 android.R.id.content 的view 或 79 | * DecorView 都会有底部导航栏的高度的切换差异感,下面会有去掉差异的方法 80 | * 当使用 android:windowBackground 做启动页时,layout加入 DecorView 无切换差异感,而加入 android.R.id.content 的view, 81 | * 有差异感 82 | */ 83 | /*ViewGroup vg = (ViewGroup) getLayoutInflater().inflate(R.layout.launch_splash, null); 84 | splashView = vg; 85 | ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).addView(vg); 86 | // ((ViewGroup) getWindow().getDecorView()).addView(vg); 87 | //去掉差异感 88 | int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); 89 | if (resourceId != 0) { 90 | View iv = vg.getChildAt(0); 91 | RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) iv.getLayoutParams(); 92 | lp.bottomMargin -= getResources().getDimensionPixelSize(resourceId);//+或-,请根据测试调,测试多次,否则可能有上次的缓存导致调试不准确 93 | }*/ 94 | 95 | /** 96 | * android:windowBackground 和 android:windowSplashscreenContent 对图片的拉伸效果不一样 97 | * 当使用 android:windowBackground 作为启动页时,此ImageView适合添加到DecorView中,人眼看不出切换差异,适合全屏大图。 98 | * 但使用 android:windowSplashscreenContent 做启动页时,不要加入到DecorView,会有一个底部导航栏的差异, 99 | * 可以加入到 android.R.id.content 的view中,不会有底部导航栏的差异,人眼看不出切换差异,适合非全屏的小图 100 | * android:windowSplashscreenContent 与 android:windowBackground 不能同时存在,否则 以 android:windowSplashscreenContent 101 | * 为主 102 | */ 103 | ImageView iv = new ImageView(this); 104 | ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); 105 | iv.setLayoutParams(layoutParams); 106 | iv.setScaleType(ImageView.ScaleType.FIT_XY); 107 | splashView = iv; 108 | iv.setImageResource(R.drawable.launcher_splash); 109 | ((ViewGroup) getWindow().getDecorView()).addView(iv); 110 | // ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).addView(iv); 111 | handler = new Handler(Looper.getMainLooper()); 112 | handler.postDelayed(this::hideSplashView, 5000); 113 | } 114 | 115 | private AnimatorListenerAdapter animatorAdapter; 116 | //动画隐藏启动页 117 | private synchronized void hideSplashView() { 118 | if (splashView == null || null != animatorAdapter) return; 119 | animatorAdapter = new AnimatorListenerAdapter() { 120 | @Override 121 | public void onAnimationEnd(Animator animation) { 122 | super.onAnimationEnd(animation); 123 | ((ViewGroup)splashView.getParent()).removeView(splashView); 124 | splashView = null; 125 | animatorAdapter = null; 126 | } 127 | }; 128 | ObjectAnimator animator = ObjectAnimator.ofFloat(splashView, "alpha", 1f, 0f); 129 | animator.setDuration(300);//时间 130 | animator.addListener(animatorAdapter); 131 | animator.start(); 132 | // getWindow().getDecorView().setBackground(null); 133 | // getWindow().setBackgroundDrawable(null); 134 | } 135 | } -------------------------------------------------------------------------------- /app/src/main/java/template/DownloadUtils.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.app.DownloadManager; 5 | import android.content.BroadcastReceiver; 6 | import android.content.ContentUris; 7 | import android.content.ContentValues; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.content.IntentFilter; 11 | import android.database.Cursor; 12 | import android.net.Uri; 13 | import android.os.Build; 14 | import android.os.Environment; 15 | 16 | import androidx.core.content.FileProvider; 17 | 18 | import java.io.File; 19 | 20 | public class DownloadUtils { 21 | //下载器 22 | private DownloadManager dm; 23 | private Context mContext; 24 | //下载任务ID 25 | private long downloadId; 26 | private String mUrl; 27 | private File file; 28 | 29 | public static DownloadUtils du; 30 | 31 | public DownloadUtils(Context context, String url) { 32 | mContext = context; 33 | mUrl = url; 34 | } 35 | 36 | public static void downloadAPK(Context context, String url) { 37 | du = new DownloadUtils(context, url); 38 | du.downloadAPK(); 39 | } 40 | 41 | //下载apk 42 | private void downloadAPK() { 43 | //创建下载请求 44 | DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mUrl)); 45 | //移动网络情况下是否允许漫游 46 | request.setAllowedOverRoaming(false); 47 | //在通知栏中显示,默认就是显示的 48 | request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); 49 | //隐藏通知栏 manifest必须配置权限:android.permission.DOWNLOAD_WITHOUT_NOTIFICATION; 50 | // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); 51 | request.setTitle("正在下载最新APK"); 52 | request.setDescription("my.apk"); 53 | request.setVisibleInDownloadsUi(true); 54 | 55 | //设置下载的路径 56 | file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), 57 | "my.apk"); 58 | if (file.exists()) file.delete(); 59 | //设置文件存放路径,路径必须是Context.getExternalFilesDir()目录下的,或Environment.getExternalStoragePublicDirectory()目录下的,否则不支持;还可能需要有Manifest.permission.WRITE_EXTERNAL_STORAGE,具体请看注释。 60 | request.setDestinationUri(Uri.fromFile(file));//Context.getExternalFilesDir(null),API29以上此目录下不需要读写权限 61 | //获取DownloadManager 62 | if (dm == null) 63 | dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); 64 | if (dm != null) { 65 | //将请求加入队列,加入后会给该任务返回id,通过该id可以取消任务、重启任务、获取下载的文件等等 66 | downloadId = dm.enqueue(request); 67 | } 68 | 69 | //注册广播接收者,监听下载状态 70 | mContext.registerReceiver(receiver, 71 | new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 72 | } 73 | 74 | //广播监听下载的各个状态 75 | private BroadcastReceiver receiver = new BroadcastReceiver() { 76 | @Override 77 | public void onReceive(Context context, Intent intent) { 78 | checkStatus(); 79 | long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 80 | } 81 | }; 82 | 83 | //检查下载状态 84 | private void checkStatus() { 85 | switch (getStatus()) { 86 | case DownloadManager.STATUS_PAUSED://下载暂停 87 | break; 88 | 89 | case DownloadManager.STATUS_PENDING://下载延迟 90 | break; 91 | 92 | case DownloadManager.STATUS_RUNNING://正在下载 93 | break; 94 | 95 | case DownloadManager.STATUS_SUCCESSFUL://下载完成 96 | du = null; 97 | mContext.unregisterReceiver(receiver); 98 | installAPK();//下载完成安装APK 99 | break; 100 | 101 | case DownloadManager.STATUS_FAILED://下载失败 102 | du = null; 103 | mContext.unregisterReceiver(receiver); 104 | break; 105 | } 106 | } 107 | 108 | @SuppressLint("Range") 109 | public int getStatus() { 110 | int status = 0; 111 | DownloadManager.Query query = new DownloadManager.Query(); 112 | //通过id查找 113 | query.setFilterById(downloadId); 114 | Cursor cursor = dm.query(query); 115 | if (cursor.moveToFirst()) { 116 | status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); 117 | } 118 | cursor.close(); 119 | return status; 120 | } 121 | 122 | private void installAPK() { 123 | Intent intent = new Intent(Intent.ACTION_VIEW); 124 | // 由于没有在Activity环境下启动Activity,设置下面的标签 125 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 126 | //Android7.0(24)以上要使用FileProvider 127 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 128 | //"test.mxm.FileProvider"在AndroidManifest.xml注册 129 | Uri apkUri = FileProvider.getUriForFile(mContext, "test.mxm.FileProvider", file); 130 | //添加这一句表示对目标应用临时授权该Uri所代表的文件 131 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 132 | intent.setDataAndType(apkUri, "application/vnd.android.package-archive"); 133 | } else { 134 | intent.setDataAndType(Uri.fromFile(file), 135 | "application/vnd.android.package-archive"); 136 | } 137 | mContext.startActivity(intent); 138 | } 139 | 140 | /*private final String TAG = "DownloadUtils"; 141 | //修改文件权限 142 | private void setPermission(String absolutePath) { 143 | String command = "chmod " + "777" + " " + absolutePath; 144 | Runtime runtime = Runtime.getRuntime(); 145 | try { 146 | runtime.exec(command); 147 | } catch (IOException e) { 148 | Log.e(TAG, "setPermission: ", e); 149 | } 150 | }*/ 151 | 152 | // 这个几个常量值在AOSP能找到 https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/provider/Downloads.java 153 | private static final String CONTENT_URI = "content://downloads/my_downloads"; 154 | private static final int CONTROL_RUN = 0; 155 | private static final int CONTROL_PAUSED = 1; 156 | private static boolean resumeDownload(Context context, long id) { 157 | return controlDownload(context, id, CONTROL_RUN); 158 | } 159 | 160 | private static boolean pauseDownload(Context context, long id) { 161 | return controlDownload(context, id, CONTROL_PAUSED); 162 | } 163 | 164 | private static boolean controlDownload(Context context, long id, int control) { 165 | int updatedRows = 0; 166 | ContentValues controls = new ContentValues(); 167 | // 以下写法可参考 DownloadManager.forceDownload() 方法 和 https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/provider/Downloads.java 168 | controls.put("control", control); // Resume Control Value 169 | // controls.put(DownloadManager.COLUMN_STATUS, 190); // 190: STATUS_PENDING 170 | try { 171 | updatedRows = context.getContentResolver().update( 172 | // Uri.parse(CONTENT_URI), 173 | // controls, 174 | // DownloadManager.COLUMN_ID + "=?", 175 | // new String[]{ String.valueOf(id) } 176 | ContentUris.withAppendedId(Uri.parse(CONTENT_URI), id), 177 | controls, null, null 178 | ); 179 | } catch (Exception ignored) {} 180 | 181 | return updatedRows > 0; 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /app/src/main/java/template/recyclerview_group/SectionItemDecoration.java: -------------------------------------------------------------------------------- 1 | package template.recyclerview_group; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Color; 6 | import android.graphics.Paint; 7 | import android.graphics.Rect; 8 | import android.util.TypedValue; 9 | import android.view.View; 10 | 11 | import androidx.recyclerview.widget.LinearLayoutManager; 12 | import androidx.recyclerview.widget.RecyclerView; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | /** 18 | * 有分类title的 ItemDecoration 19 | */ 20 | public class SectionItemDecoration extends RecyclerView.ItemDecoration { 21 | public String titles[]; 22 | public int titlePositions[];//不包含titles[0]的位置 23 | public boolean titleDocksAtTheTop = false;//是否停靠在顶部 24 | private Paint mPaint; 25 | private Rect mBounds;//用于存放测量文字Rect 26 | 27 | private int mTitleBgHeight;//title的高 28 | private int seperatorHeight = 1;//分割线的高度 29 | private static int COLOR_TITLE_BG = Color.parseColor("#FFDFDFDF"); 30 | private static int COLOR_TITLE_FONT = Color.parseColor("#FF000000"); 31 | private static int mTitleFontSize;//title字体大小 32 | 33 | 34 | public SectionItemDecoration(Context context) { 35 | super(); 36 | mPaint = new Paint(); 37 | mBounds = new Rect(); 38 | mTitleBgHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, context.getResources().getDisplayMetrics()); 39 | mTitleFontSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, context.getResources().getDisplayMetrics()); 40 | mPaint.setTextSize(mTitleFontSize); 41 | mPaint.setAntiAlias(true); 42 | } 43 | 44 | @Override 45 | public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 46 | super.onDraw(c, parent, state); 47 | 48 | final int left = parent.getPaddingLeft(); 49 | final int right = parent.getRight() - parent.getPaddingRight(); 50 | // 获取当前屏幕可见 item 数量,而不是 RecyclerView 所有的 item 数量 51 | final int childCount = parent.getChildCount(); 52 | 53 | View child; 54 | RecyclerView.LayoutParams params; 55 | int position; 56 | int bottom; 57 | // parent.getChildViewHolder() 58 | for (int i = titleDocksAtTheTop? 1 : 0; i < childCount; i++) {//有悬浮标题时,第0个item不用绘制 59 | child = parent.getChildAt(i); 60 | params = (RecyclerView.LayoutParams) child.getLayoutParams(); 61 | position = params.getViewLayoutPosition(); 62 | // position = params.getViewAdapterPosition(); 63 | bottom = child.getTop() - params.topMargin; 64 | 65 | if (0 == position || (position = titleIndexAt(position)) > 0) { 66 | drawTitleArea(c, left, bottom - mTitleBgHeight, right, bottom, titles[position]); 67 | } else if (i > 0) {//画分割线,第0个不用绘制 68 | mPaint.setColor(COLOR_TITLE_BG); 69 | c.drawRect(left, bottom - seperatorHeight, right, bottom, mPaint); 70 | } 71 | } 72 | } 73 | 74 | /** 75 | * 绘制Title区域背景和文字的方法 76 | */ 77 | private void drawTitleArea(Canvas c, int bgLeft, int bgTop, int bgRight, int bgBottom, String title) {//最先调用,绘制在最下层 78 | //绘制背景 79 | mPaint.setColor(COLOR_TITLE_BG); 80 | c.drawRect(bgLeft, bgTop, bgRight, bgBottom, mPaint); 81 | //绘制文字 82 | mPaint.setColor(COLOR_TITLE_FONT); 83 | mPaint.getTextBounds(title, 0, title.length(), mBounds); 84 | 85 | c.drawText(title, bgLeft, 86 | bgBottom - (mTitleBgHeight/2 - mBounds.height()/2),//y是baseline的位置,这里用文字的底部粗略当baseline 87 | mPaint); 88 | // Paint.FontMetrics fontMetrics = mPaint.getFontMetrics(); 89 | // float distance = (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom; 90 | // float baseline = (bgTop + bgBottom)/2 + distance;//基准线 91 | /* 92 | * 对于大部分中文英文,distance用top和bottom计算,有偏差,字体被偏下了一点点, 93 | * 应该用ascent和descent计算, 94 | * 部分国家的特殊字符的上下高度会超过descent,ascent,用top和bottom计算 95 | */ 96 | } 97 | 98 | @Override 99 | public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {//最后调用 绘制在最上层 100 | super.onDrawOver(c, parent, state); 101 | if (!titleDocksAtTheTop) return;//不用停靠在顶部 102 | 103 | final int position = ((LinearLayoutManager) parent.getLayoutManager()).findFirstVisibleItemPosition(); 104 | if (RecyclerView.NO_POSITION == position) {// 越界检查 105 | return; 106 | } 107 | 108 | String title = null; 109 | if (0 == position || null == titlePositions || position < titlePositions[0]) { 110 | title = titles[0]; 111 | } else if (null != titlePositions) { 112 | for (int i = titlePositions.length - 1; i > -1; --i) { 113 | if (position >= titlePositions[i]) {//只要在此范围内,就有标题 114 | title = titles[i + 1]; 115 | break; 116 | } 117 | } 118 | } 119 | if (null == title) { 120 | return; 121 | } 122 | 123 | //第一个可见条目的位置 124 | // View child = manager.findViewByPosition(position); 125 | final View child = parent.getChildAt(0);//获取可见的最上面的一个;这种方式获取会不会有问题 126 | //最上面的item底部的高度<=标题背景的高度,且下一个item含有标题 127 | if (child.getBottom() <= mTitleBgHeight && titleIndexAt(position + 1) > 0) { 128 | c.translate(0, child.getBottom() - mTitleBgHeight);//上移 129 | } 130 | 131 | final int top = parent.getPaddingTop(); 132 | drawTitleArea(c, parent.getPaddingLeft(), top, 133 | parent.getRight() - parent.getPaddingRight(), 134 | top + mTitleBgHeight, title); 135 | } 136 | 137 | @Override 138 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { 139 | super.getItemOffsets(outRect, view, parent, state); 140 | // int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); 141 | // int position = parent.getLayoutManager().getPosition(view); 142 | int position = parent.getChildAdapterPosition(view); 143 | if (0 == position || titleIndexAt(position) > 0) { 144 | outRect.top = mTitleBgHeight; 145 | } else { 146 | outRect.top = seperatorHeight; 147 | } 148 | } 149 | 150 | private int titleIndexAt(int position) { 151 | if (null == titlePositions) return 0; 152 | for (int i = 0; i < titlePositions.length; ++i) { 153 | if (position == titlePositions[i]) { 154 | return i+1; 155 | } 156 | } 157 | return 0; 158 | } 159 | 160 | public static void setGroup(SectionItemDecoration decoration, SectionRVAdapter adapter, List titles, ArrayList> group) { 161 | int sections = group.size(); 162 | if (sections == 0) { 163 | decoration.titlePositions = null; 164 | decoration.titles = null; 165 | adapter.count = 0; 166 | adapter.sectionFirstItemPosition = null; 167 | return; 168 | } 169 | decoration.titles = titles.toArray(new String[titles.size()]); 170 | 171 | int count = group.get(0).size(); 172 | if (sections > 1) {//有多个分组 173 | //计算从第二组开始的,每组第一项的位置 174 | int[] sectionFirstItemPosition = new int[sections - 1]; 175 | for (int i = 1; i < sections; i++) { 176 | sectionFirstItemPosition[i-1] = count; 177 | count += group.get(i).size(); 178 | } 179 | decoration.titlePositions = sectionFirstItemPosition; 180 | adapter.sectionFirstItemPosition = sectionFirstItemPosition; 181 | } else { 182 | decoration.titlePositions = null; 183 | adapter.sectionFirstItemPosition = null; 184 | } 185 | adapter.count = count; 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /app/src/main/java/template/FileMultipleSelectionFragment.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | 4 | import android.app.Fragment; 5 | import android.content.ClipData; 6 | import android.content.ContentResolver; 7 | import android.content.ContentUris; 8 | import android.content.Context; 9 | import android.content.Intent; 10 | import android.database.Cursor; 11 | import android.net.Uri; 12 | import android.os.Build; 13 | import android.os.Bundle; 14 | import android.os.Environment; 15 | import android.provider.DocumentsContract; 16 | import android.provider.MediaStore; 17 | import android.util.Log; 18 | import android.view.LayoutInflater; 19 | import android.view.View; 20 | import android.view.ViewGroup; 21 | 22 | import androidx.annotation.RequiresApi; 23 | 24 | import static android.app.Activity.RESULT_OK; 25 | 26 | 27 | public class FileMultipleSelectionFragment extends Fragment { 28 | 29 | Context context; 30 | 31 | public FileMultipleSelectionFragment() { 32 | } 33 | 34 | @Override 35 | public void onAttach(Context context) { 36 | super.onAttach(context); 37 | this.context = context; 38 | } 39 | 40 | @Override 41 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 42 | Bundle savedInstanceState) { 43 | View view = inflater.inflate(android.R.layout.simple_list_item_1, container, false); 44 | 45 | return view; 46 | } 47 | 48 | 49 | @Override 50 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 51 | super.onActivityResult(requestCode, resultCode, data); 52 | 53 | if (requestCode != FILE_SELECT || RESULT_OK != resultCode || null == data) return;//调用系统的文件选择器 54 | ContentResolver cr = getActivity().getContentResolver(); 55 | ClipData clipData = data.getClipData(); 56 | if (null != clipData) {//多选 57 | for (int i = 0; i < clipData.getItemCount(); i++) { 58 | Uri uri = clipData.getItemAt(i).getUri(); 59 | Log.i("---getClipData", "onActivityResult: " + uri.getPath()); 60 | Log.i("---getClipData", "onActivityResult: " + uri.toString()); 61 | // Log.i("---getClipData", "onActivityResult: " + getRealFilePath(cr, uri)); 62 | } 63 | } else { 64 | Uri uri = data.getData();//单选 65 | // Log.i("---getData", "onActivityResult: " + getRealFilePath(cr, data.getData())); 66 | Log.i("---getData", "onActivityResult: " + uri.toString()); 67 | } 68 | } 69 | 70 | private static final int FILE_SELECT = 1; 71 | private void showFileChooser() {//使用系统文件选择器 72 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 73 | intent.setType("*/*"); 74 | intent.addCategory(Intent.CATEGORY_OPENABLE); 75 | intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//允许多选 76 | try { 77 | //虽然设置了允许多选,但有些文件管理器不支持多选 78 | startActivityForResult(Intent.createChooser(intent, "请选择文件"), FILE_SELECT); 79 | } catch (android.content.ActivityNotFoundException ex) { 80 | // Potentially direct the user to the Market with a Dialog 81 | // Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show(); 82 | } 83 | 84 | //这个是文件夹选择器: https://github.com/googlesamples/android-DirectorySelection 85 | // Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); 86 | // startActivityForResult(intent, 1); 87 | 88 | } 89 | } 90 | 91 | /** 92 | * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使 93 | */ 94 | class ConvertUriToFilePath { 95 | /** 96 | * Get a file path from a Uri. This will get the the path for Storage Access 97 | * Framework Documents, as well as the _data field for the MediaStore and 98 | * other file-based ContentProviders. 99 | * 100 | * @param context The context. 101 | * @param uri The Uri to query. 102 | */ 103 | @RequiresApi(api = Build.VERSION_CODES.KITKAT) 104 | public static String getPathFromURI(final Context context, final Uri uri) { 105 | 106 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 107 | 108 | // DocumentProvider 109 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 110 | // ExternalStorageProvider 111 | if (isExternalStorageDocument(uri)) { 112 | final String docId = DocumentsContract.getDocumentId(uri); 113 | final String[] split = docId.split(":"); 114 | final String type = split[0]; 115 | 116 | if ("primary".equalsIgnoreCase(type)) { 117 | return Environment.getExternalStorageDirectory() + "/" + split[1]; 118 | } 119 | } 120 | // DownloadsProvider 121 | else if (isDownloadsDocument(uri)) { 122 | 123 | final String id = DocumentsContract.getDocumentId(uri); 124 | final Uri contentUri = ContentUris.withAppendedId( 125 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 126 | 127 | return getDataColumn(context, contentUri, null, null); 128 | } 129 | // MediaProvider 130 | else if (isMediaDocument(uri)) { 131 | final String docId = DocumentsContract.getDocumentId(uri); 132 | final String[] split = docId.split(":"); 133 | final String type = split[0]; 134 | 135 | Uri contentUri = null; 136 | if ("image".equals(type)) { 137 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 138 | } else if ("video".equals(type)) { 139 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 140 | } else if ("audio".equals(type)) { 141 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 142 | } 143 | 144 | final String selection = "_id=?"; 145 | final String[] selectionArgs = new String[]{ 146 | split[1] 147 | }; 148 | 149 | return getDataColumn(context, contentUri, selection, selectionArgs); 150 | } 151 | } 152 | // MediaStore (and general) 153 | else if ("content".equalsIgnoreCase(uri.getScheme())) { 154 | return getDataColumn(context, uri, null, null); 155 | } 156 | // File 157 | else if ("file".equalsIgnoreCase(uri.getScheme())) { 158 | return uri.getPath(); 159 | } 160 | 161 | return null; 162 | } 163 | 164 | /** 165 | * Get the value of the data column for this Uri. This is useful for 166 | * MediaStore Uris, and other file-based ContentProviders. 167 | * 168 | * @param context The context. 169 | * @param uri The Uri to query. 170 | * @param selection (Optional) Filter used in the query. 171 | * @param selectionArgs (Optional) Selection arguments used in the query. 172 | * @return The value of the _data column, which is typically a file path. 173 | */ 174 | public static String getDataColumn(Context context, Uri uri, String selection, 175 | String[] selectionArgs) { 176 | 177 | Cursor cursor = null; 178 | final String column = "_data"; 179 | final String[] projection = { 180 | column 181 | }; 182 | 183 | try { 184 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, 185 | null); 186 | if (cursor != null && cursor.moveToFirst()) { 187 | final int column_index = cursor.getColumnIndexOrThrow(column); 188 | return cursor.getString(column_index); 189 | } 190 | } finally { 191 | if (cursor != null) 192 | cursor.close(); 193 | } 194 | return null; 195 | } 196 | 197 | 198 | /** 199 | * @param uri The Uri to check. 200 | * @return Whether the Uri authority is ExternalStorageProvider. 201 | */ 202 | public static boolean isExternalStorageDocument(Uri uri) { 203 | return "com.android.externalstorage.documents".equals(uri.getAuthority()); 204 | } 205 | 206 | /** 207 | * @param uri The Uri to check. 208 | * @return Whether the Uri authority is DownloadsProvider. 209 | */ 210 | public static boolean isDownloadsDocument(Uri uri) { 211 | return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 212 | } 213 | 214 | /** 215 | * @param uri The Uri to check. 216 | * @return Whether the Uri authority is MediaProvider. 217 | */ 218 | public static boolean isMediaDocument(Uri uri) { 219 | return "com.android.providers.media.documents".equals(uri.getAuthority()); 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /app/src/main/java/template/AlertDialogTheme.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.app.AlertDialog; 4 | import android.content.Context; 5 | import android.content.DialogInterface; 6 | import android.graphics.Color; 7 | import android.graphics.drawable.GradientDrawable; 8 | import android.graphics.drawable.InsetDrawable; 9 | import android.text.TextUtils; 10 | import android.util.Log; 11 | import android.util.TypedValue; 12 | import android.view.LayoutInflater; 13 | import android.view.View; 14 | import android.widget.Button; 15 | import android.widget.TextView; 16 | 17 | import androidx.annotation.StringRes; 18 | 19 | import min.test.android_app_template.R; 20 | 21 | //https://www.jianshu.com/p/06a3bbb7ce79 22 | public class AlertDialogTheme { 23 | private static final String TAG = "AlertDialogTheme"; 24 | 25 | /* 主要是看R.style.AlertDialog和AppTheme中的alertDialogTheme */ 26 | public static void test(Context context) { 27 | StringBuilder sb = new StringBuilder(); 28 | for (int i = 0; i < 6; ++i) { 29 | sb.append("消息消息消息消息消息消息消息消息消息消"); 30 | } 31 | //设置了全局alertDialogTheme 32 | // AlertDialog dialog = new AlertDialog.Builder(context) 33 | //单个使用 34 | AlertDialog dialog = new AlertDialog.Builder(context, R.style.AlertDialog) 35 | .setTitle("标题") 36 | .setMessage(sb.toString()) 37 | .setNegativeButton("Cancel", null)//android.R.id.button2 38 | .setNeutralButton("Neutral", null)//android.R.id.button3 39 | .setPositiveButton("OK", null)//android.R.id.button1 40 | .show(); 41 | 42 | //可以通过这种方法修改消息体和按钮,以下所有view只能在show()之后获取,create()之后都不行 43 | TextView text = dialog.findViewById(android.R.id.message); 44 | text.setTextSize(20); 45 | Button btn1 = dialog.findViewById(android.R.id.button1); 46 | Button btn2 = dialog.findViewById(android.R.id.button2); 47 | Button btn3 = dialog.findViewById(android.R.id.button3); 48 | //也可以这么获取 49 | // Button btn1 = dialog.getButton(DialogInterface.BUTTON_POSITIVE); 50 | // Button btn2 = dialog.getButton(DialogInterface.BUTTON_NEGATIVE); 51 | // Button btn3 = dialog.getButton(DialogInterface.BUTTON_NEUTRAL); 52 | Log.e(TAG, "btn1: " + btn1.getText()); 53 | Log.e(TAG, "btn2: " + btn2.getText()); 54 | Log.e(TAG, "btn3: " + btn3.getText()); 55 | } 56 | 57 | public void test2(Context context) { 58 | new Builder(context) 59 | .setTitle("title") 60 | .setMessage("hello") 61 | .setPositiveButton("OK", new DialogInterface.OnClickListener() { 62 | @Override 63 | public void onClick(DialogInterface dialog, int which) { 64 | Log.e(TAG, "onClick: Ok"); 65 | } 66 | }) 67 | .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 68 | @Override 69 | public void onClick(DialogInterface dialog, int which) { 70 | Log.e(TAG, "onClick: Cancel"); 71 | } 72 | }) 73 | .show(); 74 | } 75 | } 76 | 77 | /** 78 | * 仿iOS的Alert,但API尽量和AlertDialog.Builder一致 79 | */ 80 | class Builder { 81 | private Context context; 82 | public Builder(Context context) { 83 | this.context = context; 84 | } 85 | 86 | private CharSequence mTitle; 87 | public Builder setTitle(CharSequence title) { 88 | mTitle = title; 89 | return this; 90 | } 91 | public Builder setTitle(@StringRes int titleId) { 92 | mTitle = context.getText(titleId); 93 | return this; 94 | } 95 | 96 | private CharSequence mMessage; 97 | public Builder setMessage(CharSequence message) { 98 | mMessage = message; 99 | return this; 100 | } 101 | public Builder setMessage(@StringRes int messageId) { 102 | mMessage = context.getText(messageId); 103 | return this; 104 | } 105 | 106 | private CharSequence leftBtnText; 107 | private DialogInterface.OnClickListener leftBtnClick; 108 | public Builder setNegativeButton(CharSequence text, DialogInterface.OnClickListener onClickListener) { 109 | leftBtnText = text; 110 | leftBtnClick = onClickListener; 111 | return this; 112 | } 113 | public Builder setNegativeButton(@StringRes int textId, DialogInterface.OnClickListener onClickListener) { 114 | leftBtnText = context.getText(textId); 115 | leftBtnClick = onClickListener; 116 | return this; 117 | } 118 | 119 | private CharSequence rightBtnText; 120 | private DialogInterface.OnClickListener rightBtnClick; 121 | public Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener onClickListener) { 122 | rightBtnText = text; 123 | rightBtnClick = onClickListener; 124 | return this; 125 | } 126 | public Builder setPositiveButton(@StringRes int textId, DialogInterface.OnClickListener onClickListener) { 127 | rightBtnText = context.getText(textId); 128 | rightBtnClick = onClickListener; 129 | return this; 130 | } 131 | 132 | private boolean mCancelable = true; 133 | public Builder setCancelable(boolean cancelable) { 134 | mCancelable = cancelable; 135 | return this; 136 | } 137 | 138 | private DialogInterface.OnCancelListener mOnCancelListener; 139 | public Builder setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) { 140 | mOnCancelListener = onCancelListener; 141 | return this; 142 | } 143 | 144 | private DialogInterface.OnDismissListener mOnDismissListener; 145 | public Builder setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) { 146 | mOnDismissListener = onDismissListener; 147 | return this; 148 | } 149 | 150 | private DialogInterface.OnKeyListener mOnKeyListener; 151 | public Builder setOnKeyListener(DialogInterface.OnKeyListener onKeyListener) { 152 | mOnKeyListener = onKeyListener; 153 | return this; 154 | } 155 | 156 | public AlertDialog create() { 157 | View view = LayoutInflater.from(context).inflate(R.layout.dialog_2_btn_alert, null, false); 158 | 159 | AlertDialog dialog = new AlertDialog.Builder(context)//R.style.AlertDialogTheme 160 | .setView(view) 161 | .setCancelable(mCancelable) 162 | .setOnCancelListener(mOnCancelListener) 163 | .setOnDismissListener(mOnDismissListener) 164 | .setOnKeyListener(mOnKeyListener) 165 | .create(); 166 | 167 | //设置AlertDialog背景,和使用R.style.AlertDialogTheme创建的AlertDialog效果相同 168 | GradientDrawable drawable = new GradientDrawable(); 169 | drawable.setShape(GradientDrawable.RECTANGLE); 170 | drawable.setColor(Color.WHITE); 171 | drawable.setCornerRadius(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, 172 | context.getResources().getDisplayMetrics())); 173 | InsetDrawable iDrawable = new InsetDrawable(drawable, 174 | (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 26, 175 | context.getResources().getDisplayMetrics())); 176 | dialog.getWindow().setBackgroundDrawable(iDrawable); 177 | 178 | //设置自定义视图dialog_2_btn_alert 179 | TextView tvTitle = view.findViewById(R.id.tvTitle); 180 | TextView tvMessage = view.findViewById(R.id.tvMessage); 181 | TextView btnLeft = view.findViewById(R.id.btn2); 182 | TextView btnRight = view.findViewById(R.id.btn1); 183 | 184 | if (!TextUtils.isEmpty(mTitle)) { 185 | tvTitle.setText(mTitle); 186 | } else { 187 | tvTitle.setVisibility(View.GONE); 188 | } 189 | if (!TextUtils.isEmpty(mMessage)) { 190 | tvMessage.setText(mMessage); 191 | } else { 192 | tvMessage.setVisibility(View.GONE); 193 | } 194 | 195 | if (!TextUtils.isEmpty(leftBtnText)) { 196 | btnLeft.setText(leftBtnText); 197 | btnLeft.setOnClickListener(new DialogOnClick(dialog, leftBtnClick, DialogInterface.BUTTON_NEGATIVE)); 198 | } else { 199 | btnLeft.setVisibility(View.GONE); 200 | } 201 | 202 | if (!TextUtils.isEmpty(rightBtnText)) { 203 | btnRight.setText(rightBtnText); 204 | btnRight.setOnClickListener(new DialogOnClick(dialog, rightBtnClick, DialogInterface.BUTTON_POSITIVE)); 205 | } else { 206 | btnRight.setVisibility(View.GONE); 207 | } 208 | 209 | return dialog; 210 | } 211 | 212 | public AlertDialog show() { 213 | AlertDialog dialog = create(); 214 | dialog.show(); 215 | return dialog; 216 | } 217 | } 218 | 219 | class DialogOnClick implements View.OnClickListener { 220 | private DialogInterface mDialog; 221 | private DialogInterface.OnClickListener mOnClickListener; 222 | private int mWhichButton; 223 | 224 | public DialogOnClick(DialogInterface dialog, DialogInterface.OnClickListener onClickListener, int whichButton) { 225 | mDialog = dialog; 226 | mOnClickListener = onClickListener; 227 | mWhichButton = whichButton; 228 | } 229 | 230 | @Override 231 | public void onClick(View v) { 232 | mDialog.dismiss(); 233 | if (null != mOnClickListener) { 234 | mOnClickListener.onClick(mDialog, mWhichButton); 235 | } 236 | mDialog = null; 237 | mOnClickListener = null; 238 | } 239 | } -------------------------------------------------------------------------------- /app/src/main/java/utils/encryption/aes/AES.java: -------------------------------------------------------------------------------- 1 | package utils.encryption.aes; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.os.Build; 5 | import android.text.TextUtils; 6 | import android.util.Log; 7 | 8 | import androidx.annotation.IntDef; 9 | 10 | import java.io.UnsupportedEncodingException; 11 | import java.nio.charset.StandardCharsets; 12 | import java.security.InvalidAlgorithmParameterException; 13 | import java.security.InvalidKeyException; 14 | import java.security.NoSuchAlgorithmException; 15 | import java.security.NoSuchProviderException; 16 | import java.security.Provider; 17 | import java.security.SecureRandom; 18 | 19 | import javax.crypto.BadPaddingException; 20 | import javax.crypto.Cipher; 21 | import javax.crypto.IllegalBlockSizeException; 22 | import javax.crypto.KeyGenerator; 23 | import javax.crypto.NoSuchPaddingException; 24 | import javax.crypto.spec.IvParameterSpec; 25 | import javax.crypto.spec.SecretKeySpec; 26 | 27 | /* 28 | * 安卓系统提供了多种密钥算法: 29 | * https://developer.android.google.cn/guide/topics/security/cryptography 30 | * https://developer.android.google.cn/training/articles/keystore 31 | */ 32 | //https://zhuanlan.zhihu.com/p/24255780 33 | public class AES { 34 | private static final String TAG = "AES"; 35 | 36 | private final static String SHA1_PRNG = "SHA1PRNG"; 37 | 38 | /* 39 | * 生成随机数,可以当做动态的密钥 加密和解密的密钥必须一致,不然将不能解密 40 | */ 41 | public static String generateKey() { 42 | try { 43 | SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1_PRNG); 44 | byte[] bytesKey = new byte[16]; 45 | localSecureRandom.nextBytes(bytesKey); 46 | String strKey = byte2HexString(bytesKey); 47 | return strKey; 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | return null; 52 | } 53 | 54 | private static final char[] hex = new char[]{ 55 | '0', '1', '2', '3', '4', '5', '6', '7', 56 | '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 57 | }; 58 | //字节数组转16进制字符串 59 | private static String byte2HexString(byte[] buf) { 60 | char[] chs = new char[buf.length * 2]; 61 | // StringBuilder sb = new StringBuilder(buf.length * 2);//字符串很长的时候用此类 62 | // String tp; 63 | int index = 0; 64 | for (byte b : buf) { 65 | //一: 66 | // sb.append(String.format("%02X", b & 0xFF));//性能最差,差的不止一个数量级的 67 | //二:性能第三 68 | // sb.append(Integer.toHexString((b >>> 4) & 0x0F));//byte会被强转成int类型,从而带来符号问题,所以需要(& 0x0F) 69 | // sb.append(Integer.toHexString(b & 0x0F)); 70 | //三:性能第二 71 | // tp = Integer.toHexString(b & 0xFF);//byte会被强转成int类型,同理 72 | // if (tp.length() < 2) sb.append('0'); 73 | // sb.append(tp); 74 | //四:性能最好 75 | // sb.append(hex[(b >>> 4) & 0x0F]); 76 | // sb.append(hex[b & 0x0F]); 77 | chs[index] = hex[(b >>> 4) & 0x0F]; 78 | ++index; 79 | chs[index] = hex[b & 0x0F]; 80 | ++index; 81 | } 82 | // return sb.toString(); 83 | return new String(chs); 84 | } 85 | 86 | //16进制转字节数组 87 | private static byte[] hexString2Byte(String hexStr) { 88 | final int len = hexStr.length(); 89 | if (len < 1) return null; 90 | byte[] result = new byte[len / 2]; 91 | // i/2 == i>>1 92 | // for (int i = 0; i < len; i+=2) { 93 | // result[i>>1] = (byte) Integer.parseInt(hexStr.substring(i, i + 2), 16);//出错抛异常 94 | // } 95 | // for (int i = 0; i < len; i+=2) { 96 | // result[i>>1] = (byte) ((Character.digit((int)hexStr.charAt(i), 16) << 4) 97 | // | Character.digit((int)hexStr.charAt(i + 1), 16));//出错无抛异常 98 | // } 99 | for (int i = 0; i < len; i+=2) { 100 | result[i>>1] = (byte) ((digit(hexStr.charAt(i)) << 4) | digit(hexStr.charAt(i + 1)));//出错抛异常 101 | } 102 | return result; 103 | } 104 | 105 | private static int digit(char codePoint) { 106 | int result = -1; 107 | if ('0' <= codePoint && codePoint <= '9') { 108 | result = codePoint - '0'; 109 | } else if ('a' <= codePoint && codePoint <= 'f') { 110 | result = 10 + (codePoint - 'a'); 111 | } else if ('A' <= codePoint && codePoint <= 'F') { 112 | result = 10 + (codePoint - 'A'); 113 | } else { 114 | throw new NumberFormatException("For input char: \"" + codePoint + "\""); 115 | } 116 | return result; 117 | } 118 | 119 | // 向量 120 | private static final byte[] IV = new byte[]{8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 6, 5}; 121 | 122 | /* 123 | 单片机参考: https://blog.csdn.net/chengjunchengjun/article/details/109322987 124 | 125 | PKCS5Padding 126 | PKCS7Padding 127 | NoPadding 128 | ZerosPadding 129 | ISO10126Padding 130 | 131 | 总结一下,就是用了 NoPadding 就代表着你对这个数据是否可以被完整分组负有责任,如果不能被完整分组就会报错或者抛出异常。 132 | 133 | 然后 ZerosPadding 意思就是在数据块末尾补0x00,注意如果刚开始已经完整分组了也需要补一整个分组的0x00,否则无法解密。 134 | 135 | PKCS7Padding 就是数据个数最后少几个就填充多少个数,具体的做法可以:数据的个数先取余16,然后16减去余数。 136 | 例如{1,2,3,4,5,6,7,8,9},总共9个数值,取余16后是9,需要补充7个7,则最后数据变为{1,2,3,4,5,6,7,8,9,7,7,7,7,7,7,7} 137 | 138 | PKCS5Padding,PKCS7Padding的子集,块大小固定为8字节。在AES加密当中其实是没有pkcs5的, 139 | 因为AES的分块是16B而pkcs5只能用于8B,所以我们在AES加密中所说的pkcs5指的就是pkcs7。 140 | 141 | 由于使用 PKCS7Padding/PKCS5Padding 填充时,最后一个字节肯定为填充数据的长度,所以在解密后可以准确删除填充的数据, 142 | 而使用 ZeroPadding 填充时,没办法区分真实数据与填充数据,所以只适合以\0结尾的字符串加解密。 143 | 为了改善这种不足,ISO10126Padding 采用不足的n-1位补随机数,最后一位补n的做法。 144 | */ 145 | /** 146 | * AES加密 147 | * @param data 要加密的数据 148 | * @param key 密钥,长度必须是8的整倍数? 149 | * @return 加密后的数据 150 | */ 151 | public static byte[] encryptAES128CBC(byte[] data, byte[] key) { 152 | try { 153 | // iOS 只支持 PKCS7Padding 加密,或者 iOS 也用NoPadding自己补齐,Android PKCS7Padding 和 PKCS5Padding 都支持。AES/CBC/PKCS7Padding AES/ECB/PKCS5Padding 154 | @SuppressLint("GetInstance") 155 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 156 | 157 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV)); 158 | int blockSize = cipher.getBlockSize(); 159 | int length = data.length; 160 | if (length % blockSize == 0) return cipher.doFinal(data); 161 | 162 | // 使用 NoPadding 就要自己补齐不足的字节 163 | length = length + (blockSize - (length % blockSize)); 164 | byte[] newData = new byte[length]; 165 | System.arraycopy(data, 0, newData, 0, data.length); 166 | return cipher.doFinal(newData); 167 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) { 168 | Log.e(TAG, "aes128encrypt: ", e); 169 | } 170 | 171 | return null; 172 | } 173 | 174 | public static byte[] decryptUseAES128CBC(byte[] data, byte[] key) { 175 | try { 176 | @SuppressLint("GetInstance") 177 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 178 | cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV)); 179 | return trimBytes(cipher.doFinal(data)); 180 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) { 181 | Log.e(TAG, "aes128encrypt: ", e); 182 | } 183 | 184 | return null; 185 | } 186 | 187 | public static byte[] trimBytes(byte[] bytes) { 188 | int useLen; 189 | for (useLen = bytes.length - 1; useLen >= 0; useLen--) { 190 | if (0x00 != bytes[useLen]) { 191 | byte[] newBytes = new byte[useLen + 1]; 192 | System.arraycopy(bytes, 0, newBytes, 0, newBytes.length); 193 | return newBytes; 194 | } 195 | } 196 | if (bytes.length == 16) { 197 | return new byte[]{bytes[0]}; 198 | } 199 | return bytes; 200 | } 201 | 202 | public static byte[] encryptAES128CBCPKCS7(byte[] data, byte[] key) { 203 | try { 204 | // iOS 只支持 PKCS7Padding 加密,或者 iOS 也用NoPadding自己补齐,Android PKCS7Padding 和 PKCS5Padding 都支持。AES/CBC/PKCS7Padding AES/ECB/PKCS5Padding 205 | @SuppressLint("GetInstance") 206 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 207 | 208 | // ECB 不需要 IvParameterSpec 209 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV)); 210 | return cipher.doFinal(data); 211 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) { 212 | Log.e(TAG, "aes128encrypt: ", e); 213 | } 214 | 215 | return null; 216 | } 217 | 218 | public static byte[] decryptUseAES128CBCPKCS7(byte[] data, byte[] key) { 219 | try { 220 | @SuppressLint("GetInstance") 221 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); 222 | // ECB 不需要 IvParameterSpec 223 | cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV)); 224 | return cipher.doFinal(data); 225 | } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e) { 226 | Log.e(TAG, "aes128encrypt: ", e); 227 | } 228 | 229 | return null; 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /app/src/main/java/template/CalendarAndAlarmClock.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | import android.Manifest; 4 | import android.app.Activity; 5 | import android.content.ContentUris; 6 | import android.content.ContentValues; 7 | import android.content.Intent; 8 | import android.content.pm.PackageManager; 9 | import android.database.Cursor; 10 | import android.net.Uri; 11 | import android.provider.AlarmClock; 12 | import android.provider.CalendarContract; 13 | import android.widget.Toast; 14 | 15 | import androidx.core.app.ActivityCompat; 16 | 17 | import org.json.JSONArray; 18 | import org.json.JSONException; 19 | import org.json.JSONObject; 20 | 21 | import java.util.ArrayList; 22 | import java.util.Calendar; 23 | import java.util.TimeZone; 24 | 25 | /** 26 | * https://developer.android.com/guide/topics/providers/calendar-provider 27 | * https://www.jianshu.com/p/4820e02b2ee4 28 | */ 29 | public class CalendarAndAlarmClock { 30 | 31 | private static Uri calanderURL = CalendarContract.Calendars.CONTENT_URI; 32 | private static Uri calanderEventURL = CalendarContract.Events.CONTENT_URI; 33 | private static Uri calanderRemiderURL = CalendarContract.Reminders.CONTENT_URI; 34 | 35 | private static long calenderId = -1; 36 | 37 | /** 38 | * 是否没有读写权限 39 | * @param activity 40 | * @return true没有读写权限, false有读写权限 41 | */ 42 | public static boolean hasNoReadWritePermission(Activity activity) { 43 | return ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED || 44 | ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED; 45 | } 46 | /** 47 | * 请求读写权限 48 | * 需要重写的方法: 49 | * @see ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[]) 50 | * 用户操作后回调重写方法 51 | * */ 52 | public static void requestReadWritePermission(Activity activity, int requestCode) { 53 | ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}, requestCode); 54 | } 55 | 56 | private static void init(Activity activity) { 57 | if (calenderId <= 0) { 58 | Cursor userCursor = activity.getContentResolver() 59 | .query(calanderURL, null, null, null, null); 60 | //如果小于1代表没有账户 61 | if (userCursor.getCount() < 1) { 62 | //添加账户 63 | calenderId = initCalendars(activity, "mintest"); 64 | } else { 65 | //注意:是向最后一个账户添加,开发者可以根据需要改变添加事件 的账户 66 | userCursor.moveToLast(); 67 | calenderId = userCursor.getLong(userCursor.getColumnIndex(CalendarContract.Calendars._ID)); 68 | } 69 | userCursor.close(); 70 | } 71 | } 72 | 73 | /** 74 | * 添加一个属于自己的账户,方便以后取这个账户的提醒事件 75 | * 76 | * @param activity 77 | * @param accountName 账户名 78 | */ 79 | private static long initCalendars(Activity activity, String accountName) { 80 | /* 81 | * 小米默认账户 82 | * allowedReminders=0,1 83 | * sync_events=1 84 | * canModifyTimeZone=1 85 | * canOrganizerRespond=1 86 | * maxReminders=5 87 | * _id=1 88 | * visible=1 89 | * calendar_color=-30720 90 | * account_name=account_name_local 91 | * account_type=LOCAL 92 | * calendar_displayName=calendar_displayname_local 93 | * deleted=0 94 | * ownerAccount=owner_account_local 95 | * calendar_access_level=700 96 | * canPartiallyUpdate=0 97 | */ 98 | ContentValues value = new ContentValues(); 99 | value.put(CalendarContract.Calendars.NAME, "com.min.test"); 100 | 101 | value.put(CalendarContract.Calendars.ACCOUNT_NAME, accountName);//日历账户名称 102 | value.put(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.exchange"); 103 | value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, accountName); 104 | value.put(CalendarContract.Calendars.VISIBLE, 1); 105 | value.put(CalendarContract.Calendars.CALENDAR_COLOR, -30720); 106 | value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER); 107 | value.put(CalendarContract.Calendars.SYNC_EVENTS, 1); 108 | value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, TimeZone.getDefault().getID()); 109 | value.put(CalendarContract.Calendars.OWNER_ACCOUNT, accountName); 110 | value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0); 111 | 112 | Uri calendarUri = CalendarContract.Calendars.CONTENT_URI; 113 | calendarUri = calendarUri.buildUpon() 114 | .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") 115 | .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName) 116 | .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, "com.android.exchange") 117 | .build(); 118 | //插入账号数据 119 | Uri uri = activity.getContentResolver().insert(calendarUri, value); 120 | if (null != uri) { 121 | return ContentUris.parseId(uri); 122 | } 123 | return -1; 124 | } 125 | 126 | /** 127 | * 日期时间转时间戳 128 | * @param time 时间 格式 yyyy/mm/dd/hh/mm 129 | * @return 130 | */ 131 | private static long getTime(String time) { 132 | Calendar calendar = Calendar.getInstance(); 133 | String[] startTime = time.split("/"); 134 | calendar.set(Calendar.YEAR, Integer.parseInt(startTime[0]));//年 135 | calendar.set(Calendar.MONTH, Integer.parseInt(startTime[1])-1);//月 136 | calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(startTime[2]));//日 137 | calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTime[3]));//时 138 | calendar.set(Calendar.MINUTE, Integer.parseInt(startTime[4]));//分 139 | return calendar.getTimeInMillis(); 140 | } 141 | 142 | /** 143 | * 获取日历事件 144 | * 145 | * @param context 146 | */ 147 | public static JSONArray queryCalendarEvent(Activity context, long eventId) throws JSONException { 148 | Uri uri = calanderEventURL; 149 | if (eventId > 0) { 150 | uri = ContentUris.withAppendedId(calanderEventURL, eventId); 151 | } 152 | Cursor cursor = context.getContentResolver() 153 | .query(uri, null, 154 | CalendarContract.Events.MUTATORS + " = ?", 155 | new String[]{context.getPackageName()}, null); 156 | JSONArray ja = new JSONArray(); 157 | JSONObject jo; 158 | while (cursor.moveToNext()) { 159 | jo = new JSONObject(); 160 | jo.put("title", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.TITLE))); 161 | jo.put("description", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DESCRIPTION))); 162 | jo.put("dtStart", cursor.getString(cursor.getColumnIndex(CalendarContract.Events.DTSTART))); 163 | String rrule = cursor.getString(cursor.getColumnIndex(CalendarContract.Events.RRULE)); 164 | if (null != rrule) { 165 | String[] keyValues = rrule.split(";"); 166 | 167 | String[] keyValue = keyValues[0].split("="); 168 | jo.put("freq", keyValue[1].toLowerCase()); 169 | 170 | keyValue = keyValues[1].split("="); 171 | jo.put("interval", keyValue[1]); 172 | } 173 | ja.put(jo); 174 | } 175 | cursor.close(); 176 | return ja; 177 | } 178 | 179 | /** 180 | * 添加日历事件或更新 181 | * 182 | * @param context 183 | * @param title 日程标题 184 | * @param description 备注信息 185 | * @param dtStart 提醒开始时间, 时间戳 186 | * @param freq 频率 187 | * @param interval 频率间隔 188 | * @return 189 | */ 190 | public static int addCalendarEvent(Activity context, long eventId, String title, String description, long dtStart, String freq, short interval) { 191 | if (dtStart <= 0) { 192 | Toast.makeText(context, "提醒开始时间不能为空!", Toast.LENGTH_SHORT).show(); 193 | return -1; 194 | } 195 | 196 | init(context); 197 | 198 | //rrule组装 199 | switch (freq.toLowerCase()) { 200 | case "daily"://天 201 | break; 202 | case "weekly"://周 203 | { 204 | Calendar calendar = Calendar.getInstance(); 205 | calendar.setTimeInMillis(dtStart); 206 | String[] weeklys = new String[]{"SU", "MO", "TU", "WE", "TH", "FR", "SA"}; 207 | String wk = ";BYDAY=" + weeklys[calendar.get(Calendar.DAY_OF_WEEK) - 1]; 208 | } 209 | break; 210 | case "monthly"://月 211 | break; 212 | case "yearly"://年 213 | break; 214 | } 215 | 216 | //FREQ=WEEKLY;INTERVAL=2;WKST=SU;BYDAY=WE //WKST得根据地区调整? 217 | String rrlue = "FREQ=" + freq.toUpperCase() + ";INTERVAL" + interval; 218 | 219 | ContentValues event = new ContentValues(); 220 | // 插入账户 221 | event.put(CalendarContract.Events.CALENDAR_ID, 1); 222 | // event.put(CalendarContract.Events.MUTATORS, context.getPackageName());//同步的包名,不用自己设置,系统默认设置成自己的包名 223 | event.put(CalendarContract.Events.TITLE, title); 224 | event.put(CalendarContract.Events.DESCRIPTION, description); 225 | event.put(CalendarContract.Events.DURATION, "P10M");//我们默认持续时间10分钟 226 | event.put(CalendarContract.Events.RRULE, rrlue);//重复规则,https://www.cnblogs.com/ice5/p/14023771.html 227 | // event.put(CalendarContract.Events.HAS_ALARM, true);//是否含有提醒,这个不用设置,关联Reminders是会自动设置为true 228 | // event.put(CalendarContract.Events.ALLOWED_REMINDERS, CalendarContract.Reminders.METHOD_ALERT);//是否提示,默认0,1 229 | event.put(CalendarContract.Events.DTSTART, dtStart);//提醒开始时间 230 | event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID()); //这个是时区,必须有, 231 | Uri newEvent; 232 | if (eventId <= 0) { 233 | //添加事件 234 | newEvent = context.getContentResolver().insert(calanderEventURL, event); 235 | } else { 236 | Uri uri = ContentUris.withAppendedId(calanderEventURL, eventId); 237 | return context.getContentResolver().update(uri, event, null, null); 238 | } 239 | if (null == newEvent) { 240 | return -1; 241 | } 242 | 243 | //事件提醒的设定 244 | ContentValues values = new ContentValues(); 245 | values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent)); 246 | values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); 247 | if (context.getContentResolver().insert(calanderRemiderURL, values) == null) { 248 | return -1; 249 | } 250 | return 0; 251 | } 252 | 253 | /** 254 | * 删除日历事件 255 | */ 256 | public static int deleteCalendarEvent(Activity context, long id) { 257 | return context.getContentResolver().delete(ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id), null, null); 258 | } 259 | 260 | //必须的权限:  261 | private void createAlarm(Activity activity, String message, int hour, int minutes, int resId) { 262 | ArrayList testDays = new ArrayList<>(); 263 | testDays.add(Calendar.MONDAY);//周一 264 | testDays.add(Calendar.TUESDAY);//周二 265 | testDays.add(Calendar.FRIDAY);//周五 266 | 267 | String packageName = activity.getPackageName(); 268 | Uri ringtoneUri = Uri.parse("android.resource://" + packageName + "/" + resId); 269 | 270 | Intent intent = new Intent(AlarmClock.ACTION_SET_ALARM)//ACTION_DISMISS_ALARM 271 | //闹钟的小时 272 | .putExtra(AlarmClock.EXTRA_HOUR, hour) 273 | //闹钟的分钟 274 | .putExtra(AlarmClock.EXTRA_MINUTES, minutes) 275 | //响铃时提示的信息 276 | .putExtra(AlarmClock.EXTRA_MESSAGE, message) 277 | //用于指定该闹铃触发时是否振动 278 | .putExtra(AlarmClock.EXTRA_VIBRATE, true) 279 | //一个 content: URI,用于指定闹铃使用的铃声,也可指定 VALUE_RINGTONE_SILENT 以不使用铃声。 280 | //如需使用默认铃声,则无需指定此 extra。 281 | .putExtra(AlarmClock.EXTRA_RINGTONE, ringtoneUri) 282 | //对于一次性闹铃,无需指定此 extra 283 | .putExtra(AlarmClock.EXTRA_DAYS, testDays) 284 | //如果为true,则调用startActivity()不会进入手机的闹钟设置界面 285 | .putExtra(AlarmClock.EXTRA_SKIP_UI, true); 286 | if (intent.resolveActivity(activity.getPackageManager()) != null) { 287 | activity.startActivity(intent); 288 | } 289 | } 290 | } 291 | --------------------------------------------------------------------------------