Clean up a bunch of warnings. (#1053)

* Clean up a bunch of warnings.

* Remove unused class.
This commit is contained in:
Justin Bassett 2020-10-15 08:16:34 -04:00 committed by GitHub
parent 48afca5427
commit 1f48c44f44
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 51 additions and 164 deletions

View file

@ -118,6 +118,7 @@ dependencies {
}
implementation(Config.Dependency.Kotlin.core)
implementation(Config.Dependency.Kotlin.reflect)
implementation(Config.Dependency.Kotlin.coroutines)
implementation(Config.Dependency.Kotlin.coroutinesAndroid)

View file

@ -31,7 +31,6 @@ class NotificationDeleteReceiver : BroadcastReceiver() {
.build()
.inject(this)
@SuppressWarnings("unchecked")
val hashData = intent.getSerializableExtra(EXTRA_DATA) as HashMap<String, *>
val group = intent.getStringExtra(EXTRA_NOTIFICATION_GROUP)
val groupId = intent.getIntExtra(EXTRA_NOTIFICATION_GROUP_ID, -1)

View file

@ -271,12 +271,12 @@ abstract class AppDatabase : RoomDatabase() {
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var notificationChannel =
notificationManager?.getNotificationChannel(channelId)
notificationManager.getNotificationChannel(channelId)
if (notificationChannel == null) {
notificationChannel = NotificationChannel(
channelId, TAG, NotificationManager.IMPORTANCE_HIGH
)
notificationManager?.createNotificationChannel(notificationChannel)
notificationManager.createNotificationChannel(notificationChannel)
}
}
}

View file

@ -44,7 +44,7 @@ class ManualSetupFragment : Fragment(), ManualSetupView {
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_manual_setup, container, false).apply {
findViewById<AppCompatEditText>(R.id.home_assistant_url).setOnEditorActionListener { view, actionId, event ->
findViewById<AppCompatEditText>(R.id.home_assistant_url).setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
submitForm()
return@setOnEditorActionListener true

View file

@ -21,10 +21,10 @@ class ManualSetupPresenterImpl @Inject constructor(
private val mainScope: CoroutineScope = CoroutineScope(Dispatchers.Main + Job())
override fun onClickOk(url: String) {
override fun onClickOk(urlString: String) {
mainScope.launch {
try {
urlUseCase.saveUrl(url, false)
urlUseCase.saveUrl(urlString, false)
} catch (e: MalformedHttpUrlException) {
Log.e(TAG, "Unable to parse url", e)
view.displayUrlError()

View file

@ -48,13 +48,11 @@ class BluetoothSensorManager : SensorManager {
if (!isEnabled(context, bluetoothConnection.id))
return
var connectedNotPairedAddress = ""
var totalConnectedDevices = 0
val icon = "mdi:bluetooth"
val connectedPairedDevices: MutableList<String> = ArrayList()
val connectedNotPairedDevices: MutableList<String> = ArrayList()
var bondedString = ""
var isBtOn = false
if (checkPermission(context, bluetoothConnection.id)) {
@ -66,7 +64,7 @@ class BluetoothSensorManager : SensorManager {
var connectedAddress = ""
val adapter = bluetoothManager.adapter
isBtOn = adapter.isEnabled
val isBtOn = adapter.isEnabled
if (isBtOn) {
val bondedDevices = adapter.bondedDevices
@ -80,7 +78,7 @@ class BluetoothSensorManager : SensorManager {
}
for (BluetoothDevice in btConnectedDevices) {
if (isConnected(BluetoothDevice)) {
connectedNotPairedAddress = BluetoothDevice.address
val connectedNotPairedAddress = BluetoothDevice.address
connectedNotPairedDevices.add(connectedNotPairedAddress)
if (connectedNotPairedAddress != connectedAddress) {
totalConnectedDevices += 1

View file

@ -38,9 +38,8 @@ class DNDSensorManager : SensorManager {
if (!isEnabled(context, dndSensor.id))
return
var dndState = "unavailable"
try {
dndState = when (Global.getInt(context.contentResolver, "zen_mode")) {
val dndState = when (Global.getInt(context.contentResolver, "zen_mode")) {
0 -> "off"
1 -> "priority_only"
2 -> "total_silence"

View file

@ -1,5 +1,6 @@
package io.homeassistant.companion.android.sensors
import android.annotation.SuppressLint
import android.content.Context
import android.os.SystemClock
import android.util.Log
@ -47,6 +48,7 @@ class LastRebootSensorManager : SensorManager {
updateLastReboot(context)
}
@SuppressLint("SimpleDateFormat")
private fun updateLastReboot(context: Context) {
if (!isEnabled(context, lastRebootSensor.id))
return
@ -59,7 +61,7 @@ class LastRebootSensorManager : SensorManager {
val fullSensor = sensorDao.getFull(lastRebootSensor.id)
val sensorSetting = sensorDao.getSettings(lastRebootSensor.id)
val lastTimeMillis = fullSensor?.attributes?.firstOrNull { it.name == TIME_MILLISECONDS }?.value?.toLongOrNull() ?: 0L
val settingDeadband = sensorSetting?.firstOrNull { it.name == DEADBAND }?.value?.toIntOrNull() ?: 60000
val settingDeadband = sensorSetting.firstOrNull { it.name == DEADBAND }?.value?.toIntOrNull() ?: 60000
sensorDao.add(Setting(lastRebootSensor.id, DEADBAND, settingDeadband.toString(), "number"))
try {
timeInMillis = System.currentTimeMillis() - SystemClock.elapsedRealtime()

View file

@ -172,8 +172,8 @@ class NetworkSensorManager : SensorManager {
val settingName = "replace_$bssid"
val sensorDao = AppDatabase.getInstance(context).sensorDao()
val sensorSettings = sensorDao.getSettings(bssidState.id)
val getCurrentBSSID = sensorSettings?.firstOrNull { it.name == GET_CURRENT_BSSID }?.value ?: "false"
val currentSetting = sensorSettings?.firstOrNull { it.name == settingName }?.value ?: ""
val getCurrentBSSID = sensorSettings.firstOrNull { it.name == GET_CURRENT_BSSID }?.value ?: "false"
val currentSetting = sensorSettings.firstOrNull { it.name == settingName }?.value ?: ""
if (getCurrentBSSID == "true") {
if (currentSetting == "") {
sensorDao.add(Setting(bssidState.id, GET_CURRENT_BSSID, "false", "toggle"))
@ -202,13 +202,12 @@ class NetworkSensorManager : SensorManager {
if (!isEnabled(context, wifiIp.id))
return
var conInfo: WifiInfo? = null
var deviceIp = "Unknown"
if (checkPermission(context, wifiIp.id)) {
val wifiManager =
(context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager)
conInfo = wifiManager.connectionInfo
val conInfo = wifiManager.connectionInfo
deviceIp = if (conInfo.networkId == -1) {
"<not connected>"
@ -232,14 +231,13 @@ class NetworkSensorManager : SensorManager {
if (!isEnabled(context, wifiLinkSpeed.id))
return
var conInfo: WifiInfo? = null
var linkSpeed = 0
var lastScanStrength = -1
if (checkPermission(context, wifiLinkSpeed.id)) {
val wifiManager =
(context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager)
conInfo = wifiManager.connectionInfo
val conInfo = wifiManager.connectionInfo
linkSpeed = if (conInfo.networkId == -1) {
0
@ -299,13 +297,12 @@ class NetworkSensorManager : SensorManager {
if (!isEnabled(context, wifiFrequency.id))
return
var conInfo: WifiInfo? = null
var frequency = 0
if (checkPermission(context, wifiFrequency.id)) {
val wifiManager =
(context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager)
conInfo = wifiManager.connectionInfo
val conInfo = wifiManager.connectionInfo
frequency = if (conInfo.networkId == -1) {
0
@ -329,13 +326,12 @@ class NetworkSensorManager : SensorManager {
if (!isEnabled(context, wifiSignalStrength.id))
return
var conInfo: WifiInfo? = null
var lastScanStrength = -1
if (checkPermission(context, wifiSignalStrength.id)) {
val wifiManager =
(context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager)
conInfo = wifiManager.connectionInfo
val conInfo = wifiManager.connectionInfo
lastScanStrength = wifiManager.scanResults.firstOrNull {
it.BSSID == conInfo.bssid

View file

@ -56,7 +56,7 @@ class NextAlarmManager : SensorManager {
val sensorDao = AppDatabase.getInstance(context).sensorDao()
val sensorSetting = sensorDao.getSettings(nextAlarm.id)
val allowPackageList = sensorSetting?.firstOrNull { it.name == ALLOW_LIST }?.value ?: ""
val allowPackageList = sensorSetting.firstOrNull { it.name == ALLOW_LIST }?.value ?: ""
try {
val alarmManager: AlarmManager =

View file

@ -5,6 +5,7 @@ import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.InputType
import androidx.preference.EditTextPreference
@ -37,7 +38,7 @@ class SensorDetailFragment(
}
private lateinit var sensorDao: SensorDao
private val handler = Handler()
private val handler = Handler(Looper.getMainLooper())
private val refresh = object : Runnable {
override fun run() {
refreshSensorData()

View file

@ -76,12 +76,12 @@ class SensorWorker(
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var notificationChannel =
notificationManager?.getNotificationChannel(channelId)
notificationManager.getNotificationChannel(channelId)
if (notificationChannel == null) {
notificationChannel = NotificationChannel(
channelId, TAG, NotificationManager.IMPORTANCE_LOW
)
notificationManager?.createNotificationChannel(notificationChannel)
notificationManager.createNotificationChannel(notificationChannel)
}
}
}

View file

@ -3,6 +3,7 @@ package io.homeassistant.companion.android.sensors
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
@ -19,7 +20,7 @@ class SensorsSettingsFragment : PreferenceFragmentCompat() {
@Inject
lateinit var integrationUseCase: IntegrationRepository
private val handler = Handler()
private val handler = Handler(Looper.getMainLooper())
private val refresh = object : Runnable {
override fun run() {
SensorWorker.start(requireContext())

View file

@ -55,12 +55,12 @@ class TrafficStatsManager : SensorManager {
listOf(rxBytesMobile, txBytesMobile, rxBytesTotal, txBytesTotal)
} else listOf(rxBytesTotal, txBytesTotal)
override fun requiredPermissions(senorId: String): Array<String> {
override fun requiredPermissions(sensorId: String): Array<String> {
return emptyArray()
}
override fun hasSensor(context: Context): Boolean {
val cm: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = cm.allNetworks
var networkCapabilities: NetworkCapabilities?
for (item in networkInfo) {
@ -84,17 +84,15 @@ class TrafficStatsManager : SensorManager {
if (!isEnabled(context, rxBytesMobile.id))
return
var mobileRx = 0f
val icon = "mdi:radio-tower"
try {
mobileRx = TrafficStats.getMobileRxBytes().toFloat()
val mobileRx = try {
TrafficStats.getMobileRxBytes().toFloat() / GB
} catch (e: Exception) {
Log.e(TAG, "Error getting the mobile rx bytes", e)
return
}
mobileRx /= GB
onSensorUpdated(context,
rxBytesMobile,
mobileRx.toBigDecimal().setScale(3, RoundingMode.HALF_EVEN),
@ -108,17 +106,15 @@ class TrafficStatsManager : SensorManager {
if (!isEnabled(context, txBytesMobile.id))
return
var mobileTx = 0f
val icon = "mdi:radio-tower"
try {
mobileTx = TrafficStats.getMobileTxBytes().toFloat()
val mobileTx = try {
TrafficStats.getMobileTxBytes().toFloat() / GB
} catch (e: Exception) {
Log.e(TAG, "Error getting the mobile tx bytes", e)
return
}
mobileTx /= GB
onSensorUpdated(context,
txBytesMobile,
mobileTx.toBigDecimal().setScale(3, RoundingMode.HALF_EVEN),
@ -131,16 +127,14 @@ class TrafficStatsManager : SensorManager {
if (!isEnabled(context, rxBytesTotal.id))
return
var totalRx = 0f
val icon = "mdi:radio-tower"
try {
totalRx = TrafficStats.getTotalRxBytes().toFloat().absoluteValue
val totalRx = try {
TrafficStats.getTotalRxBytes().toFloat().absoluteValue / GB
} catch (e: Exception) {
Log.e(TAG, "Error getting the total rx bytes", e)
return
}
totalRx /= GB
onSensorUpdated(context,
rxBytesTotal,
@ -155,18 +149,15 @@ class TrafficStatsManager : SensorManager {
if (!isEnabled(context, txBytesTotal.id))
return
var totalTx = 0f
val icon = "mdi:radio-tower"
try {
totalTx = TrafficStats.getTotalTxBytes().toFloat().absoluteValue
val totalTx = try {
TrafficStats.getTotalTxBytes().toFloat().absoluteValue / GB
} catch (e: Exception) {
Log.e(TAG, "Error getting the total tx bytes", e)
return
}
totalTx /= GB
onSensorUpdated(context,
txBytesTotal,
totalTx.toBigDecimal().setScale(3, RoundingMode.HALF_EVEN),

View file

@ -1,106 +0,0 @@
package io.homeassistant.companion.android.util
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import io.homeassistant.companion.android.sensors.LocationSensorManager
class PermissionManager {
companion object {
const val LOCATION_REQUEST_CODE = 1
const val PHONE_STATE_REQUEST_CODE = 2
/**
* Check if the a given permission is granted
*/
private fun hasPermission(context: Context, permission: String): Boolean {
return ActivityCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
}
/**
* Returns TRUE if all permissions in the grantResults were granted
*/
private fun arePermissionsGranted(grantResults: IntArray): Boolean {
return grantResults.all { it == PackageManager.PERMISSION_GRANTED }
}
/**
* Check if the required location permissions are granted
*/
private fun checkLocationPermission(context: Context): Boolean {
for (permission in getLocationPermissionArray()) {
if (!hasPermission(context, permission)) {
return false
}
}
return true
}
private fun checkBluetoothPermission(context: Context): Boolean {
for (permission in getBluetoohPermissionArray()) {
if (!hasPermission(context, permission)) {
return false
}
}
return true
}
/**
* Returns an Array with required location permissions.
* ACCESS_FINE_LOCATION and, if API level >= 29, ACCESS_BACKGROUND_LOCATION.
*/
private fun getLocationPermissionArray(): Array<String> {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
}
private fun getBluetoohPermissionArray(): Array<String> {
return arrayOf(Manifest.permission.BLUETOOTH)
}
private fun validateLocationPermissions(
requestCode: Int,
grantResults: IntArray
): Boolean {
return requestCode == LOCATION_REQUEST_CODE && arePermissionsGranted(grantResults)
}
private fun requestLocationPermissions(fragment: Fragment) {
fragment.requestPermissions(getLocationPermissionArray(), LOCATION_REQUEST_CODE)
}
private fun restartLocationTracking(context: Context) {
val intent = Intent(context, LocationSensorManager::class.java)
intent.action = LocationSensorManager.ACTION_REQUEST_LOCATION_UPDATES
context.sendBroadcast(intent)
}
private fun getPhonePermissionArray(): Array<String> {
return arrayOf(Manifest.permission.READ_PHONE_STATE)
}
private fun requestPhoneStatePermissions(fragment: Fragment) {
fragment.requestPermissions(getPhonePermissionArray(), PHONE_STATE_REQUEST_CODE)
}
private fun checkPhoneStatePermission(context: Context): Boolean {
return hasPermission(context, Manifest.permission.READ_PHONE_STATE)
}
private fun validatePhoneStatePermissions(
requestCode: Int,
grantResults: IntArray
): Boolean {
return requestCode == PHONE_STATE_REQUEST_CODE && arePermissionsGranted(grantResults)
}
}
}

View file

@ -13,6 +13,7 @@ import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
@ -869,7 +870,7 @@ class WebViewActivity : AppCompatActivity(), io.homeassistant.companion.android.
}
private fun waitForConnection() {
Handler().postDelayed({
Handler(Looper.getMainLooper()).postDelayed({
if (!isConnected) {
showError()
}

View file

@ -7,6 +7,7 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.RemoteViews
@ -231,7 +232,7 @@ class ButtonWidget : AppWidgetProvider() {
views = getWidgetRemoteViews(context, appWidgetId)
// Set a timer to change it back after 1 second
Handler().postDelayed({
Handler(Looper.getMainLooper()).postDelayed({
views.setViewVisibility(R.id.widgetLabelLayout, View.VISIBLE)
views.setInt(
R.id.widgetLayout,

View file

@ -179,7 +179,7 @@ class EntityWidget : AppWidgetProvider() {
Log.d(
TAG, "Saving service call config data:" + System.lineSeparator() +
"entity id: " + entitySelection + System.lineSeparator() +
"attribute: " + attributeSelection ?: "N/A"
"attribute: " + (attributeSelection ?: "N/A")
)
staticWidgetDao.add(StaticWidgetEntity(
appWidgetId,

View file

@ -130,7 +130,7 @@ class EntityWidgetConfigureActivity : Activity() {
}
private val attributeDropDownOnItemClick =
AdapterView.OnItemClickListener { parent, view, position, id ->
AdapterView.OnItemClickListener { parent, _, position, _ ->
selectedAttributeIds.add(parent.getItemAtPosition(position) as String)
}

View file

@ -7,6 +7,7 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.RemoteViews
@ -152,7 +153,7 @@ class MediaPlayerControlsWidget : AppWidgetProvider() {
View.GONE
)
Log.d(TAG, "Fetching media preview image")
Handler().post {
Handler(Looper.getMainLooper()).post {
Picasso.get().load(entityPictureUrl).into(
this,
R.id.widgetMediaImage,
@ -272,11 +273,11 @@ class MediaPlayerControlsWidget : AppWidgetProvider() {
when (action) {
RECEIVE_DATA -> saveEntityConfiguration(context, intent.extras, appWidgetId)
UPDATE_MEDIA_IMAGE -> updateAppWidget(context, appWidgetId)
CALL_PREV_TRACK -> callPreviousTrackService(context, appWidgetId)
CALL_PREV_TRACK -> callPreviousTrackService(appWidgetId)
CALL_REWIND -> callRewindService(context, appWidgetId)
CALL_PLAYPAUSE -> callPlayPauseService(context, appWidgetId)
CALL_PLAYPAUSE -> callPlayPauseService(appWidgetId)
CALL_FASTFORWARD -> callFastForwardService(context, appWidgetId)
CALL_NEXT_TRACK -> callNextTrackService(context, appWidgetId)
CALL_NEXT_TRACK -> callNextTrackService(appWidgetId)
}
}
@ -312,7 +313,7 @@ class MediaPlayerControlsWidget : AppWidgetProvider() {
}
}
private fun callPreviousTrackService(context: Context, appWidgetId: Int) {
private fun callPreviousTrackService(appWidgetId: Int) {
mainScope.launch {
Log.d(TAG, "Retrieving media player entity for app widget $appWidgetId")
val entity: MediaPlayerControlsWidgetEntity? = mediaPlayCtrlWidgetDao.get(appWidgetId)
@ -380,7 +381,7 @@ class MediaPlayerControlsWidget : AppWidgetProvider() {
}
}
private fun callPlayPauseService(context: Context, appWidgetId: Int) {
private fun callPlayPauseService(appWidgetId: Int) {
mainScope.launch {
Log.d(TAG, "Retrieving media player entity for app widget $appWidgetId")
val entity: MediaPlayerControlsWidgetEntity? = mediaPlayCtrlWidgetDao.get(appWidgetId)
@ -448,7 +449,7 @@ class MediaPlayerControlsWidget : AppWidgetProvider() {
}
}
private fun callNextTrackService(context: Context, appWidgetId: Int) {
private fun callNextTrackService(appWidgetId: Int) {
mainScope.launch {
Log.d(TAG, "Retrieving media player entity for app widget $appWidgetId")
val entity: MediaPlayerControlsWidgetEntity? = mediaPlayCtrlWidgetDao.get(appWidgetId)

View file

@ -25,6 +25,7 @@ object Config {
object Kotlin {
const val version = "1.4.10"
const val core = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${version}"
const val reflect = "org.jetbrains.kotlin:kotlin-reflect:${version}"
private const val coroutinesVersion = "1.3.3"
const val coroutines = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutinesVersion}"

View file

@ -19,6 +19,7 @@ android {
dependencies {
implementation(Config.Dependency.Kotlin.core)
implementation(Config.Dependency.Kotlin.reflect)
implementation(Config.Dependency.Kotlin.coroutines)
implementation(Config.Dependency.Google.dagger)