-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathCallActivity.kt
839 lines (733 loc) · 30.5 KB
/
CallActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
package org.fossify.phone.activities
import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.media.AudioManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.telecom.Call
import android.telecom.CallAudioState
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.children
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import org.fossify.commons.extensions.*
import org.fossify.commons.helpers.*
import org.fossify.commons.models.SimpleListItem
import org.fossify.phone.R
import org.fossify.phone.databinding.ActivityCallBinding
import org.fossify.phone.dialogs.DynamicBottomSheetChooserDialog
import org.fossify.phone.extensions.*
import org.fossify.phone.helpers.*
import org.fossify.phone.models.AudioRoute
import org.fossify.phone.models.CallContact
import kotlin.math.max
import kotlin.math.min
class CallActivity : SimpleActivity() {
companion object {
fun getStartIntent(context: Context): Intent {
val openAppIntent = Intent(context, CallActivity::class.java)
openAppIntent.flags = Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
return openAppIntent
}
}
private val binding by viewBinding(ActivityCallBinding::inflate)
private var isSpeakerOn = false
private var isMicrophoneOff = false
private var isCallEnded = false
private var callContact: CallContact? = null
private var proximityWakeLock: PowerManager.WakeLock? = null
private var screenOnWakeLock: PowerManager.WakeLock? = null
private var callDuration = 0
private val callContactAvatarHelper by lazy { CallContactAvatarHelper(this) }
private val callDurationHandler = Handler(Looper.getMainLooper())
private var dragDownX = 0f
private var stopAnimation = false
private var viewsUnderDialpad = arrayListOf<Pair<View, Float>>()
private var dialpadHeight = 0f
private var audioRouteChooserDialog: DynamicBottomSheetChooserDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
if (CallManager.getPhoneState() == NoCall) {
finish()
return
}
updateTextColors(binding.callHolder)
initButtons()
audioManager.mode = AudioManager.MODE_IN_CALL
addLockScreenFlags()
CallManager.addListener(callCallback)
updateCallContactInfo(CallManager.getPrimaryCall())
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
updateState()
}
override fun onResume() {
super.onResume()
updateState()
updateNavigationBarColor(getProperBackgroundColor())
if (config.isUsingSystemTheme) {
updateStatusbarColor(getProperBackgroundColor())
}
}
override fun onDestroy() {
super.onDestroy()
CallManager.removeListener(callCallback)
disableProximitySensor()
if (screenOnWakeLock?.isHeld == true) {
screenOnWakeLock!!.release()
}
}
override fun onBackPressed() {
if (binding.dialpadWrapper.isVisible()) {
hideDialpad()
return
} else {
super.onBackPressed()
}
val callState = CallManager.getState()
if (callState == Call.STATE_CONNECTING || callState == Call.STATE_DIALING) {
endCall()
}
}
private fun initButtons() = binding.apply {
if (config.disableSwipeToAnswer) {
callDraggable.beGone()
callDraggableBackground.beGone()
callLeftArrow.beGone()
callRightArrow.beGone()
callDecline.setOnClickListener {
endCall()
}
callAccept.setOnClickListener {
acceptCall()
}
} else {
handleSwipe()
}
callToggleMicrophone.setOnClickListener {
toggleMicrophone()
}
callToggleSpeaker.setOnClickListener {
changeCallAudioRoute()
}
callDialpad.setOnClickListener {
toggleDialpadVisibility()
}
dialpadClose.setOnClickListener {
hideDialpad()
}
callToggleHold.setOnClickListener {
toggleHold()
}
callAdd.setOnClickListener {
Intent(applicationContext, DialpadActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(this)
}
}
callSwap.setOnClickListener {
CallManager.swap()
}
callMerge.setOnClickListener {
CallManager.merge()
}
callManage.setOnClickListener {
startActivity(Intent(this@CallActivity, ConferenceActivity::class.java))
}
callEnd.setOnClickListener {
endCall()
}
dialpadInclude.apply {
dialpad0Holder.setOnClickListener { dialpadPressed('0') }
dialpad1Holder.setOnClickListener { dialpadPressed('1') }
dialpad2Holder.setOnClickListener { dialpadPressed('2') }
dialpad3Holder.setOnClickListener { dialpadPressed('3') }
dialpad4Holder.setOnClickListener { dialpadPressed('4') }
dialpad5Holder.setOnClickListener { dialpadPressed('5') }
dialpad6Holder.setOnClickListener { dialpadPressed('6') }
dialpad7Holder.setOnClickListener { dialpadPressed('7') }
dialpad8Holder.setOnClickListener { dialpadPressed('8') }
dialpad9Holder.setOnClickListener { dialpadPressed('9') }
arrayOf(
dialpad0Holder,
dialpad1Holder,
dialpad2Holder,
dialpad3Holder,
dialpad4Holder,
dialpad5Holder,
dialpad6Holder,
dialpad7Holder,
dialpad8Holder,
dialpad9Holder,
dialpadPlusHolder,
dialpadAsteriskHolder,
dialpadHashtagHolder
).forEach {
it.background = ResourcesCompat.getDrawable(resources, R.drawable.pill_background, theme)
it.background?.alpha = LOWER_ALPHA_INT
}
dialpad0Holder.setOnLongClickListener { dialpadPressed('+'); true }
dialpadAsteriskHolder.setOnClickListener { dialpadPressed('*') }
dialpadHashtagHolder.setOnClickListener { dialpadPressed('#') }
}
dialpadWrapper.setBackgroundColor(getProperBackgroundColor())
arrayOf(dialpadClose, callSimImage).forEach {
it.applyColorFilter(getProperTextColor())
}
val bgColor = getProperBackgroundColor()
val inactiveColor = getInactiveButtonColor()
arrayOf(
callToggleMicrophone, callToggleSpeaker, callDialpad,
callToggleHold, callAdd, callSwap, callMerge, callManage
).forEach {
it.applyColorFilter(bgColor.getContrastColor())
it.background.applyColorFilter(inactiveColor)
}
arrayOf(
callToggleMicrophone, callToggleSpeaker, callDialpad,
callToggleHold, callAdd, callSwap, callMerge, callManage
).forEach { imageView ->
imageView.setOnLongClickListener {
if (!imageView.contentDescription.isNullOrEmpty()) {
toast(imageView.contentDescription.toString())
}
true
}
}
callSimId.setTextColor(getProperTextColor().getContrastColor())
dialpadInput.disableKeyboard()
dialpadWrapper.onGlobalLayout {
dialpadHeight = dialpadWrapper.height.toFloat()
}
}
@SuppressLint("ClickableViewAccessibility")
private fun handleSwipe() = binding.apply {
var minDragX = 0f
var maxDragX = 0f
var initialDraggableX = 0f
var initialLeftArrowX = 0f
var initialRightArrowX = 0f
var initialLeftArrowScaleX = 0f
var initialLeftArrowScaleY = 0f
var initialRightArrowScaleX = 0f
var initialRightArrowScaleY = 0f
var leftArrowTranslation = 0f
var rightArrowTranslation = 0f
val isRtl = isRTLLayout
callAccept.onGlobalLayout {
minDragX = if (isRtl) {
callAccept.left.toFloat()
} else {
callDecline.left.toFloat()
}
maxDragX = if (isRtl) {
callDecline.left.toFloat()
} else {
callAccept.left.toFloat()
}
initialDraggableX = callDraggable.left.toFloat()
initialLeftArrowX = callLeftArrow.x
initialRightArrowX = callRightArrow.x
initialLeftArrowScaleX = callLeftArrow.scaleX
initialLeftArrowScaleY = callLeftArrow.scaleY
initialRightArrowScaleX = callRightArrow.scaleX
initialRightArrowScaleY = callRightArrow.scaleY
leftArrowTranslation = if (isRtl) {
callAccept.x
} else {
-callDecline.x
}
rightArrowTranslation = if (isRtl) {
-callAccept.x
} else {
callDecline.x
}
if (isRtl) {
callLeftArrow.setImageResource(R.drawable.ic_chevron_right_vector)
callRightArrow.setImageResource(R.drawable.ic_chevron_left_vector)
}
callLeftArrow.applyColorFilter(getColor(R.color.md_red_400))
callRightArrow.applyColorFilter(getColor(R.color.md_green_400))
startArrowAnimation(callLeftArrow, initialLeftArrowX, initialLeftArrowScaleX, initialLeftArrowScaleY, leftArrowTranslation)
startArrowAnimation(callRightArrow, initialRightArrowX, initialRightArrowScaleX, initialRightArrowScaleY, rightArrowTranslation)
}
callDraggable.drawable.mutate().setTint(getProperTextColor())
callDraggableBackground.drawable.mutate().setTint(getProperTextColor())
var lock = false
callDraggable.setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
dragDownX = event.x
callDraggableBackground.animate().alpha(0f)
stopAnimation = true
callLeftArrow.animate().alpha(0f)
callRightArrow.animate().alpha(0f)
lock = false
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
dragDownX = 0f
callDraggable.animate().x(initialDraggableX).withEndAction {
callDraggableBackground.animate().alpha(0.2f)
}
callDraggable.setImageDrawable(getDrawable(R.drawable.ic_phone_down_vector))
callDraggable.drawable.mutate().setTint(getProperTextColor())
callLeftArrow.animate().alpha(1f)
callRightArrow.animate().alpha(1f)
stopAnimation = false
startArrowAnimation(callLeftArrow, initialLeftArrowX, initialLeftArrowScaleX, initialLeftArrowScaleY, leftArrowTranslation)
startArrowAnimation(callRightArrow, initialRightArrowX, initialRightArrowScaleX, initialRightArrowScaleY, rightArrowTranslation)
}
MotionEvent.ACTION_MOVE -> {
callDraggable.x = min(maxDragX, max(minDragX, event.rawX - dragDownX))
when {
callDraggable.x >= maxDragX - 50f -> {
if (!lock) {
lock = true
callDraggable.performHapticFeedback()
if (isRtl) {
endCall()
} else {
acceptCall()
}
}
}
callDraggable.x <= minDragX + 50f -> {
if (!lock) {
lock = true
callDraggable.performHapticFeedback()
if (isRtl) {
acceptCall()
} else {
endCall()
}
}
}
callDraggable.x > initialDraggableX -> {
lock = false
val drawableRes = if (isRtl) {
R.drawable.ic_phone_down_red_vector
} else {
R.drawable.ic_phone_green_vector
}
callDraggable.setImageDrawable(getDrawable(drawableRes))
}
callDraggable.x <= initialDraggableX -> {
lock = false
val drawableRes = if (isRtl) {
R.drawable.ic_phone_green_vector
} else {
R.drawable.ic_phone_down_red_vector
}
callDraggable.setImageDrawable(getDrawable(drawableRes))
}
}
}
}
true
}
}
private fun startArrowAnimation(arrow: ImageView, initialX: Float, initialScaleX: Float, initialScaleY: Float, translation: Float) {
arrow.apply {
alpha = 1f
x = initialX
scaleX = initialScaleX
scaleY = initialScaleY
animate()
.alpha(0f)
.translationX(translation)
.scaleXBy(-0.5f)
.scaleYBy(-0.5f)
.setDuration(1000)
.withEndAction {
if (!stopAnimation) {
startArrowAnimation(this, initialX, initialScaleX, initialScaleY, translation)
}
}
}
}
private fun dialpadPressed(char: Char) {
CallManager.keypad(char)
binding.dialpadInput.addCharacter(char)
}
private fun changeCallAudioRoute() {
val supportAudioRoutes = CallManager.getSupportedAudioRoutes()
if (supportAudioRoutes.contains(AudioRoute.BLUETOOTH)) {
createOrUpdateAudioRouteChooser(supportAudioRoutes)
} else {
val isSpeakerOn = !isSpeakerOn
val newRoute = if (isSpeakerOn) CallAudioState.ROUTE_SPEAKER else CallAudioState.ROUTE_WIRED_OR_EARPIECE
CallManager.setAudioRoute(newRoute)
}
}
private fun createOrUpdateAudioRouteChooser(routes: Array<AudioRoute>, create: Boolean = true) {
val callAudioRoute = CallManager.getCallAudioRoute()
val items = routes
.sortedByDescending { it.route }
.map {
SimpleListItem(id = it.route, textRes = it.stringRes, imageRes = it.iconRes, selected = it == callAudioRoute)
}
.toTypedArray()
if (audioRouteChooserDialog?.isVisible == true) {
audioRouteChooserDialog?.updateChooserItems(items)
} else if (create) {
audioRouteChooserDialog = DynamicBottomSheetChooserDialog.createChooser(
fragmentManager = supportFragmentManager,
title = R.string.choose_audio_route,
items = items
) {
audioRouteChooserDialog = null
CallManager.setAudioRoute(it.id)
}
}
}
private fun updateCallAudioState(route: AudioRoute?) {
if (route != null) {
isMicrophoneOff = audioManager.isMicrophoneMute
updateMicrophoneButton()
isSpeakerOn = route == AudioRoute.SPEAKER
val supportedAudioRoutes = CallManager.getSupportedAudioRoutes()
binding.callToggleSpeaker.apply {
val bluetoothConnected = supportedAudioRoutes.contains(AudioRoute.BLUETOOTH)
contentDescription = if (bluetoothConnected) {
getString(R.string.choose_audio_route)
} else {
getString(if (isSpeakerOn) R.string.turn_speaker_off else R.string.turn_speaker_on)
}
// show speaker icon when a headset is connected, a headset icon maybe confusing to some
if (route == AudioRoute.WIRED_HEADSET) {
setImageResource(R.drawable.ic_volume_down_vector)
} else {
setImageResource(route.iconRes)
}
}
toggleButtonColor(binding.callToggleSpeaker, enabled = route != AudioRoute.EARPIECE && route != AudioRoute.WIRED_HEADSET)
createOrUpdateAudioRouteChooser(supportedAudioRoutes, create = false)
if (isSpeakerOn) {
disableProximitySensor()
} else {
enableProximitySensor()
}
}
}
private fun toggleMicrophone() {
isMicrophoneOff = !isMicrophoneOff
audioManager.isMicrophoneMute = isMicrophoneOff
CallManager.inCallService?.setMuted(isMicrophoneOff)
updateMicrophoneButton()
}
private fun updateMicrophoneButton() {
toggleButtonColor(binding.callToggleMicrophone, isMicrophoneOff)
binding.callToggleMicrophone.contentDescription = getString(if (isMicrophoneOff) R.string.turn_microphone_on else R.string.turn_microphone_off)
}
private fun toggleDialpadVisibility() {
if (binding.dialpadWrapper.isVisible()) hideDialpad() else showDialpad()
}
private fun findVisibleViewsUnderDialpad(): Sequence<Pair<View, Float>> {
return binding.ongoingCallHolder.children.filter { it.isVisible() }.map { view -> Pair(view, view.alpha) }
}
private fun showDialpad() {
binding.dialpadWrapper.apply {
translationY = dialpadHeight
alpha = 0f
animate()
.withStartAction { beVisible() }
.setInterpolator(AccelerateDecelerateInterpolator())
.setDuration(200L)
.alpha(1f)
.translationY(0f)
.start()
}
viewsUnderDialpad.clear()
viewsUnderDialpad.addAll(findVisibleViewsUnderDialpad())
viewsUnderDialpad.forEach { (view, _) ->
view.run {
animate().scaleX(0f).alpha(0f).withEndAction { beGone() }.duration = 250L
animate().scaleY(0f).alpha(0f).withEndAction { beGone() }.duration = 250L
}
}
}
private fun hideDialpad() {
binding.dialpadWrapper.animate()
.withEndAction { binding.dialpadWrapper.beGone() }
.setInterpolator(AccelerateDecelerateInterpolator())
.setDuration(200L)
.alpha(0f)
.translationY(dialpadHeight)
.start()
viewsUnderDialpad.forEach { (view, alpha) ->
view.run {
animate().withStartAction { beVisible() }.setInterpolator(OvershootInterpolator()).scaleX(1f).alpha(alpha).duration = 250L
animate().withStartAction { beVisible() }.setInterpolator(OvershootInterpolator()).scaleY(1f).alpha(alpha).duration = 250L
}
}
}
private fun toggleHold() {
val isOnHold = CallManager.toggleHold()
toggleButtonColor(binding.callToggleHold, isOnHold)
binding.callToggleHold.contentDescription = getString(if (isOnHold) R.string.resume_call else R.string.hold_call)
binding.holdStatusLabel.beVisibleIf(isOnHold)
}
private fun updateOtherPersonsInfo(avatarUri: String?) {
if (callContact == null) {
return
}
binding.apply {
callerNameLabel.text = callContact!!.name.ifEmpty { getString(R.string.unknown_caller) }
if (callContact!!.number.isNotEmpty() && callContact!!.number != callContact!!.name) {
callerNumber.text = callContact!!.number
if (callContact!!.numberLabel.isNotEmpty()) {
callerNumber.text = "${callContact!!.number} - ${callContact!!.numberLabel}"
}
} else {
callerNumber.beGone()
}
Glide.with(callerAvatar)
.load(avatarUri)
.apply(RequestOptions.circleCropTransform())
.into(callerAvatar)
}
}
private fun getContactNameOrNumber(contact: CallContact): String {
return contact.name.ifEmpty {
contact.number.ifEmpty {
getString(R.string.unknown_caller)
}
}
}
@SuppressLint("MissingPermission")
private fun checkCalledSIMCard() {
try {
val simLabels = getAvailableSIMCardLabels()
if (simLabels.size > 1) {
simLabels.forEachIndexed { index, sim ->
if (sim.handle == CallManager.getPrimaryCall()?.details?.accountHandle) {
binding.apply {
callSimId.text = sim.id.toString()
callSimId.beVisible()
callSimImage.beVisible()
callSimImage.applyColorFilter(sim.color.adjustSimColorForBackground(getProperBackgroundColor()))
}
val acceptDrawableId = when (index) {
0 -> R.drawable.ic_phone_one_vector
1 -> R.drawable.ic_phone_two_vector
else -> R.drawable.ic_phone_vector
}
val rippleBg = resources.getDrawable(R.drawable.ic_call_accept, theme) as RippleDrawable
val layerDrawable = rippleBg.findDrawableByLayerId(R.id.accept_call_background_holder) as LayerDrawable
layerDrawable.setDrawableByLayerId(R.id.accept_call_icon, getDrawable(acceptDrawableId))
binding.callAccept.setImageDrawable(rippleBg)
}
}
}
} catch (ignored: Exception) {
}
}
private fun updateCallState(call: Call) {
val state = call.getStateCompat()
when (state) {
Call.STATE_RINGING -> callRinging()
Call.STATE_ACTIVE -> callStarted()
Call.STATE_DISCONNECTED -> endCall()
Call.STATE_CONNECTING, Call.STATE_DIALING -> initOutgoingCallUI()
Call.STATE_SELECT_PHONE_ACCOUNT -> showPhoneAccountPicker()
}
val statusTextId = when (state) {
Call.STATE_RINGING -> R.string.is_calling
Call.STATE_CONNECTING, Call.STATE_DIALING -> R.string.dialing
else -> 0
}
binding.apply {
if (statusTextId != 0) {
callStatusLabel.text = getString(statusTextId)
}
callManage.beVisibleIf(call.hasCapability(Call.Details.CAPABILITY_MANAGE_CONFERENCE))
setActionButtonEnabled(callSwap, state == Call.STATE_ACTIVE)
setActionButtonEnabled(callMerge, state == Call.STATE_ACTIVE)
}
}
private fun updateState() {
val phoneState = CallManager.getPhoneState()
if (phoneState is SingleCall) {
updateCallState(phoneState.call)
updateCallOnHoldState(null)
val state = phoneState.call.getStateCompat()
val isSingleCallActionsEnabled = (state == Call.STATE_ACTIVE || state == Call.STATE_DISCONNECTED
|| state == Call.STATE_DISCONNECTING || state == Call.STATE_HOLDING)
setActionButtonEnabled(binding.callToggleHold, isSingleCallActionsEnabled)
setActionButtonEnabled(binding.callAdd, isSingleCallActionsEnabled)
} else if (phoneState is TwoCalls) {
updateCallState(phoneState.active)
updateCallOnHoldState(phoneState.onHold)
}
updateCallAudioState(CallManager.getCallAudioRoute())
}
private fun updateCallOnHoldState(call: Call?) {
val hasCallOnHold = call != null
if (hasCallOnHold) {
getCallContact(applicationContext, call) { contact ->
runOnUiThread {
binding.onHoldCallerName.text = getContactNameOrNumber(contact)
}
}
}
binding.apply {
onHoldStatusHolder.beVisibleIf(hasCallOnHold)
controlsSingleCall.beVisibleIf(!hasCallOnHold)
controlsTwoCalls.beVisibleIf(hasCallOnHold)
}
}
private fun updateCallContactInfo(call: Call?) {
getCallContact(applicationContext, call) { contact ->
if (call != CallManager.getPrimaryCall()) {
return@getCallContact
}
callContact = contact
val avatar = if (!call.isConference()) contact.photoUri else null
runOnUiThread {
updateOtherPersonsInfo(avatar)
checkCalledSIMCard()
}
}
}
private fun acceptCall() {
CallManager.accept()
}
private fun initOutgoingCallUI() {
enableProximitySensor()
binding.incomingCallHolder.beGone()
binding.ongoingCallHolder.beVisible()
}
private fun callRinging() {
binding.incomingCallHolder.beVisible()
}
private fun callStarted() {
enableProximitySensor()
binding.incomingCallHolder.beGone()
binding.ongoingCallHolder.beVisible()
callDurationHandler.removeCallbacks(updateCallDurationTask)
callDurationHandler.post(updateCallDurationTask)
}
private fun showPhoneAccountPicker() {
if (callContact != null) {
getHandleToUse(intent, callContact!!.number) { handle ->
CallManager.getPrimaryCall()?.phoneAccountSelected(handle, false)
}
}
}
private fun endCall() {
CallManager.reject()
disableProximitySensor()
audioRouteChooserDialog?.dismissAllowingStateLoss()
if (isCallEnded) {
finishAndRemoveTask()
return
}
try {
audioManager.mode = AudioManager.MODE_NORMAL
} catch (ignored: Exception) {
}
isCallEnded = true
if (callDuration > 0) {
runOnUiThread {
binding.callStatusLabel.text = "${callDuration.getFormattedDuration()} (${getString(R.string.call_ended)})"
Handler().postDelayed({
finishAndRemoveTask()
}, 3000)
}
} else {
binding.callStatusLabel.text = getString(R.string.call_ended)
finish()
}
}
private val callCallback = object : CallManagerListener {
override fun onStateChanged() {
updateState()
}
override fun onAudioStateChanged(audioState: AudioRoute) {
updateCallAudioState(audioState)
}
override fun onPrimaryCallChanged(call: Call) {
callDurationHandler.removeCallbacks(updateCallDurationTask)
updateCallContactInfo(call)
updateState()
}
}
private val updateCallDurationTask = object : Runnable {
override fun run() {
callDuration = CallManager.getPrimaryCall().getCallDuration()
if (!isCallEnded) {
binding.callStatusLabel.text = callDuration.getFormattedDuration()
callDurationHandler.postDelayed(this, 1000)
}
}
}
@SuppressLint("NewApi")
private fun addLockScreenFlags() {
if (isOreoMr1Plus()) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
)
}
if (isOreoPlus()) {
(getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager).requestDismissKeyguard(this, null)
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
}
try {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
screenOnWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "org.fossify.phone:full_wake_lock")
screenOnWakeLock!!.acquire(5 * 1000L)
} catch (e: Exception) {
}
}
private fun enableProximitySensor() {
if (!config.disableProximitySensor && (proximityWakeLock == null || proximityWakeLock?.isHeld == false)) {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
proximityWakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "org.fossify.phone:wake_lock")
proximityWakeLock!!.acquire(60 * MINUTE_SECONDS * 1000L)
}
}
private fun disableProximitySensor() {
if (proximityWakeLock?.isHeld == true) {
proximityWakeLock!!.release()
}
}
private fun setActionButtonEnabled(button: ImageView, enabled: Boolean) {
button.apply {
isEnabled = enabled
alpha = if (enabled) 1.0f else LOWER_ALPHA
}
}
private fun getActiveButtonColor() = getProperPrimaryColor()
private fun getInactiveButtonColor() = getProperTextColor().adjustAlpha(0.10f)
private fun toggleButtonColor(view: ImageView, enabled: Boolean) {
if (enabled) {
val color = getActiveButtonColor()
view.background.applyColorFilter(color)
view.applyColorFilter(color.getContrastColor())
} else {
view.background.applyColorFilter(getInactiveButtonColor())
view.applyColorFilter(getProperBackgroundColor().getContrastColor())
}
}
}