Foregound service type improvement

Code formating improvements
This commit is contained in:
Juha Heinanen
2026-06-25 17:45:39 +03:00
parent b02bc7a521
commit 0fcfc6abc5

View File

@ -1,6 +1,7 @@
@file:Suppress("DEPRECATION")
package com.tutpro.baresip
import android.Manifest
import android.Manifest.permission.RECORD_AUDIO
import android.annotation.SuppressLint
import android.app.Notification
@ -78,10 +79,6 @@ import androidx.core.net.toUri
import androidx.lifecycle.MutableLiveData
import com.tutpro.baresip.Utils.e164Uri
import com.tutpro.baresip.Utils.toCircle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.net.InetAddress
import java.nio.charset.Charset
@ -92,6 +89,10 @@ import java.util.TimerTask
import kotlin.concurrent.schedule
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class BaresipService: Service() {
@ -333,8 +334,10 @@ class BaresipService: Service() {
override fun onReceive(ctx: Context, intent: Intent) {
when (intent.action) {
BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> {
val state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
BluetoothHeadset.STATE_DISCONNECTED)
val state = intent.getIntExtra(
BluetoothHeadset.EXTRA_STATE,
BluetoothHeadset.STATE_DISCONNECTED
)
when (state) {
BluetoothHeadset.STATE_CONNECTED -> {
Log.d(TAG, "Bluetooth headset is connected")
@ -412,8 +415,10 @@ class BaresipService: Service() {
}
}
proximityWakeLock = pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
"com.tutpro.baresip:proximity_wakelock")
proximityWakeLock = pm.newWakeLock(
PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
"com.tutpro.baresip:proximity_wakelock"
)
wifiLock = if (VERSION.SDK_INT < 29) {
@Suppress("DEPRECATION")
@ -709,7 +714,8 @@ class BaresipService: Service() {
if (ua.account.telProvider == "") {
Log.w(TAG, "No telephony provider for $aor")
peerUri = ""
} else
}
else
peerUri = Utils.telToSip(peerUri, ua.account)
}
if (peerUri != "") {
@ -774,14 +780,12 @@ class BaresipService: Service() {
super.onConfigurationChanged(newConfig)
val currentNightMode = newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK
when (currentNightMode) {
Configuration.UI_MODE_NIGHT_NO -> {
Configuration.UI_MODE_NIGHT_NO ->
darkTheme.value = Preferences(this).displayTheme == AppCompatDelegate.MODE_NIGHT_YES
}
Configuration.UI_MODE_NIGHT_YES -> {
Configuration.UI_MODE_NIGHT_YES ->
darkTheme.value = true
}
}
}
override fun onBind(intent: Intent): IBinder? {
return null
@ -822,9 +826,9 @@ class BaresipService: Service() {
if (password != null) {
Api.account_set_auth_pass(acc.accp, password)
acc.authPass = password
} else {
Api.account_set_auth_pass(acc.accp, NO_AUTH_PASS)
}
else
Api.account_set_auth_pass(acc.accp, NO_AUTH_PASS)
}
Log.d(TAG, "got uaEvent $event/${acc.aor}")
@ -853,7 +857,7 @@ class BaresipService: Service() {
agc = null
ns?.release()
ns = null
if (aecAvailable) {
if (aecAvailable)
try {
aec = AcousticEchoCanceler.create(sessionId)
if (aec != null) {
@ -863,8 +867,7 @@ class BaresipService: Service() {
} catch (e: Exception) {
Log.e(TAG, "Exception creating AEC: $e")
}
}
if (agcAvailable) {
if (agcAvailable)
try {
agc = AutomaticGainControl.create(sessionId)
if (agc != null) {
@ -874,8 +877,7 @@ class BaresipService: Service() {
} catch (e: Exception) {
Log.e(TAG, "Exception creating AGC: $e")
}
}
if (nsAvailable) {
if (nsAvailable)
try {
ns = NoiseSuppressor.create(sessionId)
if (ns != null) {
@ -886,7 +888,6 @@ class BaresipService: Service() {
Log.e(TAG, "Exception creating NS: $e")
}
}
}
return
}
@ -910,6 +911,7 @@ class BaresipService: Service() {
for (accountIndex in uas.value.indices) {
if (uas.value[accountIndex].account.aor == aor) {
when (ev[0]) {
"registering", "unregistering" -> {
ua.updateStatus(circleYellow.getValue(colorblind))
updateStatusNotification()
@ -917,6 +919,7 @@ class BaresipService: Service() {
registrationUpdate.postValue(System.currentTimeMillis())
return
}
"registered" -> {
ua.updateStatus(
if (Api.account_regint(ua.account.accp) == 0)
@ -929,8 +932,10 @@ class BaresipService: Service() {
registrationUpdate.postValue(System.currentTimeMillis())
return
}
"registering failed" -> {
ua.updateStatus(if (Api.account_regint(ua.account.accp) == 0)
ua.updateStatus(
if (Api.account_regint(ua.account.accp) == 0)
R.drawable.circle_white
else
circleRed.getValue(colorblind)
@ -944,12 +949,14 @@ class BaresipService: Service() {
": DNS lookup failed"
else
": ${ev[1]}"
} else
}
else
""
toast(String.format(getString(R.string.registering_failed), aor) + reason)
}
return
}
"call outgoing" -> {
if (call!!.status.value == "transferring")
break
@ -959,18 +966,20 @@ class BaresipService: Service() {
ensureCommunicationMode()
proximitySensing(proximitySensing)
}
"call ringing" -> {
playRingBack()
return
}
"call progress" -> {
if ((ev[1].toInt() and Api.SDP_RECVONLY) != 0)
stopMediaPlayer()
else {
else
playRingBack()
}
return
}
"incoming call" -> {
speakerPhone = speakerPhoneAuto
val peerUri = ev[1]
@ -1023,11 +1032,10 @@ class BaresipService: Service() {
"raw",
packageName
)
if (resourceId != 0) {
if (resourceId != 0)
ensureCommunicationMode()
} else {
else
Log.e(TAG, "Callwaiting tone $name.wav not found")
}
if (ua.account.callHistory) {
CallHistoryNew(aor, peerUri, "in").add()
ua.account.missedCalls = true
@ -1039,6 +1047,7 @@ class BaresipService: Service() {
Api.ua_accept(uap, callp)
return
}
"call incoming" -> {
val peerUri = ev[1]
Log.d(TAG, "Incoming call $uap/$callp/$peerUri")
@ -1055,6 +1064,7 @@ class BaresipService: Service() {
}
return
}
"call answered" -> {
stopMediaPlayer()
ConnectionService.connections[callp]?.setActive()
@ -1068,9 +1078,10 @@ class BaresipService: Service() {
}
}
}
"call redirect" -> {
"call redirect" ->
stopMediaPlayer()
}
"call established" -> {
ensureCommunicationMode()
stopMediaPlayer()
@ -1092,6 +1103,7 @@ class BaresipService: Service() {
if (!isMainVisible)
return
}
"call update" -> {
Handler(Looper.getMainLooper()).post {
if (call != null) {
@ -1118,7 +1130,8 @@ class BaresipService: Service() {
call.callOnHold.value = true
if (connection?.state != Connection.STATE_HOLDING)
connection?.setOnHold()
} else {
}
else {
// Peer un-held us
call.showOnHoldNotice.value = false
if (!call.onhold) {
@ -1127,10 +1140,9 @@ class BaresipService: Service() {
connection?.setActive()
}
}
if (call.state() == Api.CALL_STATE_EARLY) {
if (call.state() == Api.CALL_STATE_EARLY)
if ((ev[1].toInt() and Api.SDP_RECVONLY) != 0)
stopMediaPlayer()
}
if (call.status.value == "connected" && !call.held && !call.onhold) {
if (call.callOnHold.value || call.showOnHoldNotice.value) {
Log.d(
@ -1147,12 +1159,13 @@ class BaresipService: Service() {
if (!isMainVisible || call?.status?.value != "connected")
return
}
"call verified", "call secure" -> {
Handler(Looper.getMainLooper()).post {
if (call != null) {
if (ev[0] == "call secure") {
if (ev[0] == "call secure")
call.security = R.color.colorTrafficYellow
} else {
else {
call.security = R.color.colorTrafficGreen
call.zid = ev[1]
}
@ -1161,6 +1174,7 @@ class BaresipService: Service() {
if (!isMainVisible)
return
}
"call transfer" -> {
if (!Utils.isVisible()) {
val piFlags = PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
@ -1198,16 +1212,26 @@ class BaresipService: Service() {
val denyIntent = Intent(this, BaresipService::class.java)
denyIntent.action = "Transfer Deny"
denyIntent.putExtra("callp", callp)
val denyPendingIntent = PendingIntent.getService(this,
DENY_REQ_CODE, denyIntent, piFlags)
nb.addAction(R.drawable.ic_notification_call,
getString(R.string.accept), acceptPendingIntent)
nb.addAction(R.drawable.ic_notification_call_end,
getString(R.string.deny), denyPendingIntent)
val denyPendingIntent = PendingIntent.getService(
this,
DENY_REQ_CODE,
denyIntent,
piFlags)
nb.addAction(
R.drawable.ic_notification_call,
getString(R.string.accept),
acceptPendingIntent
)
nb.addAction(
R.drawable.ic_notification_call_end,
getString(R.string.deny),
denyPendingIntent
)
nm.notify(TRANSFER_NOTIFICATION_ID, nb.build())
return
}
}
"transfer failed" -> {
Log.d(TAG, "AoR $aor call $callp transfer failed: ${ev[1]}")
stopMediaPlayer()
@ -1217,6 +1241,7 @@ class BaresipService: Service() {
if (!isMainVisible)
return
}
"call closed" -> {
Log.d(TAG, "AoR $aor call $callp is closed prm: ${ev[1]}")
val connection = ConnectionService.connections[callp]
@ -1237,15 +1262,12 @@ class BaresipService: Service() {
call.terminated.value = true
call.remove()
val noMoreCalls = synchronized(calls) { !Call.inCall() }
stopRinging()
stopMediaPlayer()
if (noMoreCalls) {
proximitySensing(false)
abandonAudioFocus(this)
}
val newCall = call.newCall
if (newCall != null) {
newCall.onHoldCall = null
@ -1285,7 +1307,6 @@ class BaresipService: Service() {
!reason.startsWith("408") &&
!reason.startsWith("480") &&
!reason.startsWith("Connection reset by")
val missed = call.dir == "in" && call.startTime == null && !call.rejected
if (ua.account.callHistory) {
val completedElsewhere = missed && ev[2].startsWith("SIP") &&
@ -1298,9 +1319,8 @@ class BaresipService: Service() {
else
call.startTime
history.rejected = call.rejected
if (call.dumpfiles[0] != "") {
if (call.dumpfiles[0] != "")
history.recording = call.dumpfiles
}
history.add()
if (call.startTime != null && call.dumpfiles[0] != "") {
delay(500.milliseconds)
@ -1345,8 +1365,7 @@ class BaresipService: Service() {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra("action", "call missed")
.putExtra("uap", uap)
intent.putExtra("action", "call missed").putExtra("uap", uap)
val pi = PendingIntent.getActivity(
this,
CALL_REQ_CODE,
@ -1370,8 +1389,11 @@ class BaresipService: Service() {
else {
nb.setContentTitle(getString(R.string.missed_calls))
nb.setContentText(
String.format(getString(R.string.missed_calls_count),
missedCalls + 1))
String.format(
getString(R.string.missed_calls_count),
missedCalls + 1
)
)
}
nm.notify(CALL_MISSED_NOTIFICATION_ID, nb.build())
}
@ -1432,8 +1454,7 @@ class BaresipService: Service() {
return
}
val charsetString = Utils.paramValue(cType.replace(" ", ""),
"charset")
val charsetString = Utils.paramValue(cType.replace(" ", ""), "charset")
val charset = try {
Charset.forName(charsetString)
} catch (_: Exception) {
@ -1510,9 +1531,7 @@ class BaresipService: Service() {
val intent = Intent(this, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_NEW_TASK
intent.putExtra("action", "message show")
.putExtra("uap", uap)
.putExtra("peer", peerUri)
intent.putExtra("action", "message show").putExtra("uap", uap).putExtra("peer", peerUri)
val pi = PendingIntent.getActivity(
this,
MESSAGE_REQ_CODE,
@ -1546,8 +1565,7 @@ class BaresipService: Service() {
.build()
val directReplyIntent = Intent(this, BaresipService::class.java)
directReplyIntent.action = "Message Inline Reply"
directReplyIntent.putExtra("uap", uap)
.putExtra("peer", peerUri).putExtra("time", timeStamp)
directReplyIntent.putExtra("uap", uap).putExtra("peer", peerUri).putExtra("time", timeStamp)
val directReplyPendingIntent = PendingIntent.getService(
this,
DIRECT_REPLY_REQ_CODE,
@ -1612,20 +1630,20 @@ class BaresipService: Service() {
val timeStamp = time.toLong()
for (m in messages.reversed())
if (m.timeStamp == timeStamp) {
if (responseCode < 300) {
if (responseCode < 300)
m.direction = MESSAGE_UP
} else {
else {
m.direction = MESSAGE_UP_FAIL
m.responseCode = responseCode
m.responseReason = responseReason
}
messageUpdate.postValue(System.currentTimeMillis())
break
} else {
}
else
if (m.timeStamp < timeStamp - 60000)
break
}
}
private var audioModeChangedListener: AudioManager.OnModeChangedListener? = null
@ -1656,14 +1674,14 @@ class BaresipService: Service() {
call.destroy()
updateStatusNotification()
}
} else {
}
else
ConnectionService.pendingOutgoingConnection?.let {
it.setDisconnected(DisconnectCause(DisconnectCause.ERROR))
it.destroy()
ConnectionService.pendingOutgoingConnection = null
}
}
}
}, audioDelay)
}
@ -1727,7 +1745,7 @@ class BaresipService: Service() {
}
}
if (VERSION.SDK_INT >= 31 && !telephonyCallbackRegistered) {
if (VERSION.SDK_INT >= 31 && !telephonyCallbackRegistered)
try {
telephonyManager.registerTelephonyCallback(mainExecutor, telephonyCallback)
telephonyCallbackRegistered = true
@ -1735,16 +1753,14 @@ class BaresipService: Service() {
} catch (e: Exception) {
Log.e(TAG, "Failed to register TelephonyCallback: ${e.message}")
}
} else if (!telephonyCallbackRegistered) {
else if (!telephonyCallbackRegistered) {
@Suppress("DEPRECATION")
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE)
telephonyCallbackRegistered = true
Log.d(TAG, "Registered PhoneStateListener")
}
Api.net_debug()
postServiceEvent(
ServiceEvent("started", arrayListOf(callActionUri), System.nanoTime())
)
postServiceEvent(ServiceEvent("started", arrayListOf(callActionUri), System.nanoTime()))
callActionUri = ""
Log.d(TAG, "Battery optimizations are ignored: " +
"${pm.isIgnoringBatteryOptimizations(packageName)}")
@ -1761,15 +1777,15 @@ class BaresipService: Service() {
quitTimer.cancel()
cleanService()
isServiceRunning = false
postServiceEvent(
ServiceEvent("stopped", arrayListOf(error), System.nanoTime())
)
postServiceEvent(ServiceEvent("stopped", arrayListOf(error), System.nanoTime()))
stopSelf()
}
private fun createNotificationChannels() {
val lowChannel = NotificationChannel(LOW_CHANNEL_ID, "No sound, no vibrate",
NotificationManager.IMPORTANCE_LOW)
val lowChannel = NotificationChannel(
LOW_CHANNEL_ID, "No sound, no vibrate",
NotificationManager.IMPORTANCE_LOW
)
lowChannel.description = "Background status notifications"
lowChannel.enableVibration(false)
lowChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
@ -1778,15 +1794,21 @@ class BaresipService: Service() {
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build()
val highChannel = NotificationChannel(HIGH_CHANNEL_ID, "Sound, vibrate, and peek",
NotificationManager.IMPORTANCE_HIGH)
val highChannel = NotificationChannel(
HIGH_CHANNEL_ID,
"Sound, vibrate, and peek",
NotificationManager.IMPORTANCE_HIGH
)
highChannel.description = "Incoming calls and important alerts"
highChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
highChannel.enableVibration(true)
highChannel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, ringAttributes)
nm.createNotificationChannel(highChannel)
val mediumChannel = NotificationChannel(MEDIUM_CHANNEL_ID, "Sound only",
NotificationManager.IMPORTANCE_DEFAULT)
val mediumChannel = NotificationChannel(
MEDIUM_CHANNEL_ID,
"Sound only",
NotificationManager.IMPORTANCE_DEFAULT
)
mediumChannel.description = "Incoming messages"
mediumChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
mediumChannel.enableVibration(false)
@ -1866,9 +1888,7 @@ class BaresipService: Service() {
intent,
PendingIntent.FLAG_IMMUTABLE
)
val deleteIntent =
Intent(this, BaresipService::class.java)
.setAction("Notification Dismissed")
val deleteIntent = Intent(this, BaresipService::class.java).setAction("Notification Dismissed")
val dpi = PendingIntent.getService(
this,
STATUS_REQ_CODE,
@ -1912,7 +1932,8 @@ class BaresipService: Service() {
else -> getString(R.string.call)
}
)
} else {
}
else {
builder.setStyle(null)
builder.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCategory(Notification.CATEGORY_SERVICE)
@ -1934,9 +1955,9 @@ class BaresipService: Service() {
if (i < uas.value.size) {
notificationLayout.setImageViewResource(resId, uas.value[i].status)
notificationLayout.setViewVisibility(resId, View.VISIBLE)
} else {
notificationLayout.setViewVisibility(resId, View.INVISIBLE)
}
else
notificationLayout.setViewVisibility(resId, View.INVISIBLE)
}
if (uas.value.size > 4)
notificationLayout.setViewVisibility(R.id.etc, View.VISIBLE)
@ -1970,8 +1991,8 @@ class BaresipService: Service() {
}
else
nm.notify(STATUS_NOTIFICATION_ID, notification)
} else {
if (isNotificationInCall) {
}
else if (isNotificationInCall) {
stopForeground(STOP_FOREGROUND_REMOVE)
// Only call startForeground to drop the "Call" type when the LAST call ends.
if (VERSION.SDK_INT >= 29)
@ -1983,7 +2004,6 @@ class BaresipService: Service() {
else
// Already in standby, just keep the notification current.
nm.notify(STATUS_NOTIFICATION_ID, notification)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to update notification: ${e.message}")
nm.notify(STATUS_NOTIFICATION_ID, notification)
@ -1993,21 +2013,20 @@ class BaresipService: Service() {
private fun foregroundServiceType(activeCall: Call? = null): Int {
var type = 0
if (VERSION.SDK_INT >= 30) {
if (VERSION.SDK_INT >= 29) {
if (activeCall != null) {
type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
if (ContextCompat.checkSelfPermission(this, RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED)
if (VERSION.SDK_INT >= 30) {
if (ContextCompat.checkSelfPermission(this, RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
}
}
if (VERSION.SDK_INT >= 34) {
type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
}
// Fallback for API 30-33 when no active call (specialUse not available)
if (type == 0 && VERSION.SDK_INT >= 30)
if (VERSION.SDK_INT >= 34)
type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
// Fallback for API 29-33 when no active call (specialUse not available)
if (type == 0 && VERSION.SDK_INT >= 29)
type = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
return type
}
@ -2062,14 +2081,13 @@ class BaresipService: Service() {
Log.d(TAG, "Auto-rejecting incoming PSTN hidden call")
telecomCall.disconnect()
toast(getString(R.string.hidden_call_blocked))
if (ua.account.callHistory) {
if (ua.account.callHistory)
Blocked(
ua.account.aor,
uri,
"invite",
GregorianCalendar().timeInMillis
).add()
}
return
}
if (ua.account.blockUnknown && Contact.contactName(e164Uri) == e164Uri) {
@ -2079,14 +2097,13 @@ class BaresipService: Service() {
String.format(getString(R.string.call_blocked),
Utils.friendlyUri(this, uri, ua.account))
)
if (ua.account.callHistory) {
if (ua.account.callHistory)
Blocked(
ua.account.aor,
uri,
"invite",
GregorianCalendar().timeInMillis
).add()
}
return
}
}
@ -2179,9 +2196,7 @@ class BaresipService: Service() {
calls.remove(call)
}
postServiceEvent(
ServiceEvent(
"call closed", arrayListOf(uap, callp), System.nanoTime()
)
ServiceEvent("call closed", arrayListOf(uap, callp), System.nanoTime())
)
}
if (!Call.inCall()) {
@ -2226,7 +2241,7 @@ class BaresipService: Service() {
val mobileUa = UserAgent(0L, account)
val isAirplaneModeOn = Settings.Global.getInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0
val sm = getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE) as android.telephony.SubscriptionManager
val hasActiveSubscription = if (checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE) ==
val hasActiveSubscription = if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) ==
PackageManager.PERMISSION_GRANTED)
!sm.activeSubscriptionInfoList.isNullOrEmpty()
else
@ -2264,14 +2279,12 @@ class BaresipService: Service() {
ua.status
else
R.drawable.circle_white
} else {
if (ua.status == R.drawable.circle_white) {
}
else if (ua.status == R.drawable.circle_white)
// Show "Red" (not yet in service)
circleRed.getValue(colorblind)
} else {
else
ua.status
}
}
if (ua.status != status) {
Log.d(TAG, "Updating Mobile status to $status")
ua.updateStatus(status)
@ -2320,9 +2333,7 @@ class BaresipService: Service() {
val diverterUri = call.diverterUri()
val contentText = if (diverterUri != "")
"${getString(R.string.is_calling)} " +
"(${getString(R.string.diverted_by)} " +
"${Utils.friendlyUri(this, diverterUri, ua.account)})"
"${getString(R.string.is_calling)} (${getString(R.string.diverted_by)} ${Utils.friendlyUri(this, diverterUri, ua.account)})"
else
getString(R.string.is_calling)
val caller = createPerson(this, peerUri, ua.account)
@ -2410,14 +2421,14 @@ class BaresipService: Service() {
vbTimer = Timer()
vbTimer!!.schedule(object : TimerTask() {
override fun run() {
if (VERSION.SDK_INT >= 33) {
if (VERSION.SDK_INT >= 33)
vibrator.vibrate(
effect,
android.os.VibrationAttributes.Builder()
.setUsage(android.os.VibrationAttributes.USAGE_RINGTONE)
.build()
)
} else {
else {
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
@ -2449,7 +2460,6 @@ class BaresipService: Service() {
// First, check if the ringer volume is actually non-zero
if (am.getStreamVolume(AudioManager.STREAM_RING) == 0) return false
// Finally, check the system "Vibrate for calls" setting.
// Although deprecated, it is the standard way to check the "Also vibrate for calls" toggle.
return try {
@Suppress("DEPRECATION")
Settings.System.getInt(
@ -2472,14 +2482,12 @@ class BaresipService: Service() {
)
val projection = arrayOf(ContactsContract.PhoneLookup.STARRED)
try {
val cursor = contentResolver
.query(phoneUri, projection, null, null, null)
val cursor = contentResolver.query(phoneUri, projection, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
val isStarred = it.getInt(0) == 1
if (isStarred) {
if (isStarred)
Log.d(TAG, "Caller '$callerNumber' is a starred contact.")
}
return isStarred
}
}
@ -2507,7 +2515,6 @@ class BaresipService: Service() {
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
mediaPlayer = MediaPlayer().apply {
setAudioAttributes(audioAttributes)
val afd = resources.openRawResourceFd(resourceId)
@ -2517,9 +2524,9 @@ class BaresipService: Service() {
prepare()
start()
}
} else {
Log.e(TAG, "Ringback tone $name.wav not found")
}
else
Log.e(TAG, "Ringback tone $name.wav not found")
}
}
@ -2533,7 +2540,6 @@ class BaresipService: Service() {
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build()
mediaPlayer = MediaPlayer().apply {
setAudioAttributes(audioAttributes)
val afd = resources.openRawResourceFd(resourceId)
@ -2546,9 +2552,9 @@ class BaresipService: Service() {
prepare()
start()
}
} else {
Log.e(TAG, "Busy tone $name.wav not found")
}
else
Log.e(TAG, "Busy tone $name.wav not found")
}
}
@ -2605,7 +2611,8 @@ class BaresipService: Service() {
return
}
}
} else if (!Call.inCall() && currentMode == MODE_NORMAL) {
}
else if (!Call.inCall() && currentMode == MODE_NORMAL) {
if (speakerPhone) {
Log.d(TAG, "Resetting speakerPhone UI state while idle")
speakerPhone = false
@ -2643,15 +2650,17 @@ class BaresipService: Service() {
else
android.telecom.CallAudioState.ROUTE_EARPIECE
)
} else if (!hasTelecom) {
}
else if (!hasTelecom) {
Log.d(TAG, "No Telecom connection, using AudioManager for speaker")
Utils.setSpeakerPhone(mainExecutor, am, speakerPhone)
} else {
}
else
for (c in Call.calls()) {
ConnectionService.setOutput(c.callp, speakerPhone)
}
}
} else {
else {
if (am.mode != MODE_NORMAL) {
am.mode = MODE_NORMAL
Log.d(TAG, "Manual Mode Guard: Resetting to MODE_NORMAL")
@ -2690,11 +2699,7 @@ class BaresipService: Service() {
speakerPhone = !speakerPhone
// Notify the UI to update the icon color
postServiceEvent(
ServiceEvent(
"speaker update,$speakerPhone",
arrayListOf(0L, 0L),
System.nanoTime()
)
ServiceEvent("speaker update,$speakerPhone", arrayListOf(0L, 0L), System.nanoTime())
)
// Apply the new audio route
ensureCommunicationMode()
@ -2706,18 +2711,17 @@ class BaresipService: Service() {
if (!proximityWakeLock.isHeld) {
Log.d(TAG, "Acquiring proximity wake lock")
proximityWakeLock.acquire()
} else {
}
else
Log.d(TAG, "Proximity wake lock already acquired")
}
} else {
if (proximityWakeLock.isHeld) {
else if (proximityWakeLock.isHeld) {
proximityWakeLock.release()
Log.d(TAG, "Released proximity wake lock")
} else {
}
else
Log.d(TAG, "Proximity wake lock is not held")
}
}
}
private fun updateNetwork() {
if (!isNativeReady) return
@ -2770,13 +2774,11 @@ class BaresipService: Service() {
wifiLock.acquire()
}
}
else {
if (wifiLock.isHeld) {
else if (wifiLock.isHeld) {
Log.d(TAG, "Releasing WiFi Lock")
wifiLock.release()
}
}
}
private fun linkAddresses(): MutableMap<String, String> {
val addresses = mutableMapOf<String, String>()
@ -2795,11 +2797,10 @@ class BaresipService: Service() {
}
}
}
if (hotSpotIsEnabled) {
if (hotSpotIsEnabled)
for ((k, v) in hotSpotAddresses)
if (afMatch(k))
addresses[k] = v
}
return addresses
}
@ -2833,9 +2834,9 @@ class BaresipService: Service() {
// Update if change
synchronized(dnsServers) {
if (servers != dnsServers) {
if (isServiceRunning && Config.updateDnsServers(servers) != 0) {
if (isServiceRunning && Config.updateDnsServers(servers) != 0)
Log.w(TAG, "Failed to update DNS servers '${servers}'")
} else {
else {
// Log.d(TAG, "Updated DNS servers: '${servers}'")
dnsServers = servers
return true
@ -2894,11 +2895,11 @@ class BaresipService: Service() {
airplaneModeReceiverRegistered = false
}
if (telephonyCallbackRegistered) {
if (VERSION.SDK_INT >= 31) {
if (VERSION.SDK_INT >= 31)
try {
telephonyManager.unregisterTelephonyCallback(telephonyCallback)
} catch (_: Exception) {}
} else {
else {
@Suppress("DEPRECATION")
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE)
}
@ -2927,11 +2928,10 @@ class BaresipService: Service() {
proximityWakeLock.release()
if (this::wifiLock.isInitialized)
wifiLock.release()
if (this::networkCallback.isInitialized) {
if (this::networkCallback.isInitialized)
try {
cm.unregisterNetworkCallback(networkCallback)
} catch (_: Exception) {}
}
if (androidContactsObserverRegistered) {
try {
contentResolver.unregisterContentObserver(androidContactsObserver)
@ -3003,9 +3003,8 @@ class BaresipService: Service() {
var blockRules = mutableListOf<BlockRule>()
fun isBlocked(uri: String): Boolean {
for (rule in blockRules) {
for (rule in blockRules)
if (rule.matches(uri)) return true
}
return false
}
@ -3112,8 +3111,7 @@ class BaresipService: Service() {
if (audioFocusRequest != null) {
Log.d(TAG, "Abandoning audio focus")
val am = ctx.getSystemService(AUDIO_SERVICE) as AudioManager
if (am.abandonAudioFocusRequest(audioFocusRequest!!) ==
AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
if (am.abandonAudioFocusRequest(audioFocusRequest!!) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
audioFocusRequest = null
else
Log.e(TAG, "Failed to abandon audio focus")
@ -3124,8 +3122,7 @@ class BaresipService: Service() {
return if (VERSION.SDK_INT < 31)
@Suppress("DEPRECATION")
am.isBluetoothScoOn
else
if (am.communicationDevice != null)
else if (am.communicationDevice != null)
am.communicationDevice!!.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO
else
false