Forum Visual Studio
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Find Which program is app

hi

I want to know which app is running in Xamarin.Forms. If the app I want was open, run a Method

Please help

Answers

  • LeonLuLeonLu Member, Xamarin Team Xamurai
    edited October 23

    You can create an dependenceService to acheve it.

    In android, you can use UsageStatsManager the one second's running application.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Android.App;
    using Android.App.Usage;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using App9.Droid;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(GetRunningApplicationService))]
    namespace App9.Droid
    {
        class GetRunningApplicationService : IGetRunningApplication
        {
            Context context = Android.App.Application.Context;
            public void OpenFunctionIntent()
            {
    
                Intent intent = new Intent(Android.Provider.Settings.ActionUsageAccessSettings);
                context.StartActivity(intent);
            }
            public   List<string> getRunningApplication()
            {
    
    
                List<string> vs = new List<string>();
                UsageStatsManager mUsageStatsManager = (UsageStatsManager)context.ApplicationContext.GetSystemService("usagestats");
                long time = TimeUtils.CurrentTimeMillis();
    
                List<UsageStats> stats = mUsageStatsManager.QueryUsageStats(UsageStatsInterval.Daily, time - 1, time).ToList<UsageStats>();
    
                foreach (var item in stats)
                {
                    vs.Add(item.PackageName);
                }
    
    
                return vs;
            }
        }
    
        public class TimeUtils
        {
            private static readonly DateTime Jan1st1970 = new DateTime
            (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    
            public static long CurrentTimeMillis()
            {
                return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
            }
        }
    }
    

    Note: you need add the <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" /> permission. and execute OpenFunctionIntent method firstly.

Sign In or Register to comment.