[英]Is there a way to stop audio on Android when my app crashes or hangs?
我已经使用Xamarin Studio为Android编写了一个应用程序。 有时,由于其他代码,该应用程序将挂起并变得无响应。 当用户单击“主页”按钮时,音频将继续播放而不是停止播放。 是否有一种方法可以让“挂起”的应用程序知道已将其置于后台并强制音频暂停?
protected override void OnDestroy ()
{
DependencyService.Get<IMediaController>().Stop();
// Call base method
base.OnDestroy ();
}
protected override void OnSleep()
{
DependencyService.Get<IMediaController>().Pause();
}
我已确定执行此操作的方法是监视Android运行任务。 这使我能够确定我的应用程序是否已后台运行。 我有一个贯穿应用程序生命周期的线程,通常在OnSleep中被杀死。 如果未调用OnSleep,则该线程将确定该应用程序无响应,并将调用OnSleep。 这是给Xamarin的。 我从这篇文章中得到了我的想法。 如何在后台服务中从android应用检查顶部活动
//Returns the top running task information
private static ActivityManager activityManager;
private static Android.App.ActivityManager.RunningTaskInfo runningTaskInfo;
public static ComponentName GetTopActivity()
{
if(activityManager == null)
{
activityManager = (ActivityManager) Application.Context.GetSystemService(Context.ActivityService);
}
IList<Android.App.ActivityManager.RunningTaskInfo> runningTasks =
activityManager.GetRunningTasks(1);
if(runningTasks != null && runningTasks.Count > 0)
{
runningTaskInfo = runningTasks[0];
return runningTaskInfo.TopActivity;
}
else
{
return null;
}
}
//This called from my thread every 2 seconds
public bool IsAppVisible()
{
//have to do a complicated version of this to determine the current running tasks //and whether our app is the most prominent.
Android.Content.ComponentName componentName = AndroidUtils.GetTopActivity();
bool isCurrentActivity;
if(componentName != null)
{
isCurrentActivity = string.Compare(componentName.PackageName, "myPackage") == 0;
}
else
{
isCurrentActivity = false;
}
return isCurrentActivity;
}
if(DependencyService.Get<IDeviceUtility>().IsAppVisible() == false)
{
//This needs to be manually called if the app becomes completely unresponive
OnSleep();
Debug.WriteLine("App is no longer visible");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.