Skip to content

Commit

Permalink
Fix crash after applying wallpaper
Browse files Browse the repository at this point in the history
  • Loading branch information
cvzi committed Jun 19, 2024
1 parent a25a63a commit be6e45c
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ class DarkWallpaperService : WallpaperService() {

private val self = WeakReference(this)
private lateinit var preferencesGlobal: Preferences
private lateinit var handler: Handler

private var engines: ArrayList<WeakReference<DarkWallpaperService.WallpaperEngine>> =
ArrayList()
Expand All @@ -189,6 +190,7 @@ class DarkWallpaperService : WallpaperService() {
keyguardService = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager

preferencesGlobal = Preferences(this, R.string.pref_file)
handler = Handler(Looper.getMainLooper())
}

override fun onDestroy() {
Expand All @@ -202,6 +204,7 @@ class DarkWallpaperService : WallpaperService() {
SERVICES.remove(self)
self.clear()
}
handler.removeCallbacksAndMessages(null)
super.onDestroy()
}

Expand Down Expand Up @@ -234,7 +237,7 @@ class DarkWallpaperService : WallpaperService() {
}
}
// Update all wallpapers after 3 seconds
Handler(Looper.getMainLooper()).postDelayed({
handler.postDelayed({
invalidate()
}, 3000)
}
Expand All @@ -261,7 +264,7 @@ class DarkWallpaperService : WallpaperService() {
private var invalid = true
private val self = WeakReference(this)
private var imageProvider: ImageProvider =
StaticDayAndNightProvider(WeakReference(this@DarkWallpaperService))
StaticDayAndNightProvider(this@DarkWallpaperService)

private var wallpaperImage: WallpaperImage? = null
private var isSecondaryDisplay = false
Expand Down Expand Up @@ -330,7 +333,6 @@ class DarkWallpaperService : WallpaperService() {
}

override fun onDestroy() {
imageProvider.weakContext.clear()
synchronized(engines) {
engines.remove(self)
}
Expand Down Expand Up @@ -380,7 +382,7 @@ class DarkWallpaperService : WallpaperService() {
onUnLockBroadcastReceiver = OnUnLockBroadcastReceiver()
}
onUnLockBroadcastReceiver?.register()
Handler(Looper.getMainLooper()).postDelayed({
handler.postDelayed({
// Check if the device was already unlocked before the broadcast receiver was ready
if (isLockScreen && !keyguardService.isDeviceLocked) {
// Device was already unlocked
Expand Down Expand Up @@ -478,9 +480,9 @@ class DarkWallpaperService : WallpaperService() {

override fun notifyColorsChanged() {
if (isPreview && !isLockScreen && fixedConfig && MainActivity.originalDesiredWidth > 0) {
Log.v(TAG, "notifyColorsChanged() blocked because: In-app preview")
Log.d(TAG, "notifyColorsChanged() blocked because: In-app preview")
} else if (isPreview && (desiredMinimumWidth < width || desiredMinimumHeight < height)) {
Log.v(TAG, "notifyColorsChanged() blocked because: Material you preview")
Log.d(TAG, "notifyColorsChanged() blocked because: Material you preview")
} else {
super.notifyColorsChanged()
}
Expand Down Expand Up @@ -524,7 +526,7 @@ class DarkWallpaperService : WallpaperService() {
}
hasZoom = true
if (visible && (abs(zoom - newZoom) > 0.04f || newZoom == 0f || newZoom == 1f)) {
Handler(Looper.getMainLooper()).post {
handler.post {
updateCanvas()
}
}
Expand Down Expand Up @@ -604,6 +606,9 @@ class DarkWallpaperService : WallpaperService() {
private val runnableComputeWallpaperColors = Runnable {
computeWallpaperColors()
}
private val runnableUpdate = Runnable {
update()
}

private fun computeWallpaperColors() {
val helper = calculateWallpaperColorsHelper ?: return
Expand Down Expand Up @@ -635,9 +640,10 @@ class DarkWallpaperService : WallpaperService() {
}
} else {
Log.d(TAG, "computeWallpaperColors() deferred")
Handler(Looper.getMainLooper()).postDelayed({
update()
}, 1000)
handler.apply {
removeCallbacks(runnableUpdate)
postDelayed(runnableUpdate, 1000)
}
}
}

Expand Down Expand Up @@ -871,7 +877,6 @@ class DarkWallpaperService : WallpaperService() {
)
}
} else {
Log.e(TAG, "No image file")
errorLoadingFile = "\uD83D\uDC81\uD83C\uDFFE\u200D♀ no image file️"
}
}
Expand Down Expand Up @@ -925,7 +930,7 @@ class DarkWallpaperService : WallpaperService() {
imageFile,
wallpaperImage?.customWallpaperColors
)
Handler(Looper.getMainLooper()).apply {
handler.apply {
removeCallbacks(runnableComputeWallpaperColors)
postDelayed(runnableComputeWallpaperColors, 200)
}
Expand Down Expand Up @@ -969,9 +974,10 @@ class DarkWallpaperService : WallpaperService() {
) {
blendImages = null
}
Handler(Looper.getMainLooper()).postDelayed({
update()
}, 50)
handler.apply {
removeCallbacks(runnableUpdate)
postDelayed(runnableUpdate, 50)
}
return WallpaperStatusLoadedBlending()
} else if (bm != null) {
return drawOnCanvasBitmap(canvas, bm)
Expand All @@ -992,9 +998,10 @@ class DarkWallpaperService : WallpaperService() {
getString(R.string.wallpaper_is_loading)
)
waitAnimation?.draw(canvas, errorLoadingFile)
Handler(Looper.getMainLooper()).postDelayed({
update()
}, 200)
handler.apply {
removeCallbacks(runnableUpdate)
postDelayed(runnableUpdate, 200)
}
return WallpaperStatusLoading()
}
return WallpaperStatusLoading()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import android.os.Environment
import android.util.Log
import java.io.File
import java.io.IOException
import java.lang.ref.WeakReference

/**
* All relevant properties of a Wallpaper
Expand All @@ -47,7 +46,7 @@ data class WallpaperImage(

const val IMAGEPROVIDERTAG = "ImageProvider"

abstract class ImageProvider(val weakContext: WeakReference<Context>) {
abstract class ImageProvider {
abstract fun get(
dayOrNight: DayOrNight,
isLockScreen: Boolean,
Expand All @@ -60,11 +59,11 @@ abstract class ImageProvider(val weakContext: WeakReference<Context>) {
): File
}

class StaticDayAndNightProvider(context: WeakReference<Context>) : ImageProvider(context) {
private val preferencesLockScreen: Preferences =
Preferences(context.get()!!, R.string.pref_file_lock_screen)
private val preferencesHomeScreen: Preferences =
Preferences(context.get()!!, R.string.pref_file)
class StaticDayAndNightProvider(val context: Context) : ImageProvider() {
private val preferencesLockScreen =
Preferences(context, R.string.pref_file_lock_screen)
private val preferencesHomeScreen =
Preferences(context, R.string.pref_file)

private fun dayFileName(isLockScreen: Boolean): String {
val currentPreferences = if (isLockScreen) preferencesLockScreen else preferencesHomeScreen
Expand All @@ -78,48 +77,44 @@ class StaticDayAndNightProvider(context: WeakReference<Context>) : ImageProvider

private fun dayFileName(isLockScreen: Boolean, isAnimated: Boolean): String {
return if (isAnimated) {
weakContext.get()!!
.getString(if (isLockScreen) R.string.file_name_gif_day_lock_wallpaper else R.string.file_name_gif_day_wallpaper)
context.getString(if (isLockScreen) R.string.file_name_gif_day_lock_wallpaper else R.string.file_name_gif_day_wallpaper)
} else {
weakContext.get()!!
.getString(if (isLockScreen) R.string.file_name_day_lock_wallpaper else R.string.file_name_day_wallpaper)
context.getString(if (isLockScreen) R.string.file_name_day_lock_wallpaper else R.string.file_name_day_wallpaper)
}
}

private fun nightFileName(isLockScreen: Boolean, isAnimated: Boolean): String {
return if (isAnimated) {
weakContext.get()!!
.getString(if (isLockScreen) R.string.file_name_gif_night_lock_wallpaper else R.string.file_name_gif_night_wallpaper)
context.getString(if (isLockScreen) R.string.file_name_gif_night_lock_wallpaper else R.string.file_name_gif_night_wallpaper)
} else {
weakContext.get()!!
.getString(if (isLockScreen) R.string.file_name_night_lock_wallpaper else R.string.file_name_night_wallpaper)
context.getString(if (isLockScreen) R.string.file_name_night_lock_wallpaper else R.string.file_name_night_wallpaper)
}
}

private fun dayFileLocation(isLockScreen: Boolean, isAnimated: Boolean): File {
return File(
weakContext.get()!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
dayFileName(isLockScreen, isAnimated)
)
}

private fun nightFileLocation(isLockScreen: Boolean, isAnimated: Boolean): File {
return File(
weakContext.get()!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
nightFileName(isLockScreen, isAnimated)
)
}

private fun dayFileLocation(isLockScreen: Boolean): File {
return File(
weakContext.get()!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
dayFileName(isLockScreen)
)
}

private fun nightFileLocation(isLockScreen: Boolean): File {
return File(
weakContext.get()!!.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
nightFileName(isLockScreen)
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
*/
package com.github.cvzi.darkmodewallpaper.activity

import android.Manifest
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
Expand Down Expand Up @@ -94,7 +94,6 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.lang.ref.WeakReference
import kotlin.math.exp
import kotlin.math.log
import kotlin.math.max
Expand All @@ -107,10 +106,6 @@ open class MainActivity : AppCompatActivity() {
private const val TAG = "MainActivity"
var originalDesiredWidth = -1
var originalDesiredHeight = -1
const val READ_WALLPAPER_PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE
const val WALLPAPER_EXPORT_PACKAGE = "com.github.cvzi.wallpaperexport"
const val WALLPAPER_EXPORT_FDROID =
"https://f-droid.org/packages/com.github.cvzi.wallpaperexport/"
}

protected lateinit var preferencesGlobal: Preferences
Expand Down Expand Up @@ -154,7 +149,7 @@ open class MainActivity : AppCompatActivity() {

setContentView(binding.root)

imageProvider = StaticDayAndNightProvider(WeakReference(this))
imageProvider = StaticDayAndNightProvider(this)

startForPickDayHomeScreenFile = registerForActivityResult(
dayOrNight = DAY, isLockScreen = false
Expand Down Expand Up @@ -1087,6 +1082,11 @@ open class MainActivity : AppCompatActivity() {
}, 500)
}

override fun onDestroy() {
Handler(Looper.getMainLooper()).removeCallbacksAndMessages(null)
super.onDestroy()
}

override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Expand Down Expand Up @@ -1221,8 +1221,8 @@ open class MainActivity : AppCompatActivity() {
}
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.safeDismiss()
if (checkSelfPermission(READ_WALLPAPER_PERMISSION) != PackageManager.PERMISSION_GRANTED) {
startForStoragePermission.launch(READ_WALLPAPER_PERMISSION)
if (checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
startForStoragePermission.launch(READ_EXTERNAL_STORAGE)
} else {
askImportWhichWallpaper()
}
Expand All @@ -1248,8 +1248,8 @@ open class MainActivity : AppCompatActivity() {
}
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.safeDismiss()
if (checkSelfPermission(READ_WALLPAPER_PERMISSION) != PackageManager.PERMISSION_GRANTED) {
startForStoragePermission.launch(READ_WALLPAPER_PERMISSION)
if (checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
startForStoragePermission.launch(READ_EXTERNAL_STORAGE)
} else {
selection.forEachIndexed { index, checked ->
if (checked) {
Expand Down Expand Up @@ -1297,7 +1297,7 @@ open class MainActivity : AppCompatActivity() {
object : Thread("saveFileFromUri") {
override fun run() {
var success = false
if (checkSelfPermission(READ_WALLPAPER_PERMISSION) == PackageManager.PERMISSION_GRANTED) {
if (checkSelfPermission(READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
wallpaperManager.drawable?.let {
success = storeFile(fileLocation, it)
}
Expand All @@ -1321,7 +1321,7 @@ open class MainActivity : AppCompatActivity() {
).show()
}
if (Build.VERSION.SDK_INT >= 33) {
revokeSelfPermissionOnKill(READ_WALLPAPER_PERMISSION)
revokeSelfPermissionOnKill(READ_EXTERNAL_STORAGE)
}
}
}
Expand Down Expand Up @@ -1360,18 +1360,19 @@ open class MainActivity : AppCompatActivity() {
private fun showWallpaperExportHint() {
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.wallpaper_import_dialog_title)
builder.setMessage("Permission to import wallpaper was denied. If you did not see a permission dialog to allow the permission, Android 13+ has denied the permission automatically.\n\nHowever you can export the current wallpaper with a separate app and then import the image to this app.\n\nGo to separate app?\n\nhttps://f-droid.org/packages/com.github.cvzi.wallpaperexport/")
builder.setMessage(R.string.wallpaper_import_denied)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.safeDismiss()

val intent = packageManager.getLaunchIntentForPackage(WALLPAPER_EXPORT_PACKAGE)
val wallpaperExportPackageName = getString(R.string.wallpaper_export_package_name)
val wallpaperExportFDroidUrl = getString(R.string.wallpaper_export_fdroid_url)
val intent = packageManager.getLaunchIntentForPackage(wallpaperExportPackageName)
if (intent?.resolveActivity(packageManager) != null) {
intent.addFlags(FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
} else {
Intent(ACTION_VIEW, Uri.parse(WALLPAPER_EXPORT_FDROID)).apply {
Intent(ACTION_VIEW, Uri.parse(wallpaperExportFDroidUrl)).apply {
if (resolveActivity(packageManager) != null) {
startActivity(Intent.createChooser(this, WALLPAPER_EXPORT_FDROID))
startActivity(Intent.createChooser(this, wallpaperExportFDroidUrl))
} else {
Log.e(TAG, "showWallpaperExportHint: No browser installed")
}
Expand All @@ -1381,23 +1382,23 @@ open class MainActivity : AppCompatActivity() {
builder.setNegativeButton(android.R.string.cancel, null)
builder.show()
}
}

class ScrollingModeOnItemSelectedListener(
spinner: Spinner,
private val imageProvider: StaticDayAndNightProvider,
private val isDayOrNight: DayOrNight
) : AdapterView.OnItemSelectedListener {
init {
spinner.setSelection(imageProvider.getScrollingMode(isDayOrNight).ordinal)
}
inner class ScrollingModeOnItemSelectedListener(
spinner: Spinner,
private val imageProvider: StaticDayAndNightProvider,
private val isDayOrNight: DayOrNight
) : AdapterView.OnItemSelectedListener {
init {
spinner.setSelection(imageProvider.getScrollingMode(isDayOrNight).ordinal)
}

override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
imageProvider.setScrollingMode(isDayOrNight, ScrollingMode.entries[pos])
DarkWallpaperService.invalidate()
}
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
imageProvider.setScrollingMode(isDayOrNight, ScrollingMode.entries[pos])
DarkWallpaperService.invalidate()
}

override fun onNothingSelected(parent: AdapterView<*>) {
Log.d("Spinner", "onNothingSelected")
override fun onNothingSelected(parent: AdapterView<*>) {
Log.d("Spinner", "onNothingSelected")
}
}
}
Loading

0 comments on commit be6e45c

Please sign in to comment.