屏幕锁定时Xamarin Android振动不起作用
当屏幕锁定时,我一直在尝试使我的Android手机振动,以下代码是接收SMS消息并振动。我已经看到屏幕上锁定的多个示例可以振动,但我永远无法正常工作。我是移动应用程序开发的新手。下面的代码在屏幕锁定时适合三星Galaxy Note 9。我在清单中设置了振动和接收SMS的权限。但是当屏幕锁定时,它只是失败。有人可以查看我的代码并在锁定屏幕时振动。
我非常感谢。请发布完整的示例,我可以再次使用我是移动开发的新手。
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver", Exported = true)]
[IntentFilter(new string[] { "android.provider.Telephony.SMS_RECEIVED" }, Priority = (int)IntentFilterPriority.HighPriority)]
public class MySMSReciver : BroadcastReceiver
{
public static readonly String INTENT_ACTION = "android.provider.Telephony.SMS_RECEIVED";
protected string message, address = "";
public override void OnReceive(Context context, Intent intent)
{
InvokeAbortBroadcast();
try
{
if (intent.Action != INTENT_ACTION) return;
var bundle = intent.Extras;
if (bundle == null)
{
return;
}
var pdus = bundle.Get("pdus").ToArray<Java.Lang.Object>();
var msgs = new SmsMessage[pdus.Length];
var sb = new StringBuilder();
String sender = null;
String messageBody = null;
for (int i = 0; i < msgs.Length; i++)
{
msgs[i] = SmsMessage.CreateFromPdu((byte[])pdus[i]);
messageBody = msgs[i].MessageBody;
if (sender == null)
{
sender = msgs[i].OriginatingAddress;
}
sb.Append(string.Format("SMS From: {0}{1}Body: {2}{1}", msgs[i].OriginatingAddress, System.Environment.NewLine, messageBody));
}
if (sender != null)
{
Toast.MakeText(context, "your SMS Message:" + sb.ToString(), ToastLength.Long).Show();
//works well but fails when screen is locked.
var duration = TimeSpan.FromSeconds(5);
Xamarin.Essentials.Vibration.Vibrate(duration);
}
else
{
ClearAbortBroadcast();
}
}
catch (Exception ex)
{
Toast.MakeText(context, "Error :" +ex.Message, ToastLength.Long).Show();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用前景服务,请参阅: https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/services/foreground-services
这是其中的一个示例:https://github.com/xamarin/monodroid-samples/tree/main/ApplicationFundamentals/ServiceSamples/ForegroundServiceDemo< /a>
You can try to use foreground service,refer to:https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services
And here is a sample of it:https://github.com/xamarin/monodroid-samples/tree/main/ApplicationFundamentals/ServiceSamples/ForegroundServiceDemo