├── app ├── .gitignore ├── build.gradle ├── libs │ └── library-release.aar ├── proguard-rules.pro ├── saferCompExporting.gradle └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── madchan │ │ └── supportandroid12 │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── madchan │ │ │ └── supportandroid12 │ │ │ ├── MainActivity.kt │ │ │ ├── PermissionUtils.kt │ │ │ ├── SPUtils.java │ │ │ ├── SplashActivity.kt │ │ │ ├── SupportAndroid12Application.kt │ │ │ ├── appSplashScreens │ │ │ ├── AppSplashScreensActivity.kt │ │ │ └── AppSplashScreensStateMachine.kt │ │ │ ├── approximateLocation │ │ │ └── ApproximateLocationActivity.kt │ │ │ ├── customNotification │ │ │ └── CustomNotificationActivity.kt │ │ │ ├── exactAlarmPermission │ │ │ ├── ExactAlarmPermissionActivity.kt │ │ │ ├── ExactAlarmPermissionReceiver.kt │ │ │ └── ExactAlarmPermissionStateMachine.kt │ │ │ ├── foregroundServiceLimit │ │ │ ├── ForegroundServiceLimitActivity.kt │ │ │ └── ForegroundServiceLimitService.kt │ │ │ ├── notificationTrampolineLimit │ │ │ ├── NotificationTrampolineLimitActivity.kt │ │ │ ├── NotificationTrampolineLimitReceiver.kt │ │ │ └── NotificationTrampolineLimitService.kt │ │ │ ├── pendingIntentsMutability │ │ │ └── PendingIntentsMutabilityActivity.kt │ │ │ ├── saferComponentExporting │ │ │ └── SaferComponentExportingActivity.kt │ │ │ └── toggleMicAndCamera │ │ │ └── ToggleMicActivity.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_app_splash_screens.xml │ │ ├── activity_approximate_location.xml │ │ ├── activity_custom_notification.xml │ │ ├── activity_exact_alarm_permission.xml │ │ ├── activity_limit_foreground_service.xml │ │ ├── activity_main.xml │ │ ├── activity_notification_trampoline_limit.xml │ │ ├── activity_pending_intents_mutability.xml │ │ ├── activity_safer_component_exporting.xml │ │ ├── activity_splash.xml │ │ ├── activity_toggle_mic.xml │ │ ├── notification_large.xml │ │ └── notification_small.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── values-night │ │ └── themes.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ ├── styles.xml │ │ └── themes.xml │ │ └── xml │ │ └── filepaths.xml │ └── test │ └── java │ └── com │ └── madchan │ └── supportandroid12 │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── madchan │ │ └── library │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── madchan │ │ └── library │ │ └── SaferComponentExportingService.kt │ └── test │ └── java │ └── com │ └── madchan │ └── library │ └── ExampleUnitTest.kt └── settings.gradle /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | //apply from: 'saferCompExporting.gradle' 6 | 7 | android { 8 | compileSdkVersion 32 9 | 10 | defaultConfig { 11 | applicationId "com.madchan.supportandroid12" 12 | minSdkVersion 21 13 | targetSdkVersion 31 14 | versionCode 1 15 | versionName "1.0" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | 20 | buildTypes { 21 | release { 22 | minifyEnabled false 23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 24 | } 25 | } 26 | compileOptions { 27 | sourceCompatibility JavaVersion.VERSION_1_8 28 | targetCompatibility JavaVersion.VERSION_1_8 29 | } 30 | kotlinOptions { 31 | jvmTarget = '1.8' 32 | } 33 | viewBinding { 34 | enabled = true 35 | } 36 | } 37 | 38 | dependencies { 39 | 40 | implementation 'androidx.core:core-ktx:1.7.0' 41 | implementation 'androidx.appcompat:appcompat:1.4.1' 42 | implementation 'com.google.android.material:material:1.5.0' 43 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3' 44 | testImplementation 'junit:junit:4.13.2' 45 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 46 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 47 | 48 | implementation 'androidx.core:core-splashscreen:1.0.0-beta01' 49 | 50 | // implementation files('libs/library-release.aar') 51 | } -------------------------------------------------------------------------------- /app/libs/library-release.aar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/madchan/SupportAndroid12/a9211f199eeb6f98e7cdaa86069e623928cf251c/app/libs/library-release.aar -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /app/saferCompExporting.gradle: -------------------------------------------------------------------------------- 1 | /** 2 | * 修改 Android 12 因为 exported 的构建问题 3 | */ 4 | android.applicationVariants.all { variant -> 5 | variant.outputs.each { output -> 6 | def processManifest = output.getProcessManifestProvider().get() 7 | processManifest.doLast { task -> 8 | def outputDir = task.multiApkManifestOutputDirectory 9 | File outputDirectory 10 | if (outputDir instanceof File) { 11 | outputDirectory = outputDir 12 | } else { 13 | outputDirectory = outputDir.get().asFile 14 | } 15 | File manifestOutFile = file("$outputDirectory/AndroidManifest.xml") 16 | println("----------- ${manifestOutFile} ----------- ") 17 | 18 | if (manifestOutFile.exists() && manifestOutFile.canRead() && manifestOutFile.canWrite()) { 19 | def manifestFile = manifestOutFile 20 | ///这里第二个参数是 false ,所以 namespace 是展开的,所以下面不能用 androidSpace,而是用 nameTag 21 | def xml = new XmlParser(false, false).parse(manifestFile) 22 | def exportedTag = "android:exported" 23 | def nameTag = "android:name" 24 | ///指定 space 25 | //def androidSpace = new groovy.xml.Namespace('http://schemas.android.com/apk/res/android', 'android') 26 | 27 | def nodes = xml.application[0].'*'.findAll { 28 | //挑选要修改的节点,没有指定的 exported 的才需要增加 29 | //如果 exportedTag 拿不到可以尝试 it.attribute(androidSpace.exported) 30 | (it.name() == 'activity' || it.name() == 'receiver' || it.name() == 'service') && it.attribute(exportedTag) == null 31 | 32 | } 33 | ///添加 exported,默认 false 34 | nodes.each { 35 | def isMain = false 36 | it.each { 37 | if (it.name() == "intent-filter") { 38 | it.each { 39 | if (it.name() == "action") { 40 | //如果 nameTag 拿不到可以尝试 it.attribute(androidSpace.name) 41 | if (it.attributes().get(nameTag) == "android.intent.action.MAIN") { 42 | isMain = true 43 | println("......................MAIN FOUND......................") 44 | } 45 | } 46 | } 47 | } 48 | } 49 | it.attributes().put(exportedTag, "${isMain}") 50 | } 51 | 52 | PrintWriter pw = new PrintWriter(manifestFile) 53 | pw.write(groovy.xml.XmlUtil.serialize(xml)) 54 | pw.close() 55 | 56 | } 57 | 58 | } 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/madchan/supportandroid12/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12 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("com.madchan.supportandroid12", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 20 | 23 | 26 | 29 | 30 | 34 | 38 | 39 | 43 | 47 | 48 | 51 | 54 | 57 | 60 | 63 | 66 | 69 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 90 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.view.View 6 | import androidx.appcompat.app.AppCompatActivity 7 | import com.madchan.supportandroid12.appSplashScreens.AppSplashScreensActivity 8 | import com.madchan.supportandroid12.approximateLocation.ApproximateLocationActivity 9 | import com.madchan.supportandroid12.customNotification.CustomNotificationActivity 10 | import com.madchan.supportandroid12.databinding.ActivityMainBinding 11 | import com.madchan.supportandroid12.exactAlarmPermission.ExactAlarmPermissionActivity 12 | import com.madchan.supportandroid12.foregroundServiceLimit.ForegroundServiceLimitActivity 13 | import com.madchan.supportandroid12.notificationTrampolineLimit.NotificationTrampolineLimitActivity 14 | import com.madchan.supportandroid12.pendingIntentsMutability.PendingIntentsMutabilityActivity 15 | import com.madchan.supportandroid12.saferComponentExporting.SaferComponentExportingActivity 16 | import com.madchan.supportandroid12.toggleMicAndCamera.ToggleMicActivity 17 | 18 | class MainActivity : AppCompatActivity() { 19 | 20 | lateinit var binding: ActivityMainBinding 21 | 22 | override fun onCreate(savedInstanceState: Bundle?) { 23 | super.onCreate(savedInstanceState) 24 | binding = ActivityMainBinding.inflate(layoutInflater) 25 | setContentView(binding.root) 26 | } 27 | 28 | fun toggleMic(view: View) { 29 | startActivity(Intent(this, ToggleMicActivity::class.java)) 30 | } 31 | 32 | fun foregroundServiceLimit(view: View) { 33 | startActivity(Intent(this, ForegroundServiceLimitActivity::class.java)) 34 | finish() 35 | } 36 | 37 | fun notificationTrampolineLimit(view: View) { 38 | startActivity(Intent(this, NotificationTrampolineLimitActivity::class.java)) 39 | finish() 40 | } 41 | 42 | fun approximateLocation(view: View) { 43 | startActivity(Intent(this, ApproximateLocationActivity::class.java)) 44 | } 45 | 46 | fun customNotification(view: View) { 47 | startActivity(Intent(this, CustomNotificationActivity::class.java)) 48 | } 49 | 50 | fun exactAlarmPermission(view: View) { 51 | startActivity(Intent(this, ExactAlarmPermissionActivity::class.java)) 52 | } 53 | 54 | fun appStartup(view: View) { 55 | startActivity(Intent(this, AppSplashScreensActivity::class.java)) 56 | } 57 | 58 | fun saferComponentExporting(view: View) { 59 | startActivity(Intent(this, SaferComponentExportingActivity::class.java)) 60 | } 61 | 62 | fun pendingIntentsMutability(view: View) { 63 | startActivity(Intent(this, PendingIntentsMutabilityActivity::class.java)) 64 | } 65 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/PermissionUtils.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12 2 | 3 | import android.app.AlarmManager 4 | import android.content.Context 5 | import android.content.pm.PackageManager 6 | import android.os.Build 7 | 8 | fun hasRequirePermission(context: Context): Boolean { 9 | val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager 10 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 11 | alarmManager?.canScheduleExactAlarms() == true 12 | } else { 13 | false 14 | } 15 | } 16 | 17 | fun hasDeclarePermission(context: Context): Boolean { 18 | val packageManager: PackageManager = context.packageManager 19 | try { 20 | val packageInfo = 21 | packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS) 22 | val permissions = packageInfo.requestedPermissions 23 | return permissions.contains(android.Manifest.permission.SCHEDULE_EXACT_ALARM) 24 | } catch (e: PackageManager.NameNotFoundException) { 25 | e.printStackTrace() 26 | } 27 | return false 28 | } 29 | 30 | class PermissionUtils { 31 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/SPUtils.java: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.SharedPreferences; 6 | 7 | import androidx.annotation.NonNull; 8 | import androidx.annotation.Nullable; 9 | 10 | import java.util.Collections; 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | import java.util.Set; 14 | 15 | /** 16 | *
 17 |  *     author: Blankj
 18 |  *     blog  : http://blankj.com
 19 |  *     time  : 2016/08/02
 20 |  *     desc  : utils about shared preference
 21 |  * 
