屏幕关闭时,前台服务的呼叫将停止工作



我有以下代码可以拨打电话:

public static void CallPhoneNumber(this Context context, string phoneNumber)
{
var uri = Android.Net.Uri.Parse("tel:" + phoneNumber);
var callIntent = new Intent(Intent.ActionCall, uri);
callIntent.AddFlags(ActivityFlags.NewTask);
callIntent.AddFlags(ActivityFlags.FromBackground);
context.StartActivity(callIntent);
}

我在正在运行的前台服务中拨打电话。基本上,该服务会检测条件(在我的情况下是GPS位置(并拨打电话。它与我的Pixel 2XL和Android 9配合得很好。但是升级到Android 10后,我遇到了一个新问题。

首先,我被迫添加新的权限FOREGROUND_SERVICE。添加,前台服务按预期工作并拨打电话 - 但仅在手机"活动"时,我的意思是当屏幕关闭时它不处于"睡眠"模式。

如果屏幕关闭 - 服务有效,我可以跟踪活动,但它不会拨打电话。

adb logcat显示此警告(第一行为Info,第二行为Warning(:

02-04 20:48:00.923  1315  7951 I ActivityTaskManager: START u0 {act=android.intent.action.CALL dat=tel:xxxxxxxxxxxx flg=0x10000004 cmp=com.android.server.telecom/.components.UserCallActivity} from uid 10174
02-04 20:48:00.924  1315  7951 W ActivityTaskManager: Background activity start [callingPackage: MyApp; callingUid: 10175; isCallingUidForeground: false; isCallingUidPersistentSystemProcess: false; realCallingUid: 10174; isRealCallingUidForeground: false; isRealCallingUidPersistentSystemProcess: false; originatingPendingIntent: null; isBgStartWhitelisted: false; intent: Intent { act=android.intent.action.CALL dat=tel:xxxxxxxxxxxx flg=0x10000004 cmp=com.android.server.telecom/.components.UserCallActivity }; callerApp: ProcessRecord{43f3a72 13957:MyApp/u0a174}]

我认为您应该看看"部分唤醒锁"以防止手机的"睡眠模式"。

https://developer.android.com/training/scheduling/wakelock

在主活动中.cs创建一个唤醒锁对象,并在OnCreate函数下配置唤醒锁:

private PowerManager.WakeLock _wl = null;
protected override void OnCreate(Bundle savedInstanceState)
{
// ... Your own code here
PowerManager pmanager = (PowerManager)this.GetSystemService("power");
_wl = pmanager.NewWakeLock(WakeLockFlags.Partial, "myapp_wakelock");
_wl?.SetReferenceCounted(false);
_wl?.Acquire();
}
public override void OnDestroy()
{
_wl?.Release();
base.OnDestroy();
}

不要忘记在 AndroidManifest 中添加权限.xml:

<uses-permission android:name="android.permission.WAKE_LOCK" />

这个解决方案可以工作,但你需要小心翼翼,因为对于某些制造商来说,如果你的应用使用许多资源,负责 CPU "始终活动"状态的前台服务可能会被杀死。在某些情况下,它们会添加"省电模式"选项模式,您需要直接在设置中禁用它才能毫无问题地运行您的应用程序。

希望这能有所帮助

使用 TelecomManager。像这样:

Uri uri = Uri.fromParts("tel", phoneNumber, null);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TelecomManager telecomManager = (TelecomManager) getInstance().getSystemService(Context.TELECOM_SERVICE);
telecomManager.placeCall(uri, new Bundle());
}
else
{
Intent callIntent = new Intent(Intent.ACTION_CALL, uri);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
}
}

最新更新