Xamarin Form Code
Create Xaml Page and add following Code
MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TestApp.MainPage">
<StackLayout Margin="10,10,10,10">
<Label Text="https://www.w3schools.com/html/mov_bbb.mp4" />
<Button Text="Click Here to Play Video In Default Player" x:Name="btnPlayVideo" Clicked="BtnPlayVideo_Clicked" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestApp.Services;
using Xamarin.Forms;
namespace TestApp
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void BtnPlayVideo_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IMediaService>().PlayVideo("https://www.w3schools.com/html/mov_bbb.mp4");
}
}
}
Now create the IMediaService Interface and add the following Code.
IMediaService.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace TestApp.Services
{
public interface IMediaService
{
void PlayVideo(string uri);
}
}
Now Implement this interface in Platform specific
TestApp.Android
Create the MediaService.cs Class that Implement IMediaService Interface.
MediaService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.CurrentActivity;
using TestApp.Droid.Services;
using TestApp.Services;
[assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
namespace TestApp.Droid.Services
{
public class MediaService : IMediaService
{
Context CurrentContext => CrossCurrentActivity.Current.Activity;
public void PlayVideo(string uri)
{
Intent intent = new Intent();
intent.SetAction(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.Parse(uri), "video/*");
((Activity)CurrentContext).StartActivity(intent);
}
}
}
Note: For accessing the CurrentContext Install the NuGet Package (Plugin.CurrentActivity) from NuGet Package Manager
No comments:
Post a Comment