Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
tsynik committed Jun 2, 2022
1 parent 7ddd160 commit 4aad674
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 60 deletions.
5 changes: 3 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
<permission android:name="com.amazon.tv.leanbacklauncher.permission.MIGRATE_RECOMMENDATIONS_DATA" />

<application
android:name="com.amazon.tv.leanbacklauncher.App"
android:name="com.amazon.tv.leanbacklauncher.LauncherApp"
android:allowBackup="true"
android:banner="@drawable/banner_leanback"
android:hardwareAccelerated="true"
Expand All @@ -65,7 +65,8 @@
android:requestLegacyExternalStorage="true"
android:requiredForAllUsers="true"
android:supportsRtl="true"
android:theme="@style/LeanbackLauncherTheme">
android:theme="@style/LeanbackLauncherTheme"
tools:targetApi="n">
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import com.amazon.tv.leanbacklauncher.App
import com.amazon.tv.leanbacklauncher.BuildConfig
import com.amazon.tv.leanbacklauncher.LauncherApp
import com.amazon.tv.leanbacklauncher.R
import com.amazon.tv.leanbacklauncher.recommendations.NotificationsServiceV4
import java.util.*

object RowPreferences {
// private val TAG by lazy { if (BuildConfig.DEBUG) ("[*]" + javaClass.simpleName).take(21) else javaClass.simpleName }
Expand Down Expand Up @@ -360,7 +359,7 @@ object RowPreferences {
}

fun fixRowPrefs() {
val context = App.getContext()
val context = LauncherApp.getContext()
val pref = PreferenceManager.getDefaultSharedPreferences(context)
val list = listOf(
context.getString(R.string.pref_banner_focus_frame_color),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,16 @@ class NotificationListenerMonitor : Service() {
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val CHANNEL_ID = NotificationsServiceV4::class.qualifiedName.toString()
val CHANNEL_NAME = "LeanbackOnFire"
val NOTIFICATION_ID = 1111
val REQUEST_CODE = 0
val channelId = NotificationsServiceV4::class.qualifiedName.toString()
val channelName = "LeanbackOnFire"
val notificationId = 1111
val requestCode = 0

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel: NotificationChannel?
notificationChannel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH
channelId,
channelName, NotificationManager.IMPORTANCE_HIGH
).also {
it.enableLights(true)
it.lightColor = Color.RED
Expand All @@ -169,9 +170,9 @@ class NotificationListenerMonitor : Service() {
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(CHANNEL_NAME)
.setContentTitle(channelName)
.setContentText(resources.getString(R.string.notification_text))
if (Util.isAmazonDev(this))
builder.setLargeIcon(
Expand All @@ -188,14 +189,14 @@ class NotificationListenerMonitor : Service() {
}
val contentIntent = PendingIntent.getActivity(
this,
REQUEST_CODE,
requestCode,
notificationIntent,
flags
)
builder.setContentIntent(contentIntent)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(NOTIFICATION_ID, builder.build())
startForeground(NOTIFICATION_ID, builder.build())
manager.notify(notificationId, builder.build())
startForeground(notificationId, builder.build())
return START_STICKY
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class App : Application() {
class LauncherApp : Application() {
private var mNewBlacklistClient: NewBlacklistClient? = null
private var mOldBlacklistClient: OldBlacklistClient? = null

Expand Down Expand Up @@ -102,7 +102,7 @@ class App : Application() {

private inner class OldBlacklistClient(context: Context?) : RecommendationsClient(context) {
override fun onConnected(service: IRecommendationsService) {
synchronized(App::class.java) {
synchronized(LauncherApp::class.java) {
if (!sBlacklistMigrated) {
try {
val blacklist = service.blacklistedPackages
Expand Down Expand Up @@ -157,6 +157,7 @@ class App : Application() {
}
}

@Suppress("DEPRECATION")
fun isConnected(context: Context): Boolean {
val connectivityManager =
context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
Expand All @@ -180,7 +181,7 @@ class App : Application() {
primes.startCrashMonitor();
return;
}*/
Log.d(TAG, "PRIMES not enabled")
if (BuildConfig.DEBUG) Log.d(TAG, "PRIMES not enabled")
}

private fun demigrate() {
Expand Down
26 changes: 15 additions & 11 deletions app/src/main/java/com/amazon/tv/leanbacklauncher/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
}

private var mNotificationsView: NotificationRowView? = null
var mPackageReplacedReceiver: BroadcastReceiver = object : BroadcastReceiver() {
private var mPackageReplacedReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val packageName = intent?.data
packageName?.let {
Expand All @@ -220,7 +220,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
}
}

var mHomeRefreshReceiver: BroadcastReceiver = object : BroadcastReceiver() {
private var mHomeRefreshReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.getBooleanExtra("RefreshHome", false) == true) {
if (BuildConfig.DEBUG) Log.d(TAG, "RESTART HOME")
Expand Down Expand Up @@ -281,7 +281,8 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,

companion object {
const val PERMISSIONS_REQUEST_LOCATION = 99
val JSONFILE = App.getContext().cacheDir?.absolutePath + "/weather.json"
const val UNINSTALL_CODE = 321
val JSONFILE = LauncherApp.getContext().cacheDir?.absolutePath + "/weather.json"

fun isMediaKey(keyCode: Int): Boolean {
return when (keyCode) {
Expand Down Expand Up @@ -468,8 +469,8 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
loaderManager.initLoader(0, null, mSearchIconCallbacks)
loaderManager.initLoader(1, null, mSearchSuggestionsCallbacks)

// start notification listener
if (RowPreferences.areRecommendationsEnabled(this) && App.inForeground)
// start notification listener monitor
if (RowPreferences.areRecommendationsEnabled(this) && LauncherApp.inForeground)
startService(Intent(this, NotificationListenerMonitor::class.java))

// fix int options migrate
Expand Down Expand Up @@ -559,15 +560,16 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
val uninstallIntent =
Intent("android.intent.action.UNINSTALL_PACKAGE", Uri.parse("package:$packageName"))
uninstallIntent.putExtra("android.intent.extra.RETURN_RESULT", true)
startActivityForResult(uninstallIntent, 321)
startActivityForResult(uninstallIntent, UNINSTALL_CODE)
}
}

@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (RowPreferences.isWeatherEnabled(this))
localWeather?.onActivityResult(requestCode, resultCode, data)
if (requestCode == 321 && resultCode != 0) {
if (requestCode == UNINSTALL_CODE && resultCode != 0) {
if (resultCode == -1) {
editModeView?.uninstallComplete()
} else if (resultCode == 1) {
Expand All @@ -591,7 +593,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
recreate()
} else {
Log.i(TAG, "Not agree location permission")
App.toast(R.string.location_note, true)
LauncherApp.toast(R.string.location_note, true)
}
}
}
Expand Down Expand Up @@ -696,7 +698,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
}
}
} else
App.toast(R.string.user_location_warning, true)
LauncherApp.toast(R.string.user_location_warning, true)
}
}

Expand All @@ -711,7 +713,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,

override fun onFailure(exception: Throwable?) {
Log.e(TAG, "Weather fetching exception ${exception!!.message!!}")
App.toast("Weather error: ${exception!!.message!!}", true)
LauncherApp.toast("Weather error: ${exception!!.message!!}", true)
}
}
// only used when useCurrentLocation is true
Expand Down Expand Up @@ -1262,7 +1264,9 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
override fun onResume() {
var forceResort = true
var z = true

super.onResume()

if (isBackgroundVisibleBehind) {
//if (BuildConfig.DEBUG) Log.d(TAG, "onResume: BackgroundVisibleBehind")
z = false
Expand Down Expand Up @@ -1600,7 +1604,7 @@ class MainActivity : AppCompatActivity(), OnEditModeChangedListener,
}
}

fun startSettings() {
private fun startSettings() {
if (applicationContext.resources.getBoolean(R.bool.full_screen_settings_enabled)) {
val intent = Intent(this@MainActivity, LegacyHomeScreenSettingsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import androidx.core.content.res.ResourcesCompat
import androidx.leanback.app.GuidedStepSupportFragment
import androidx.leanback.widget.GuidanceStylist.Guidance
import androidx.leanback.widget.GuidedAction
import com.amazon.tv.leanbacklauncher.App
import com.amazon.tv.leanbacklauncher.BuildConfig
import com.amazon.tv.leanbacklauncher.LauncherApp
import com.amazon.tv.leanbacklauncher.R
import com.amazon.tv.leanbacklauncher.util.CSyncTask
import org.json.JSONException
Expand All @@ -20,14 +20,14 @@ import java.net.URL
import javax.net.ssl.HttpsURLConnection

class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {
private val RELEASES_LINK =
private val releasesLink =
"https://api.github.com/repos/tsynik/LeanbackLauncher/releases/latest"
private var DOWNLOAD_LINK: String? = null
private val ctx = App.getContext()
private var downloadLink: String? = null
private val ctx = LauncherApp.getContext()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GetInfo(RELEASES_LINK)
GetInfo(releasesLink)
}

override fun onCreateGuidance(savedInstanceState: Bundle?): Guidance {
Expand Down Expand Up @@ -57,7 +57,7 @@ class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {
if (assets != null) {
val firstAssets = assets.optJSONObject(0)
if (firstAssets.optString("content_type") == "application/vnd.android.package-archive") {
DOWNLOAD_LINK = firstAssets.optString("browser_download_url")
downloadLink = firstAssets.optString("browser_download_url")
}
}
val lastVersionDouble: Double = try {
Expand Down Expand Up @@ -102,8 +102,8 @@ class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {

override fun onGuidedActionClicked(action: GuidedAction) {
super.onGuidedActionClicked(action)
if (action.id == 3L && DOWNLOAD_LINK!!.isNotEmpty()) {
Download(DOWNLOAD_LINK, context?.externalCacheDir.toString())
if (action.id == 3L && downloadLink!!.isNotEmpty()) {
Download(downloadLink, context?.externalCacheDir.toString())
}
}

Expand Down Expand Up @@ -169,7 +169,7 @@ class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {
}

override fun doInBackground(vararg strings: String?): File? {
val BUFFER_SIZE = 4096
val bufferSize = 4096
val fileURL = strings[0]
val saveDir = strings[1]
var urlConnection: HttpsURLConnection? = null
Expand Down Expand Up @@ -206,7 +206,7 @@ class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {
// opens an output stream to save into file
val outputStream = FileOutputStream(saveFilePath)
var bytesRead: Int
val buffer = ByteArray(BUFFER_SIZE)
val buffer = ByteArray(bufferSize)
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
Expand All @@ -224,7 +224,7 @@ class LegacyUpdatePreferenceFragment : GuidedStepSupportFragment() {

override fun onPostExecute(f: File?) {
super.onPostExecute(f)
val context = App.getContext()
val context = LauncherApp.getContext()
val intent = Intent(Intent.ACTION_VIEW)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import androidx.preference.*
import com.amazon.tv.firetv.leanbacklauncher.apps.RowPreferences
import com.amazon.tv.firetv.leanbacklauncher.util.FireTVUtils
import com.amazon.tv.firetv.leanbacklauncher.util.SharedPreferencesUtil
import com.amazon.tv.leanbacklauncher.App
import com.amazon.tv.leanbacklauncher.BuildConfig
import com.amazon.tv.leanbacklauncher.LauncherApp
import com.amazon.tv.leanbacklauncher.MainActivity.Companion.JSONFILE
import com.amazon.tv.leanbacklauncher.R
import com.amazon.tv.leanbacklauncher.UpdateActivity
Expand Down Expand Up @@ -93,7 +93,7 @@ class SettingsFragment : LeanbackSettingsFragmentCompat() {
super.onStop()
if (needRestartHome) {
if (BuildConfig.DEBUG) Log.d(TAG, "onStop() send refresh HOME broadcast")
Util.refreshHome(App.getContext())
Util.refreshHome(LauncherApp.getContext())
}
}
}
Expand Down Expand Up @@ -152,7 +152,7 @@ class VersionPreferenceFragment : LeanbackPreferenceFragmentCompat() {
startActivity(Intent(activity, UpdateActivity::class.java))
else
withContext(Dispatchers.Main) {
App.toast(getString(R.string.update_no_updates))
LauncherApp.toast(getString(R.string.update_no_updates))
}
}
return true
Expand All @@ -174,7 +174,7 @@ class VersionPreferenceFragment : LeanbackPreferenceFragmentCompat() {
try {
startActivity(intent)
} catch (e: Exception) {
App.toast(R.string.failed_launch)
LauncherApp.toast(R.string.failed_launch)
}
}
}
Expand All @@ -184,7 +184,7 @@ class VersionPreferenceFragment : LeanbackPreferenceFragmentCompat() {
* The fragment that is defined in prefs.xml
*/
class HomePreferenceFragment : LeanbackPreferenceFragmentCompat() {
private val appContext = App.getContext()
private val appContext = LauncherApp.getContext()
private val sortingMode = AppsManager.getSavedSortingMode(appContext)
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Load the prefs from an XML resource
Expand Down Expand Up @@ -445,7 +445,7 @@ class AppRowsPreferenceFragment : LeanbackPreferenceFragmentCompat() {
val enabled = (preference as SwitchPreference).isChecked
RowPreferences.setRecommendationsEnabled(ctx, enabled)
if (enabled && FireTVUtils.isAmazonNotificationsEnabled(ctx)) {
App.toast(getString(R.string.recs_warning_sale))
LauncherApp.toast(getString(R.string.recs_warning_sale))
}
// refresh home broadcast
SettingsFragment.needRestartHome = true
Expand Down Expand Up @@ -582,7 +582,7 @@ class FileListFragment : LeanbackPreferenceFragmentCompat() {
if (file.canRead())
setWallpaper(ctx, file.path.toString())
else
App.toast(getString(R.string.file_no_access))
LauncherApp.toast(getString(R.string.file_no_access))
dirName?.let { rootPath = rootPath?.removeSuffix(it) }
fm?.popBackStack()
return true
Expand Down
Loading

0 comments on commit 4aad674

Please sign in to comment.