当我的应用程序崩溃或挂起时,有没有办法在Android上停止音频?

时间:2015-03-31 01:23:36

标签: c# android xamarin

我使用Xamarin Studio为Android编写了一个应用程序。有时,由于其他代码,应用程序将挂起并变得无响应。当用户单击主页按钮时,音频继续播放而不是停止。有没有办法让“挂起”的应用程序知道它已被放入后台并强制音频暂停?

protected override void OnDestroy ()
{
    DependencyService.Get<IMediaController>().Stop();

    // Call base method
    base.OnDestroy ();
}

protected override void OnSleep()
{
    DependencyService.Get<IMediaController>().Pause();
}

1 个答案:

答案 0 :(得分:0)

我已经确定执行此操作的方法是监控Android运行任务。这使我能够确定我的应用程序是否已经背景化。我有一个在整个应用程序生命周期中运行的线程,它通常在OnSleep中被杀死​​。如果未调用OnSleep,则该线程将确定应用程序无响应,并将调用OnSleep。这适用于Xamarin。我从这篇文章中得到了我的想法。 how to check the top activity from android app in background service

//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");
}