22 | */ 23 | @SuppressLint("ApplySharedPref") 24 | public final class SPUtils { 25 | 26 | private static final Map SP_UTILS_MAP = new HashMap<>(); 27 | 28 | private SharedPreferences sp; 29 | 30 | /** 31 | * Return the single {@link SPUtils} instance 32 | * 33 | * @return the single {@link SPUtils} instance 34 | */ 35 | public static SPUtils getInstance(Context context) { 36 | return getInstance(context, "", Context.MODE_PRIVATE); 37 | } 38 | 39 | /** 40 | * Return the single {@link SPUtils} instance 41 | * 42 | * @param mode Operating mode. 43 | * @return the single {@link SPUtils} instance 44 | */ 45 | public static SPUtils getInstance(Context context, final int mode) { 46 | return getInstance(context, "", mode); 47 | } 48 | 49 | /** 50 | * Return the single {@link SPUtils} instance 51 | * 52 | * @param spName The name of sp. 53 | * @return the single {@link SPUtils} instance 54 | */ 55 | public static SPUtils getInstance(Context context, String spName) { 56 | return getInstance(context, spName, Context.MODE_PRIVATE); 57 | } 58 | 59 | /** 60 | * Return the single {@link SPUtils} instance 61 | * 62 | * @param spName The name of sp. 63 | * @param mode Operating mode. 64 | * @return the single {@link SPUtils} instance 65 | */ 66 | public static SPUtils getInstance(Context context, String spName, final int mode) { 67 | if (isSpace(spName)) spName = "spUtils"; 68 | SPUtils spUtils = SP_UTILS_MAP.get(spName); 69 | if (spUtils == null) { 70 | synchronized (SPUtils.class) { 71 | spUtils = SP_UTILS_MAP.get(spName); 72 | if (spUtils == null) { 73 | spUtils = new SPUtils(context, spName, mode); 74 | SP_UTILS_MAP.put(spName, spUtils); 75 | } 76 | } 77 | } 78 | return spUtils; 79 | } 80 | 81 | private SPUtils(Context context, final String spName) { 82 | sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE); 83 | } 84 | 85 | private SPUtils(Context context, final String spName, final int mode) { 86 | sp = context.getSharedPreferences(spName, mode); 87 | } 88 | 89 | /** 90 | * Put the string value in sp. 91 | * 92 | * @param key The key of sp. 93 | * @param value The value of sp. 94 | */ 95 | public void put(@NonNull final String key, final String value) { 96 | put(key, value, false); 97 | } 98 | 99 | /** 100 | * Put the string value in sp. 101 | * 102 | * @param key The key of sp. 103 | * @param value The value of sp. 104 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 105 | * false to use {@link SharedPreferences.Editor#apply()} 106 | */ 107 | public void put(@NonNull final String key, final String value, final boolean isCommit) { 108 | if (isCommit) { 109 | sp.edit().putString(key, value).commit(); 110 | } else { 111 | sp.edit().putString(key, value).apply(); 112 | } 113 | } 114 | 115 | /** 116 | * Return the string value in sp. 117 | * 118 | * @param key The key of sp. 119 | * @return the string value if sp exists or {@code ""} otherwise 120 | */ 121 | public String getString(@NonNull final String key) { 122 | return getString(key, ""); 123 | } 124 | 125 | /** 126 | * Return the string value in sp. 127 | * 128 | * @param key The key of sp. 129 | * @param defaultValue The default value if the sp doesn't exist. 130 | * @return the string value if sp exists or {@code defaultValue} otherwise 131 | */ 132 | public String getString(@NonNull final String key, final String defaultValue) { 133 | return sp.getString(key, defaultValue); 134 | } 135 | 136 | /** 137 | * Put the int value in sp. 138 | * 139 | * @param key The key of sp. 140 | * @param value The value of sp. 141 | */ 142 | public void put(@NonNull final String key, final int value) { 143 | put(key, value, false); 144 | } 145 | 146 | /** 147 | * Put the int value in sp. 148 | * 149 | * @param key The key of sp. 150 | * @param value The value of sp. 151 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 152 | * false to use {@link SharedPreferences.Editor#apply()} 153 | */ 154 | public void put(@NonNull final String key, final int value, final boolean isCommit) { 155 | if (isCommit) { 156 | sp.edit().putInt(key, value).commit(); 157 | } else { 158 | sp.edit().putInt(key, value).apply(); 159 | } 160 | } 161 | 162 | /** 163 | * Return the int value in sp. 164 | * 165 | * @param key The key of sp. 166 | * @return the int value if sp exists or {@code -1} otherwise 167 | */ 168 | public int getInt(@NonNull final String key) { 169 | return getInt(key, -1); 170 | } 171 | 172 | /** 173 | * Return the int value in sp. 174 | * 175 | * @param key The key of sp. 176 | * @param defaultValue The default value if the sp doesn't exist. 177 | * @return the int value if sp exists or {@code defaultValue} otherwise 178 | */ 179 | public int getInt(@NonNull final String key, final int defaultValue) { 180 | return sp.getInt(key, defaultValue); 181 | } 182 | 183 | /** 184 | * Put the long value in sp. 185 | * 186 | * @param key The key of sp. 187 | * @param value The value of sp. 188 | */ 189 | public void put(@NonNull final String key, final long value) { 190 | put(key, value, false); 191 | } 192 | 193 | /** 194 | * Put the long value in sp. 195 | * 196 | * @param key The key of sp. 197 | * @param value The value of sp. 198 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 199 | * false to use {@link SharedPreferences.Editor#apply()} 200 | */ 201 | public void put(@NonNull final String key, final long value, final boolean isCommit) { 202 | if (isCommit) { 203 | sp.edit().putLong(key, value).commit(); 204 | } else { 205 | sp.edit().putLong(key, value).apply(); 206 | } 207 | } 208 | 209 | /** 210 | * Return the long value in sp. 211 | * 212 | * @param key The key of sp. 213 | * @return the long value if sp exists or {@code -1} otherwise 214 | */ 215 | public long getLong(@NonNull final String key) { 216 | return getLong(key, -1L); 217 | } 218 | 219 | /** 220 | * Return the long value in sp. 221 | * 222 | * @param key The key of sp. 223 | * @param defaultValue The default value if the sp doesn't exist. 224 | * @return the long value if sp exists or {@code defaultValue} otherwise 225 | */ 226 | public long getLong(@NonNull final String key, final long defaultValue) { 227 | return sp.getLong(key, defaultValue); 228 | } 229 | 230 | /** 231 | * Put the float value in sp. 232 | * 233 | * @param key The key of sp. 234 | * @param value The value of sp. 235 | */ 236 | public void put(@NonNull final String key, final float value) { 237 | put(key, value, false); 238 | } 239 | 240 | /** 241 | * Put the float value in sp. 242 | * 243 | * @param key The key of sp. 244 | * @param value The value of sp. 245 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 246 | * false to use {@link SharedPreferences.Editor#apply()} 247 | */ 248 | public void put(@NonNull final String key, final float value, final boolean isCommit) { 249 | if (isCommit) { 250 | sp.edit().putFloat(key, value).commit(); 251 | } else { 252 | sp.edit().putFloat(key, value).apply(); 253 | } 254 | } 255 | 256 | /** 257 | * Return the float value in sp. 258 | * 259 | * @param key The key of sp. 260 | * @return the float value if sp exists or {@code -1f} otherwise 261 | */ 262 | public float getFloat(@NonNull final String key) { 263 | return getFloat(key, -1f); 264 | } 265 | 266 | /** 267 | * Return the float value in sp. 268 | * 269 | * @param key The key of sp. 270 | * @param defaultValue The default value if the sp doesn't exist. 271 | * @return the float value if sp exists or {@code defaultValue} otherwise 272 | */ 273 | public float getFloat(@NonNull final String key, final float defaultValue) { 274 | return sp.getFloat(key, defaultValue); 275 | } 276 | 277 | /** 278 | * Put the boolean value in sp. 279 | * 280 | * @param key The key of sp. 281 | * @param value The value of sp. 282 | */ 283 | public void put(@NonNull final String key, final boolean value) { 284 | put(key, value, true); 285 | } 286 | 287 | /** 288 | * Put the boolean value in sp. 289 | * 290 | * @param key The key of sp. 291 | * @param value The value of sp. 292 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 293 | * false to use {@link SharedPreferences.Editor#apply()} 294 | */ 295 | public void put(@NonNull final String key, final boolean value, final boolean isCommit) { 296 | if (isCommit) { 297 | sp.edit().putBoolean(key, value).commit(); 298 | } else { 299 | sp.edit().putBoolean(key, value).apply(); 300 | } 301 | } 302 | 303 | /** 304 | * Return the boolean value in sp. 305 | * 306 | * @param key The key of sp. 307 | * @return the boolean value if sp exists or {@code false} otherwise 308 | */ 309 | public boolean getBoolean(@NonNull final String key) { 310 | return getBoolean(key, false); 311 | } 312 | 313 | /** 314 | * Return the boolean value in sp. 315 | * 316 | * @param key The key of sp. 317 | * @param defaultValue The default value if the sp doesn't exist. 318 | * @return the boolean value if sp exists or {@code defaultValue} otherwise 319 | */ 320 | public boolean getBoolean(@NonNull final String key, final boolean defaultValue) { 321 | return sp.getBoolean(key, defaultValue); 322 | } 323 | 324 | /** 325 | * Put the set of string value in sp. 326 | * 327 | * @param key The key of sp. 328 | * @param value The value of sp. 329 | */ 330 | public void put(@NonNull final String key, final Set value) { 331 | put(key, value, false); 332 | } 333 | 334 | /** 335 | * Put the set of string value in sp. 336 | * 337 | * @param key The key of sp. 338 | * @param value The value of sp. 339 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 340 | * false to use {@link SharedPreferences.Editor#apply()} 341 | */ 342 | public void put(@NonNull final String key, 343 | final Set value, 344 | final boolean isCommit) { 345 | if (isCommit) { 346 | sp.edit().putStringSet(key, value).commit(); 347 | } else { 348 | sp.edit().putStringSet(key, value).apply(); 349 | } 350 | } 351 | 352 | /** 353 | * Return the set of string value in sp. 354 | * 355 | * @param key The key of sp. 356 | * @return the set of string value if sp exists 357 | * or {@code Collections.emptySet()} otherwise 358 | */ 359 | public Set getStringSet(@NonNull final String key) { 360 | return getStringSet(key, Collections.emptySet()); 361 | } 362 | 363 | /** 364 | * Return the set of string value in sp. 365 | * 366 | * @param key The key of sp. 367 | * @param defaultValue The default value if the sp doesn't exist. 368 | * @return the set of string value if sp exists or {@code defaultValue} otherwise 369 | */ 370 | public Set getStringSet(@NonNull final String key, 371 | final Set defaultValue) { 372 | return sp.getStringSet(key, defaultValue); 373 | } 374 | 375 | /** 376 | * Return all values in sp. 377 | * 378 | * @return all values in sp 379 | */ 380 | public Map getAll() { 381 | return sp.getAll(); 382 | } 383 | 384 | /** 385 | * Return whether the sp contains the preference. 386 | * 387 | * @param key The key of sp. 388 | * @return {@code true}: yes
{@code false}: no 389 | */ 390 | public boolean contains(@NonNull final String key) { 391 | return sp.contains(key); 392 | } 393 | 394 | /** 395 | * Remove the preference in sp. 396 | * 397 | * @param key The key of sp. 398 | */ 399 | public void remove(@NonNull final String key) { 400 | remove(key, false); 401 | } 402 | 403 | /** 404 | * Remove the preference in sp. 405 | * 406 | * @param key The key of sp. 407 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 408 | * false to use {@link SharedPreferences.Editor#apply()} 409 | */ 410 | public void remove(@NonNull final String key, final boolean isCommit) { 411 | if (isCommit) { 412 | sp.edit().remove(key).commit(); 413 | } else { 414 | sp.edit().remove(key).apply(); 415 | } 416 | } 417 | 418 | /** 419 | * Remove all preferences in sp. 420 | */ 421 | public void clear() { 422 | clear(false); 423 | } 424 | 425 | /** 426 | * Remove all preferences in sp. 427 | * 428 | * @param isCommit True to use {@link SharedPreferences.Editor#commit()}, 429 | * false to use {@link SharedPreferences.Editor#apply()} 430 | */ 431 | public void clear(final boolean isCommit) { 432 | if (isCommit) { 433 | sp.edit().clear().commit(); 434 | } else { 435 | sp.edit().clear().apply(); 436 | } 437 | } 438 | 439 | private static boolean isSpace(final String s) { 440 | if (s == null) return true; 441 | for (int i = 0, len = s.length(); i < len; ++i) { 442 | if (!Character.isWhitespace(s.charAt(i))) { 443 | return false; 444 | } 445 | } 446 | return true; 447 | } 448 | } 449 | -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/SplashActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.os.Handler 6 | import android.util.TypedValue 7 | import androidx.appcompat.app.AppCompatActivity 8 | import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen 9 | import com.madchan.supportandroid12.appSplashScreens.AppSplashScreensActivity 10 | import com.madchan.supportandroid12.appSplashScreens.AppStartupStateMachine 11 | import com.madchan.supportandroid12.databinding.ActivitySplashBinding 12 | 13 | 14 | class SplashActivity : AppCompatActivity() { 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | val splashScreen = installSplashScreen() 17 | 18 | super.onCreate(savedInstanceState) 19 | 20 | val binding = ActivitySplashBinding.inflate(layoutInflater) 21 | setContentView(binding.root) 22 | 23 | val outValue = TypedValue() 24 | theme.resolveAttribute(androidx.core.splashscreen.R.attr.windowSplashScreenAnimatedIcon, outValue, true) 25 | if(R.color.transparent == outValue.resourceId) { 26 | AppStartupStateMachine.save(AppStartupStateMachine.current().nextState()) 27 | } else { 28 | // 验证常规方案请把以下一行取消注释,这样的话系统启动画面会持续覆盖原有的闪屏页, 29 | // 直到开始显示广告页 30 | // splashScreen.setKeepOnScreenCondition { 31 | // AppStartupStateMachine.save(AppStartupStateMachine.current().nextState()) 32 | // true 33 | // } 34 | } 35 | 36 | Handler(mainLooper).postDelayed({ 37 | splashScreen.setKeepOnScreenCondition { false } 38 | binding.root.setBackgroundColor(resources.getColor(R.color.teal_700)) 39 | binding.textView.text = "一个无情无义的广告页" 40 | }, 2000) 41 | 42 | Handler(mainLooper).postDelayed({ 43 | 44 | if(AppStartupStateMachine.END == AppStartupStateMachine.current()){ 45 | startActivity(Intent(this, AppSplashScreensActivity::class.java)) 46 | } else { 47 | startActivity(Intent(this, MainActivity::class.java)) 48 | } 49 | 50 | finish() 51 | }, 4000) 52 | } 53 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/SupportAndroid12Application.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12 2 | 3 | import android.app.Application 4 | import android.content.Context 5 | 6 | class SupportAndroid12Application : Application() { 7 | 8 | companion object { 9 | lateinit var appContext: Context 10 | } 11 | 12 | override fun onCreate() { 13 | super.onCreate() 14 | appContext = applicationContext 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/appSplashScreens/AppSplashScreensActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.appSplashScreens 2 | 3 | import android.content.Intent 4 | import android.os.Bundle 5 | import android.view.View 6 | import androidx.appcompat.app.AppCompatActivity 7 | import androidx.lifecycle.MutableLiveData 8 | import com.madchan.supportandroid12.MainActivity 9 | import com.madchan.supportandroid12.databinding.ActivityAppSplashScreensBinding 10 | 11 | class AppSplashScreensActivity : AppCompatActivity() { 12 | 13 | lateinit var binding: ActivityAppSplashScreensBinding 14 | 15 | private val stateMachineLD = MutableLiveData(AppStartupStateMachine.current()) 16 | 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | binding = ActivityAppSplashScreensBinding.inflate(layoutInflater) 20 | setContentView(binding.root) 21 | 22 | addStateMachineObserver() 23 | } 24 | 25 | private fun addStateMachineObserver() { 26 | stateMachineLD.observe(this) { 27 | binding.textView.text = 28 | when (it) { 29 | AppStartupStateMachine.START -> "如你所见,从Android 12开始,系统为我们的App加上了一个默认的启动画面,该启动画面默认情况下包含windowBackground所设置的主题色和Launcher图标这2个元素。\n\n接下来,有两种适配的方案供你选择,你可请选择其中一种预览一下适配效果:" 30 | AppStartupStateMachine.PENDING_TO_SET_ICON_TRANSPARENT -> "懒人改变世界!这个方案很简单,请你把AndroidManifest中SplashActivity的主题改为Theme.App.Starting.Simple。\n\n该主题把默认启动画面中的图标改成了透明的颜色,因此只会显示背景色,是最简单的适配方案。改好后请重新运行。" 31 | AppStartupStateMachine.PENDING_TO_USE_SPLASH_SCREEN_API -> "赞!敢于选择更困难的路,接下来,请你把AndroidManifest中SplashActivity的主题改回Theme.App.Starting.Normal(如果前面有改的话),并将SplashActivity.kt中被注释的那条语句恢复,该语句会让默认启动画面覆盖原先的启动页,直到广告页才重新开始显示。改好后请重新运行。" 32 | AppStartupStateMachine.END -> "验证结束,如Demo演示有问题,可上GitHub上提issue,谢谢~\n\n如果想预览另一个方案的效果,可继续选择另外一个方案。" 33 | } 34 | AppStartupStateMachine.save(it) 35 | } 36 | } 37 | 38 | fun pendingToSetIconTransparent(view: View) { 39 | stateMachineLD.value = stateMachineLD.value?.nextState(SCHEME_SET_ICON_TRANSPARENT) 40 | } 41 | 42 | fun pendingToUseSplashScreenApi(view: View) { 43 | stateMachineLD.value = stateMachineLD.value?.nextState(SCHEME_USE_SPLASH_SCREEN_API) 44 | } 45 | 46 | fun testOtherChange(view: View) { 47 | AppStartupStateMachine.clear() 48 | startActivity(Intent(this, MainActivity::class.java)) 49 | finish() 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/appSplashScreens/AppSplashScreensStateMachine.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.appSplashScreens 2 | 3 | import com.madchan.supportandroid12.SPUtils 4 | import com.madchan.supportandroid12.SupportAndroid12Application.Companion.appContext 5 | 6 | const val SCHEME_SET_ICON_TRANSPARENT = 0 7 | const val SCHEME_USE_SPLASH_SCREEN_API = 1 8 | 9 | enum class AppStartupStateMachine { 10 | 11 | START { 12 | override fun nextState(scheme: Int?): AppStartupStateMachine { 13 | return when (scheme) { 14 | SCHEME_SET_ICON_TRANSPARENT -> PENDING_TO_SET_ICON_TRANSPARENT 15 | SCHEME_USE_SPLASH_SCREEN_API -> PENDING_TO_USE_SPLASH_SCREEN_API 16 | else -> this 17 | } 18 | } 19 | }, 20 | PENDING_TO_SET_ICON_TRANSPARENT { 21 | override fun nextState(scheme: Int?) = END 22 | } 23 | , 24 | PENDING_TO_USE_SPLASH_SCREEN_API { 25 | override fun nextState(scheme: Int?) = END 26 | }, 27 | END { 28 | override fun nextState(scheme: Int?): AppStartupStateMachine { 29 | return when (scheme) { 30 | SCHEME_SET_ICON_TRANSPARENT -> PENDING_TO_SET_ICON_TRANSPARENT 31 | SCHEME_USE_SPLASH_SCREEN_API -> PENDING_TO_USE_SPLASH_SCREEN_API 32 | else -> this 33 | } 34 | } 35 | } 36 | ; 37 | 38 | abstract fun nextState(scheme: Int? = null): AppStartupStateMachine 39 | 40 | companion object { 41 | private const val KEY_CURRENT_STATE = "app_startup_current_state" 42 | 43 | fun current(): AppStartupStateMachine { 44 | val value = SPUtils.getInstance(appContext).getString(KEY_CURRENT_STATE) 45 | return if (value.isNullOrBlank()) { START } else valueOf(value) 46 | } 47 | 48 | fun save(stateMachine: AppStartupStateMachine) { 49 | SPUtils.getInstance(appContext).put(KEY_CURRENT_STATE, stateMachine.name, true) 50 | } 51 | 52 | fun clear() { 53 | SPUtils.getInstance(appContext).clear(true) 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/approximateLocation/ApproximateLocationActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.approximateLocation 2 | 3 | import android.Manifest 4 | import android.content.pm.PackageManager 5 | import android.os.Build 6 | import android.os.Bundle 7 | import android.view.View 8 | import android.widget.Toast 9 | import androidx.appcompat.app.AppCompatActivity 10 | import com.madchan.supportandroid12.databinding.ActivityApproximateLocationBinding 11 | 12 | class ApproximateLocationActivity : AppCompatActivity() { 13 | 14 | lateinit var binding: ActivityApproximateLocationBinding 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | binding = ActivityApproximateLocationBinding.inflate(layoutInflater) 19 | setContentView(binding.root) 20 | } 21 | 22 | fun requestFineLocation(view: View) { 23 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 24 | requestPermissions( 25 | arrayOf( 26 | Manifest.permission.ACCESS_COARSE_LOCATION, 27 | Manifest.permission.ACCESS_FINE_LOCATION 28 | ), 1 29 | ) 30 | } 31 | } 32 | 33 | override fun onRequestPermissionsResult( 34 | requestCode: Int, 35 | permissions: Array, 36 | grantResults: IntArray 37 | ) { 38 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 39 | when (requestCode) { 40 | 1 -> { 41 | if ((grantResults.isNotEmpty() && 42 | grantResults[0] == PackageManager.PERMISSION_GRANTED) 43 | ) { 44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 45 | runOnUiThread { 46 | if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 47 | Toast.makeText(this, "确切位置权限已获得", Toast.LENGTH_LONG).show() 48 | binding.textView.text = "验证结束,如Demo演示有问题,可上GitHub上提issue,谢谢~" 49 | } else { 50 | Toast.makeText(this, "大致位置权限已获得", Toast.LENGTH_LONG).show() 51 | binding.textView.text = "现在,请尝试再次点击【请求确切位置】,系统将弹出权限对话框请求升级到确切位置" 52 | } 53 | } 54 | } 55 | } else { 56 | 57 | } 58 | } 59 | } 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/customNotification/CustomNotificationActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.customNotification 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.NotificationChannel 5 | import android.app.NotificationManager 6 | import android.os.Build 7 | import android.os.Bundle 8 | import android.view.View 9 | import android.widget.RemoteViews 10 | import androidx.appcompat.app.AppCompatActivity 11 | import androidx.core.app.NotificationCompat 12 | import com.madchan.supportandroid12.R 13 | import com.madchan.supportandroid12.databinding.ActivityCustomNotificationBinding 14 | 15 | class CustomNotificationActivity : AppCompatActivity() { 16 | 17 | lateinit var binding: ActivityCustomNotificationBinding 18 | 19 | override fun onCreate(savedInstanceState: Bundle?) { 20 | super.onCreate(savedInstanceState) 21 | binding = ActivityCustomNotificationBinding.inflate(layoutInflater) 22 | setContentView(binding.root) 23 | } 24 | 25 | @SuppressLint("RemoteViewLayout") 26 | fun notifyCustomNotification(view: View) { 27 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 28 | val mChannel = NotificationChannel("CHANNEL_ID", "name", NotificationManager.IMPORTANCE_HIGH) 29 | mChannel.description = "descriptionText" 30 | val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager 31 | notificationManager.createNotificationChannel(mChannel) 32 | 33 | // Get the layouts to use in the custom notification 34 | val notificationLayout = RemoteViews(packageName, R.layout.notification_small) 35 | val notificationLayoutExpanded = RemoteViews(packageName, R.layout.notification_large) 36 | 37 | // Apply the layouts to the notification 38 | val notification = NotificationCompat.Builder(this, "CHANNEL_ID") 39 | .setSmallIcon(R.drawable.ic_launcher_foreground) 40 | .setStyle(NotificationCompat.DecoratedCustomViewStyle()) 41 | .setCustomContentView(notificationLayout) 42 | .setCustomBigContentView(notificationLayoutExpanded) 43 | .build() 44 | 45 | notificationManager.notify(1, notification) 46 | 47 | binding.textView.text = "验证结束,如Demo演示有问题,可上GitHub上提issue,谢谢~" 48 | } 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/exactAlarmPermission/ExactAlarmPermissionActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.exactAlarmPermission 2 | 3 | import android.app.AlarmManager 4 | import android.app.AlarmManager.AlarmClockInfo 5 | import android.app.PendingIntent 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.net.Uri 9 | import android.os.Build 10 | import android.os.Bundle 11 | import android.os.SystemClock 12 | import android.provider.Settings 13 | import android.view.View 14 | import androidx.appcompat.app.AppCompatActivity 15 | import androidx.lifecycle.MutableLiveData 16 | import com.madchan.supportandroid12.databinding.ActivityExactAlarmPermissionBinding 17 | import java.util.* 18 | 19 | class ExactAlarmPermissionActivity : AppCompatActivity() { 20 | 21 | lateinit var binding: ActivityExactAlarmPermissionBinding 22 | 23 | private val stateMachineLD = MutableLiveData(ExactAlarmPermissionStateMachine.current()) 24 | 25 | override fun onCreate(savedInstanceState: Bundle?) { 26 | super.onCreate(savedInstanceState) 27 | binding = ActivityExactAlarmPermissionBinding.inflate(layoutInflater) 28 | setContentView(binding.root) 29 | 30 | addStateMachineObserver() 31 | 32 | if(stateMachineLD.value != ExactAlarmPermissionStateMachine.START) { 33 | stateMachineLD.value = stateMachineLD.value?.nextState() 34 | } 35 | } 36 | 37 | override fun onRestart() { 38 | super.onRestart() 39 | stateMachineLD.value = stateMachineLD.value?.nextState() 40 | } 41 | 42 | private fun addStateMachineObserver() { 43 | stateMachineLD.observe(this) { 44 | binding.textView.text = 45 | when (it) { 46 | ExactAlarmPermissionStateMachine.START -> "点击任一【以XXX方式设置闹钟】后,应用会崩溃,请关注Logcat的Error级别信息,看是否显示了一下消息:\\nCaused by: java.lang.SecurityException: Caller com.madchan.supportandroid12 needs to hold android.permission.SCHEDULE_EXACT_ALARM to set exact alarms." 47 | ExactAlarmPermissionStateMachine.CRASH_FOR_NO_DECLARE_PERMISSION -> "下一步,请将AndroidManifest.xml中被注释的SCHEDULE_EXACT_ALARM权限声明恢复后,重新运行,并重新点击。" 48 | ExactAlarmPermissionStateMachine.DECLARED_PERMISSION -> "现在,请重新点击【以XXX方式设置闹钟】,验证应用是否还会崩溃" 49 | ExactAlarmPermissionStateMachine.READY_TO_FORBIT_PERMISSION -> "恭喜成功,接下来,请点击【打开闹钟和提醒权限授权页面】关闭本应用的权限,模拟用户主动关闭权限的行为" 50 | ExactAlarmPermissionStateMachine.FORBITED_PERMISSION -> "此时,如果再次点击【以XXX方式设置闹钟】,应用还是会崩溃" 51 | ExactAlarmPermissionStateMachine.READY_TO_REQUIRE_PERMISSION -> "下一步,请点击【打开闹钟和提醒权限授权页面】重新开启本应用的权限" 52 | ExactAlarmPermissionStateMachine.REQUIRED_PERMISSION -> "现在,请重新点击【以XXX方式设置闹钟】,验证应用是否还会崩溃" 53 | ExactAlarmPermissionStateMachine.END -> "验证结束,如Demo演示有问题,可上GitHub上提issue,谢谢~" 54 | } 55 | ExactAlarmPermissionStateMachine.save(it) 56 | } 57 | } 58 | 59 | fun alarmBySetAlarmClock(view: View) { 60 | stateMachineLD.value = stateMachineLD.value?.nextState() 61 | 62 | val alarmManager = getSystemService(Context.ALARM_SERVICE) as? AlarmManager 63 | val alarmIntent = Intent(this, ExactAlarmPermissionReceiver::class.java).let { intent -> 64 | PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) 65 | } 66 | alarmManager?.setAlarmClock( 67 | AlarmClockInfo(Date().time + 1000, alarmIntent), 68 | alarmIntent 69 | ) 70 | } 71 | 72 | fun alarmBySetExact(view: View) { 73 | stateMachineLD.value = stateMachineLD.value?.nextState() 74 | 75 | val alarmManager = getSystemService(Context.ALARM_SERVICE) as? AlarmManager 76 | val alarmIntent = Intent(this, ExactAlarmPermissionReceiver::class.java).let { intent -> 77 | PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) 78 | } 79 | alarmManager?.setExact( 80 | AlarmManager.ELAPSED_REALTIME_WAKEUP, 81 | SystemClock.elapsedRealtime() + 1000, alarmIntent 82 | ) 83 | } 84 | 85 | fun alarmBySetExactAndAllowWhileIdle(view: View) { 86 | stateMachineLD.value = stateMachineLD.value?.nextState() 87 | 88 | val alarmManager = getSystemService(Context.ALARM_SERVICE) as? AlarmManager 89 | val alarmIntent = Intent(this, ExactAlarmPermissionReceiver::class.java).let { intent -> 90 | PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) 91 | } 92 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 93 | alarmManager?.setExactAndAllowWhileIdle( 94 | AlarmManager.ELAPSED_REALTIME_WAKEUP, 95 | SystemClock.elapsedRealtime() + 1000, alarmIntent 96 | ) 97 | } 98 | } 99 | 100 | fun requireAlarmPermission(view: View) { 101 | val uri = Uri.parse("package:$packageName") 102 | val i = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, uri) 103 | startActivity(i) 104 | } 105 | 106 | 107 | 108 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/exactAlarmPermission/ExactAlarmPermissionReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.exactAlarmPermission 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import android.widget.Toast 7 | 8 | class ExactAlarmPermissionReceiver : BroadcastReceiver() { 9 | 10 | override fun onReceive(context: Context?, p1: Intent?) { 11 | Toast.makeText(context, "通过闹钟开启了广播", Toast.LENGTH_LONG).show() 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/exactAlarmPermission/ExactAlarmPermissionStateMachine.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.exactAlarmPermission 2 | 3 | import com.madchan.supportandroid12.SPUtils 4 | import com.madchan.supportandroid12.SupportAndroid12Application.Companion.appContext 5 | import com.madchan.supportandroid12.hasDeclarePermission 6 | import com.madchan.supportandroid12.hasRequirePermission 7 | 8 | enum class ExactAlarmPermissionStateMachine { 9 | 10 | START { 11 | override fun nextState() = CRASH_FOR_NO_DECLARE_PERMISSION 12 | }, 13 | CRASH_FOR_NO_DECLARE_PERMISSION { 14 | override fun nextState() = 15 | if (hasDeclarePermission(appContext)) DECLARED_PERMISSION else this 16 | }, 17 | DECLARED_PERMISSION { 18 | override fun nextState() = READY_TO_FORBIT_PERMISSION 19 | }, 20 | READY_TO_FORBIT_PERMISSION { 21 | override fun nextState() = if (!hasRequirePermission(appContext)) FORBITED_PERMISSION else this 22 | }, 23 | FORBITED_PERMISSION { 24 | override fun nextState() = READY_TO_REQUIRE_PERMISSION 25 | }, 26 | READY_TO_REQUIRE_PERMISSION { 27 | override fun nextState() = 28 | if (hasRequirePermission(appContext)) REQUIRED_PERMISSION else this 29 | }, 30 | REQUIRED_PERMISSION { 31 | override fun nextState() = END 32 | }, 33 | END { 34 | override fun nextState() = this 35 | } 36 | ; 37 | 38 | abstract fun nextState(): ExactAlarmPermissionStateMachine 39 | 40 | companion object { 41 | private const val KEY_CURRENT_STATE = "alarm_current_state" 42 | 43 | fun current(): ExactAlarmPermissionStateMachine { 44 | val value = SPUtils.getInstance(appContext).getString(KEY_CURRENT_STATE) 45 | return if (value.isNullOrBlank()) { START } else valueOf(value) 46 | } 47 | 48 | fun save(stateMachine: ExactAlarmPermissionStateMachine) { 49 | SPUtils.getInstance(appContext).put(KEY_CURRENT_STATE, stateMachine.name, true) 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/foregroundServiceLimit/ForegroundServiceLimitActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.foregroundServiceLimit 2 | 3 | import android.content.Intent 4 | import android.os.Build 5 | import android.os.Bundle 6 | import android.os.Handler 7 | import android.view.View 8 | import androidx.appcompat.app.AppCompatActivity 9 | import com.madchan.supportandroid12.R 10 | 11 | class ForegroundServiceLimitActivity : AppCompatActivity() { 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | setContentView(R.layout.activity_limit_foreground_service) 16 | } 17 | 18 | fun startForegroundService(view: View) { 19 | moveTaskToBack(false) 20 | Handler(mainLooper).postDelayed({ 21 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 22 | val intent = Intent(this, ForegroundServiceLimitService::class.java) // Build the intent for the service 23 | startForegroundService(intent) 24 | } 25 | }, 10000) 26 | } 27 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/foregroundServiceLimit/ForegroundServiceLimitService.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.foregroundServiceLimit 2 | 3 | import android.app.* 4 | import android.app.NotificationManager.IMPORTANCE_HIGH 5 | import android.content.Intent 6 | import android.os.Build 7 | import android.os.IBinder 8 | import androidx.core.app.NotificationCompat 9 | import com.madchan.supportandroid12.MainActivity 10 | 11 | class ForegroundServiceLimitService : Service() { 12 | 13 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 14 | val pendingIntent: PendingIntent = 15 | Intent(this, MainActivity::class.java).let { notificationIntent -> 16 | PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE) 17 | } 18 | 19 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 20 | val mChannel = NotificationChannel("CHANNEL_ID", "name", IMPORTANCE_HIGH) 21 | mChannel.description = "descriptionText" 22 | val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager 23 | notificationManager.createNotificationChannel(mChannel) 24 | 25 | val notification: Notification = NotificationCompat.Builder(this, "CHANNEL_ID") 26 | .setContentTitle("ContentTitle") 27 | .setContentText("ContentText") 28 | .setContentIntent(pendingIntent) 29 | .build() 30 | 31 | // Notification ID cannot be 0. 32 | startForeground(1, notification) 33 | } 34 | 35 | return super.onStartCommand(intent, flags, startId) 36 | } 37 | 38 | override fun onBind(intent: Intent): IBinder? = null 39 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/notificationTrampolineLimit/NotificationTrampolineLimitActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.notificationTrampolineLimit 2 | 3 | import android.app.Notification 4 | import android.app.NotificationChannel 5 | import android.app.NotificationManager 6 | import android.app.PendingIntent 7 | import android.content.Intent 8 | import android.os.Build 9 | import android.os.Bundle 10 | import android.os.Handler 11 | import android.view.View 12 | import androidx.appcompat.app.AppCompatActivity 13 | import androidx.core.app.NotificationCompat 14 | import com.madchan.supportandroid12.R 15 | 16 | class NotificationTrampolineLimitActivity : AppCompatActivity() { 17 | 18 | override fun onCreate(savedInstanceState: Bundle?) { 19 | super.onCreate(savedInstanceState) 20 | setContentView(R.layout.activity_notification_trampoline_limit) 21 | } 22 | 23 | fun notificationToStartService(view: View) { 24 | moveTaskToBack(false) 25 | 26 | Handler(mainLooper).postDelayed({ 27 | val pendingIntent: PendingIntent = 28 | Intent(this, NotificationTrampolineLimitService::class.java).let { notificationIntent -> 29 | PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE) 30 | } 31 | 32 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 33 | val mChannel = NotificationChannel("CHANNEL_ID", "name", NotificationManager.IMPORTANCE_HIGH) 34 | mChannel.description = "descriptionText" 35 | val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager 36 | notificationManager.createNotificationChannel(mChannel) 37 | 38 | val notification: Notification = NotificationCompat.Builder(this, "CHANNEL_ID") 39 | .setContentTitle("notificationToStartService") 40 | .setContentText("ContentText") 41 | .setContentIntent(pendingIntent) 42 | .setSmallIcon(R.drawable.ic_launcher_foreground) 43 | .build() 44 | 45 | notificationManager.notify(0, notification) 46 | } 47 | }, 3000) 48 | } 49 | 50 | fun notificationToStartBroadcastReceiver(view: View) { 51 | moveTaskToBack(false) 52 | 53 | Handler(mainLooper).postDelayed({ 54 | val pendingIntent: PendingIntent = 55 | Intent(this, NotificationTrampolineLimitReceiver::class.java).let { notificationIntent -> 56 | PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE) 57 | } 58 | 59 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 60 | val mChannel = NotificationChannel("CHANNEL_ID", "name", NotificationManager.IMPORTANCE_HIGH) 61 | mChannel.description = "descriptionText" 62 | val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager 63 | notificationManager.createNotificationChannel(mChannel) 64 | 65 | val notification: Notification = NotificationCompat.Builder(this, "CHANNEL_ID") 66 | .setContentTitle("notificationToStartBroadcastReceiver") 67 | .setContentText("ContentText") 68 | .setContentIntent(pendingIntent) 69 | .setSmallIcon(R.drawable.ic_launcher_foreground) 70 | .build() 71 | 72 | notificationManager.notify(1, notification) 73 | } 74 | }, 3000) 75 | 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/notificationTrampolineLimit/NotificationTrampolineLimitReceiver.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.notificationTrampolineLimit 2 | 3 | import android.content.BroadcastReceiver 4 | import android.content.Context 5 | import android.content.Intent 6 | import com.madchan.supportandroid12.MainActivity 7 | 8 | class NotificationTrampolineLimitReceiver : BroadcastReceiver() { 9 | 10 | override fun onReceive(context: Context, intent: Intent) { 11 | context.startActivity(Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }) 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/notificationTrampolineLimit/NotificationTrampolineLimitService.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.notificationTrampolineLimit 2 | 3 | import android.app.Service 4 | import android.content.Intent 5 | import android.os.IBinder 6 | import com.madchan.supportandroid12.MainActivity 7 | 8 | class NotificationTrampolineLimitService : Service() { 9 | 10 | override fun onStartCommand(intent: Intent?, serviceFlags: Int, startId: Int): Int { 11 | startActivity(Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK }) 12 | return super.onStartCommand(intent, serviceFlags, startId) 13 | } 14 | 15 | override fun onBind(intent: Intent): IBinder? = null 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/pendingIntentsMutability/PendingIntentsMutabilityActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.pendingIntentsMutability 2 | 3 | import android.app.Notification 4 | import android.app.NotificationChannel 5 | import android.app.NotificationManager 6 | import android.app.PendingIntent 7 | import android.content.Intent 8 | import android.os.Build 9 | import android.os.Bundle 10 | import android.view.View 11 | import androidx.appcompat.app.AppCompatActivity 12 | import androidx.core.app.NotificationCompat 13 | import com.madchan.supportandroid12.MainActivity 14 | import com.madchan.supportandroid12.databinding.ActivityPendingIntentsMutabilityBinding 15 | import com.madchan.supportandroid12.databinding.ActivitySaferComponentExportingBinding 16 | 17 | class PendingIntentsMutabilityActivity : AppCompatActivity() { 18 | 19 | lateinit var binding: ActivityPendingIntentsMutabilityBinding 20 | 21 | override fun onCreate(savedInstanceState: Bundle?) { 22 | super.onCreate(savedInstanceState) 23 | binding = ActivityPendingIntentsMutabilityBinding.inflate(layoutInflater) 24 | setContentView(binding.root) 25 | } 26 | 27 | fun pendingIntentsMutability(view: View) { 28 | val pendingIntent: PendingIntent = 29 | Intent(this, MainActivity::class.java).let { notificationIntent -> 30 | PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) 31 | } 32 | 33 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 34 | val mChannel = NotificationChannel("CHANNEL_ID", "name", NotificationManager.IMPORTANCE_HIGH) 35 | mChannel.description = "descriptionText" 36 | val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager 37 | notificationManager.createNotificationChannel(mChannel) 38 | 39 | val notification: Notification = NotificationCompat.Builder(this, "CHANNEL_ID") 40 | .setContentTitle("ContentTitle") 41 | .setContentText("ContentText") 42 | .setContentIntent(pendingIntent) 43 | .build() 44 | 45 | notificationManager.notify(1, notification) 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/saferComponentExporting/SaferComponentExportingActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.saferComponentExporting 2 | 3 | import android.os.Bundle 4 | import androidx.appcompat.app.AppCompatActivity 5 | import com.madchan.supportandroid12.databinding.ActivitySaferComponentExportingBinding 6 | 7 | class SaferComponentExportingActivity : AppCompatActivity() { 8 | 9 | lateinit var binding: ActivitySaferComponentExportingBinding 10 | 11 | override fun onCreate(savedInstanceState: Bundle?) { 12 | super.onCreate(savedInstanceState) 13 | binding = ActivitySaferComponentExportingBinding.inflate(layoutInflater) 14 | setContentView(binding.root) 15 | } 16 | } -------------------------------------------------------------------------------- /app/src/main/java/com/madchan/supportandroid12/toggleMicAndCamera/ToggleMicActivity.kt: -------------------------------------------------------------------------------- 1 | package com.madchan.supportandroid12.toggleMicAndCamera 2 | 3 | import android.content.Intent 4 | import android.content.pm.PackageManager 5 | import android.media.MediaRecorder 6 | import android.os.Build 7 | import android.os.Bundle 8 | import android.os.Handler 9 | import android.view.View 10 | import androidx.appcompat.app.AppCompatActivity 11 | import androidx.core.content.FileProvider 12 | import com.madchan.supportandroid12.databinding.ActivityToggleMicBinding 13 | import java.io.File 14 | 15 | 16 | class ToggleMicActivity : AppCompatActivity() { 17 | 18 | lateinit var binding: ActivityToggleMicBinding 19 | var mediaRecorder: MediaRecorder? = null 20 | 21 | var audioFile: File? = null 22 | var startTimes = 0 23 | 24 | override fun onCreate(savedInstanceState: Bundle?) { 25 | super.onCreate(savedInstanceState) 26 | binding = ActivityToggleMicBinding.inflate(layoutInflater) 27 | setContentView(binding.root) 28 | } 29 | 30 | fun start(view: View) { 31 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 32 | requestPermissions(arrayOf(android.Manifest.permission.RECORD_AUDIO), 0) 33 | } 34 | } 35 | 36 | override fun onRequestPermissionsResult( 37 | requestCode: Int, 38 | permissions: Array, 39 | grantResults: IntArray 40 | ) { 41 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 42 | if(grantResults[0] == PackageManager.PERMISSION_GRANTED) { 43 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 44 | mediaRecorder = MediaRecorder().apply { 45 | setAudioSource(MediaRecorder.AudioSource.MIC) 46 | setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS) 47 | audioFile = File(cacheDir, "test.mp3") 48 | setOutputFile(audioFile) 49 | setAudioEncoder(MediaRecorder.AudioEncoder.AAC) 50 | 51 | prepare() 52 | start() 53 | 54 | startTimes++ 55 | } 56 | when { 57 | startTimes == 1 -> { 58 | binding.textView.text = "现在,请在状态栏下拉打开快捷设置菜单,关闭麦克风开关。\n\n若没找到,请点击快捷设置菜单右上角编辑按钮,将麦克风开关拖拽到菜单中。" 59 | Handler(mainLooper).postDelayed({ 60 | binding.textView.text = "若已关闭麦克风开关,状态栏中的标志应会消失。\n\n此时录音仍在持续,但输出会变为一段无声音频,可停止录音并聆听来验证。" 61 | }, 10 * 1000L) 62 | } 63 | startTimes > 1 -> binding.textView.text = "验证结束,如Demo演示有问题,可上GitHub上提issue,谢谢~" 64 | } 65 | } 66 | } 67 | } 68 | 69 | fun stop(view: View) { 70 | mediaRecorder?.stop() 71 | mediaRecorder?.release() 72 | 73 | binding.textView.text = "录音已停止,请选择合适应用验证录音的后半段是否变为静音。\n\n随后请重新开始录音,验证系统是否会重新提示开启麦克风开关。" 74 | 75 | audioFile?.let { 76 | val intent = Intent(Intent.ACTION_VIEW) 77 | intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK 78 | intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION 79 | intent.setDataAndType(FileProvider.getUriForFile(this, "$packageName.fileprovider",it), "audio/*") 80 | startActivity(intent) 81 | } 82 | 83 | } 84 | 85 | override fun finish() { 86 | stop(binding.stopBtn) 87 | super.finish() 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_app_splash_screens.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 17 | 18 | 28 | 29 |