[英]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.