Use "Context#getSystemService" extension function provided by "core-ktx".

+ Re-use local variable where possible.
This commit is contained in:
Tobias Preuss 2020-07-16 17:39:36 +02:00
parent b8b8a12035
commit 40f8e6061f
21 changed files with 52 additions and 36 deletions

View file

@ -20,6 +20,7 @@ Build 🧱:
-
Other changes:
- Use `Context#getSystemService` extension function provided by `core-ktx` (#1702)
- Hide Flair settings, this is not implemented yet.
- Rename package `im.vector.riotx.attachmentviewer` to `im.vector.lib.attachmentviewer`
- Rename package `im.vector.riotx.multipicker` to `im.vector.lib.multipicker`

View file

@ -22,6 +22,7 @@ import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import androidx.core.content.getSystemService
import timber.log.Timber
import javax.inject.Inject
@ -53,7 +54,7 @@ internal class FallbackNetworkCallbackStrategy @Inject constructor(private val c
internal class PreferredNetworkCallbackStrategy @Inject constructor(context: Context) : NetworkCallbackStrategy {
private var hasChangedCallback: (() -> Unit)? = null
private val conn = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val conn = context.getSystemService<ConnectivityManager>()!!
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {

View file

@ -24,6 +24,7 @@ import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import androidx.core.content.getSystemService
import javax.inject.Inject
internal class NetworkInfoReceiver @Inject constructor() : BroadcastReceiver() {
@ -31,7 +32,7 @@ internal class NetworkInfoReceiver @Inject constructor() : BroadcastReceiver() {
var isConnectedCallback: ((Boolean) -> Unit)? = null
override fun onReceive(context: Context, intent: Intent) {
val conn = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val conn = context.getSystemService<ConnectivityManager>()!!
val networkInfo: NetworkInfo? = conn.activeNetworkInfo
isConnectedCallback?.invoke(networkInfo?.isConnected ?: false)
}

View file

@ -19,11 +19,11 @@ package im.vector.app.features.debug
import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.Person
import androidx.core.content.getSystemService
import butterknife.OnClick
import im.vector.app.R
import im.vector.app.core.di.ActiveSessionHolder
@ -83,7 +83,7 @@ class DebugMenuActivity : VectorBaseActivity() {
@OnClick(R.id.debug_test_notification)
fun testNotification() {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationManager = getSystemService<NotificationManager>()!!
// Create channel first
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@ -95,7 +95,7 @@ class DebugMenuActivity : VectorBaseActivity() {
)
channel.description = "Channel description"
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
notificationManager.createNotificationChannel(channel)
val channel2 =
NotificationChannel(
@ -105,7 +105,7 @@ class DebugMenuActivity : VectorBaseActivity() {
)
channel2.description = "Channel description 2"
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel2)
notificationManager.createNotificationChannel(channel2)
}
val builder = NotificationCompat.Builder(this, "CHAN")

View file

@ -15,9 +15,9 @@
*/
package im.vector.app.fdroid.features.settings.troubleshoot
import android.content.Context
import android.net.ConnectivityManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
import androidx.core.net.ConnectivityManagerCompat
import im.vector.app.R
import im.vector.app.core.resources.StringProvider
@ -29,7 +29,7 @@ class TestBackgroundRestrictions @Inject constructor(private val context: AppCom
: TroubleshootTest(R.string.settings_troubleshoot_test_bg_restricted_title) {
override fun perform() {
(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).apply {
context.getSystemService<ConnectivityManager>()!!.apply {
// Checks if the device is on a metered network
if (isActiveNetworkMetered) {
// Checks users Data Saver settings.

View file

@ -26,6 +26,7 @@ import android.os.PowerManager
import androidx.core.content.ContextCompat
import im.vector.app.core.di.HasVectorInjector
import im.vector.app.core.services.VectorSyncService
import androidx.core.content.getSystemService
import im.vector.matrix.android.internal.session.sync.job.SyncService
import timber.log.Timber
@ -42,7 +43,7 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() {
}
// Acquire a lock to give enough time for the sync :/
(context.getSystemService(Context.POWER_SERVICE) as PowerManager).run {
context.getSystemService<PowerManager>()!!.run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "riotx:fdroidSynclock").apply {
acquire((10_000).toLong())
}
@ -74,7 +75,7 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() {
}
val pIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val firstMillis = System.currentTimeMillis() + delay
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmMgr = context.getSystemService<AlarmManager>()!!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, firstMillis, pIntent)
} else {
@ -86,7 +87,7 @@ class AlarmSyncBroadcastReceiver : BroadcastReceiver() {
Timber.v("Cancel alarm")
val intent = Intent(context, AlarmSyncBroadcastReceiver::class.java)
val pIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmMgr = context.getSystemService<AlarmManager>()!!
alarmMgr.cancel(pIntent)
}
}

View file

@ -16,12 +16,12 @@
package im.vector.app.core.extensions
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.core.content.getSystemService
fun View.hideKeyboard() {
val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
val imm = context?.getSystemService<InputMethodManager>()
imm?.hideSoftInputFromWindow(windowToken, 0)
}
@ -29,6 +29,6 @@ fun View.showKeyboard(andRequestFocus: Boolean = false) {
if (andRequestFocus) {
requestFocus()
}
val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
val imm = context?.getSystemService<InputMethodManager>()
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

View file

@ -23,6 +23,7 @@ import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.WorkerThread
import androidx.core.content.getSystemService
import arrow.core.Try
import okio.buffer
import okio.sink
@ -85,7 +86,7 @@ fun addEntryToDownloadManager(context: Context,
null
}
} else {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager
val downloadManager = context.getSystemService<DownloadManager>()
@Suppress("DEPRECATION")
downloadManager?.addCompletedDownload(title, description, true, mimeType, file.absolutePath, file.length(), true)
return null

View file

@ -23,6 +23,7 @@ import android.hardware.Camera
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Build
import androidx.core.content.getSystemService
import javax.inject.Inject
class HardwareInfo @Inject constructor(
@ -36,7 +37,7 @@ class HardwareInfo @Inject constructor(
return Camera.getNumberOfCameras() > 0
}
val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager? ?: return Camera.getNumberOfCameras() > 0
val manager = context.getSystemService<CameraManager>() ?: return Camera.getNumberOfCameras() > 0
return manager.cameraIdList.any {
val lensFacing = manager.getCameraCharacteristics(it).get(CameraCharacteristics.LENS_FACING)

View file

@ -20,9 +20,10 @@ import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.core.content.getSystemService
fun vibrate(context: Context, durationMillis: Long = 100) {
val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator? ?: return
val vibrator = context.getSystemService<Vibrator>() ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(durationMillis, VibrationEffect.DEFAULT_AMPLITUDE))
} else {

View file

@ -21,6 +21,7 @@ import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import androidx.core.content.getSystemService
import im.vector.app.R
import timber.log.Timber
@ -33,7 +34,7 @@ class CallRingPlayer(
private var player: MediaPlayer? = null
fun start() {
val audioManager: AudioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val audioManager = applicationContext.getSystemService<AudioManager>()!!
player?.release()
player = createPlayer()

View file

@ -21,6 +21,7 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.getSystemService
import im.vector.app.R
import im.vector.app.core.extensions.vectorComponent
import im.vector.app.features.notifications.NotificationUtils
@ -64,7 +65,7 @@ class VectorSyncService : SyncService() {
}
private fun removeForegroundNotification() {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationManager = getSystemService<NotificationManager>()!!
notificationManager.cancel(NotificationUtils.NOTIFICATION_ID_FOREGROUND_SERVICE)
}
@ -75,7 +76,7 @@ class VectorSyncService : SyncService() {
PendingIntent.getService(this, 0, newIntent(this, sessionId), 0)
}
val firstMillis = System.currentTimeMillis() + delay
val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmMgr = getSystemService<AlarmManager>()!!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, firstMillis, pendingIntent)
} else {

View file

@ -35,6 +35,7 @@ import androidx.browser.customtabs.CustomTabsIntent
import androidx.browser.customtabs.CustomTabsSession
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.getSystemService
import androidx.fragment.app.Fragment
import im.vector.app.BuildConfig
import im.vector.app.R
@ -375,7 +376,7 @@ private fun saveMediaLegacy(context: Context, mediaMimeType: String?, title: Str
}
val savedFile = saveFileIntoLegacy(file, downloadDir, outputFilename)
if (savedFile != null) {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as? DownloadManager
val downloadManager = context.getSystemService<DownloadManager>()
downloadManager?.addCompletedDownload(
savedFile.name,
title,

View file

@ -30,6 +30,7 @@ import android.provider.Settings
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
import androidx.fragment.app.Fragment
import im.vector.app.R
import im.vector.app.features.notifications.NotificationUtils
@ -47,7 +48,7 @@ import im.vector.app.features.notifications.NotificationUtils
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
// no issue before Android M, battery optimisations did not exist
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
|| (context.getSystemService(Context.POWER_SERVICE) as PowerManager?)?.isIgnoringBatteryOptimizations(context.packageName) == true
|| context.getSystemService<PowerManager>()?.isIgnoringBatteryOptimizations(context.packageName) == true
}
fun isAirplaneModeOn(context: Context): Boolean {
@ -84,7 +85,7 @@ fun requestDisablingBatteryOptimization(activity: Activity, fragment: Fragment?,
* @param text the text to copy
*/
fun copyToClipboard(context: Context, text: CharSequence, showToast: Boolean = true, @StringRes toastMessage: Int = R.string.copied_to_clipboard) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipboard = context.getSystemService<ClipboardManager>()!!
clipboard.setPrimaryClip(ClipData.newPlainText("", text))
if (showToast) {
context.toast(toastMessage)

View file

@ -22,6 +22,7 @@ import android.bluetooth.BluetoothProfile
import android.content.Context
import android.content.pm.PackageManager
import android.media.AudioManager
import androidx.core.content.getSystemService
import im.vector.app.core.services.WiredHeadsetStateReceiver
import im.vector.matrix.android.api.session.call.MxCall
import timber.log.Timber
@ -55,9 +56,9 @@ class CallAudioManager(
init {
executor.execute {
audioManager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager
audioManager = applicationContext.getSystemService()
}
val bm = applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
val bm = applicationContext.getSystemService<BluetoothManager>()
val adapter = bm?.adapter
Timber.d("## VOIP Bluetooth adapter $adapter")
bluetoothAdapter = adapter

View file

@ -28,6 +28,7 @@ import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import androidx.core.content.getSystemService
import androidx.core.view.ViewCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
@ -458,7 +459,7 @@ class VectorCallActivity : VectorBaseActivity(), CallControlsView.InteractionLis
)
}
with(getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager) {
with(getSystemService<KeyguardManager>()!!) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
requestDismissKeyguard(this@VectorCallActivity, null)
}

View file

@ -20,6 +20,7 @@ import android.content.Context
import android.hardware.camera2.CameraManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
import im.vector.app.ActiveSessionDataSource
import im.vector.app.core.services.BluetoothHeadsetReceiver
import im.vector.app.core.services.CallService
@ -480,7 +481,7 @@ class WebRtcPeerConnectionManager @Inject constructor(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val restarter = CameraRestarter(cameraInUse?.name ?: "", callContext.mxCall.callId)
callContext.cameraAvailabilityCallback = restarter
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraManager = context.getSystemService<CameraManager>()!!
cameraManager.registerAvailabilityCallback(restarter, null)
}
}
@ -792,7 +793,7 @@ class WebRtcPeerConnectionManager @Inject constructor(
currentCall?.cameraAvailabilityCallback?.let { cameraAvailabilityCallback ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraManager = context.getSystemService<CameraManager>()!!
cameraManager.unregisterAvailabilityCallback(cameraAvailabilityCallback)
}
}
@ -1048,8 +1049,7 @@ class WebRtcPeerConnectionManager @Inject constructor(
// re-start the capture
// TODO notify that video is enabled
videoCapturer?.startCapture(currentCaptureMode.width, currentCaptureMode.height, currentCaptureMode.fps)
(context.getSystemService(Context.CAMERA_SERVICE) as? CameraManager)
?.unregisterAvailabilityCallback(this)
context.getSystemService<CameraManager>()?.unregisterAvailabilityCallback(this)
}
}
}

View file

@ -18,11 +18,12 @@ package im.vector.app.features.call.telecom
import android.content.Context
import android.telephony.TelephonyManager
import androidx.core.content.getSystemService
object TelecomUtils {
fun isLineBusy(context: Context): Boolean {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
val telephonyManager = context.getSystemService<TelephonyManager>()
?: return false
return telephonyManager.callState != TelephonyManager.CALL_STATE_IDLE
}

View file

@ -20,6 +20,7 @@ import android.content.Context
import android.content.pm.ShortcutManager
import android.graphics.Bitmap
import android.os.Build
import androidx.core.content.getSystemService
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
@ -96,7 +97,7 @@ class ShortcutsHandler @Inject constructor(
// We can only disabled pinned shortcuts with the API, but at least it will prevent the crash
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
context.getSystemService(ShortcutManager::class.java)
context.getSystemService<ShortcutManager>()
?.let {
it.disableShortcuts(it.pinnedShortcuts.map { pinnedShortcut -> pinnedShortcut.id })
}

View file

@ -35,6 +35,7 @@ import androidx.core.app.NotificationManagerCompat
import androidx.core.app.RemoteInput
import androidx.core.app.TaskStackBuilder
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.core.graphics.drawable.IconCompat
import androidx.fragment.app.Fragment
import im.vector.app.BuildConfig
@ -853,7 +854,7 @@ class NotificationUtils @Inject constructor(private val context: Context,
}
// We cannot use NotificationManagerCompat here.
val setting = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).currentInterruptionFilter
val setting = context.getSystemService<NotificationManager>()!!.currentInterruptionFilter
return setting == NotificationManager.INTERRUPTION_FILTER_NONE
|| setting == NotificationManager.INTERRUPTION_FILTER_ALARMS

View file

@ -21,6 +21,7 @@ import android.hardware.Sensor
import android.hardware.SensorManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
import com.squareup.seismic.ShakeDetector
import im.vector.app.R
import im.vector.app.core.hardware.vibrate
@ -41,7 +42,7 @@ class RageShake @Inject constructor(private val activity: AppCompatActivity,
var interceptor: (() -> Unit)? = null
fun start() {
val sensorManager = activity.getSystemService(AppCompatActivity.SENSOR_SERVICE) as? SensorManager ?: return
val sensorManager = activity.getSystemService<SensorManager>() ?: return
shakeDetector = ShakeDetector(this).apply {
setSensitivity(vectorPreferences.getRageshakeSensitivity())
@ -94,8 +95,7 @@ class RageShake @Inject constructor(private val activity: AppCompatActivity,
* Check if the feature is available
*/
fun isAvailable(context: Context): Boolean {
return (context.getSystemService(AppCompatActivity.SENSOR_SERVICE) as? SensorManager)
?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null
return context.getSystemService<SensorManager>()?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null
}
}
}