Why my XamarinMediaManager can't play HLS? - xamarin

I am about to play HLS on the android device by Xamarin.Forms(5.0.0.2012).
I referenced the XamarinMediaManager Nuget Package(1.0.8)
And the android version is 10.0(Q).
Here is my code:
<?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:mm="clr-namespace:MediaManager.Forms;assembly=MediaManager.Forms"
x:Class="Test.Pages.RootPage" NavigationPage.HasNavigationBar="False" >
<ContentPage.Content>
<Grid>
<mm:VideoView VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="http://live4.tdm.com.mo/ch1/_definst_/ch1.live/playlist.m3u8" ShowControls="False" x:Name="Player" AutoPlay="True" />
</Grid>
</ContentPage.Content>
</ContentPage>
And here is the code in MainActivity of the android project:
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using MediaManager;
namespace Test.Droid
{
[Activity(Label = "Test", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
CrossMediaManager.Current.Init(this);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
After the program ran, it always can't play anything.
What's wrong with my code? Thank you.

In code behind, write following code :
var item = await CrossMediaManager.Current.Extractor.CreateMediaItem("https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8");
item.MediaType = MediaType.Hls;
await CrossMediaManager.Current.Play(item);
For better understanding, please go through following HLS Video sample application

Related

xamarin Flyoutpage change text color

enter image description here
Hello friend
How can I change the color of the text in the title in the picture I am using flyoutpage
How can I change the color of the text in the title in the picture I am using flyoutpage
Do you mean the text color of tabs of TabbedPage in your screenshot?
If yes, then in android, you can try to create a Tabbar.xml in folder layout and adding following code:
<?xml version="1.0" encoding="utf-8" ?>
<com.google.android.material.tabs.TabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabTextColor="#color/your_unselected_text_color"
app:tabSelectedTextColor="#color/your_selected_text_color"
app:tabIndicatorColor="#color/your_indicator_color"
/>
Then inflate this layout with code:
FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar;
The whole code of MainActivity.cs
      
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate (Bundle bundle)
            {
FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar;
base.OnCreate (bundle);
            global::Xamarin.Forms.Forms.Init (this, bundle);
            LoadApplication (new App ());
            }
      }
On IOS, you can use custom renderer to achieve this.
[assembly: ExportRenderer(typeof(TabbedPage), typeof(TabbedPageRenderer))]
namespace MyApp.iOS
{
public class TabbedPageRenderer : TabbedRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
TabBar.TintColor = UIColor.White;
TabBar.BarTintColor = UIColor.Black;
TabBar.BackgroundColor = UIColor.Gray;
}
}
}

Exception : System.NullReferenceException: 'Object reference not set to an instance of an object.'

I'm trying to create a simple Qr code scanner application who have a single view like this:
But when I tried to press the "CLICK" button to lunch the scanner I got this excption:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
this is the main.xaml page:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="scanner.MainPage">
<StackLayout Spacing="10">
<Button Text="Click"
x:Name="btnScan"
Clicked="btnScan_Clicked"/>
<Entry x:Name="txtBarcode"
Placeholder="Text Do scan"/>
</StackLayout>
</ContentPage>
the main.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btnScan_Clicked(object sender, EventArgs e)
{
try
{
var scanner = DependencyService.Get<Interface1>();
var result = await scanner.ScanAsync();
if (result != null)
{
txtBarcode.Text = result;
}
}
catch (Exception ex)
{ throw;
}
the service:
internal class QrScanningService : Interface1
{
public async Task<string> ScanAsync()
{
var optionsDefault = new MobileBarcodeScanningOptions();
var optionsCustom = new MobileBarcodeScanningOptions();
var scanner = new MobileBarcodeScanner()
{
TopText = "Scan the QR Code",
BottomText = "Please Wait",
};
var scanResult = await scanner.Scan(optionsCustom);
return scanResult.Text;
}
}
I had done a simple and meet the same problem. So I searched it on the internet and found that the plugin need to be initialized when you use the ZXing.Net.Mobile package.
So you can add the initialized code in to the OnCreate method of the MainActivity. Such as:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
MobileBarcodeScanner.Initialize(Application);// this line initialize the plugin
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
You can check the document about it :https://github.com/Redth/ZXing.Net.Mobile#android
And on the ios check this link:https://github.com/Redth/ZXing.Net.Mobile#ios

Android image localisation in Xamarin Form

I have a Xamarin Form application which has a language dropdown so user can select the application language. When user select a language I call:
CultureInfo culture = CultureInfo.CreateSpecificCulture(language);
System.Globalization.CultureInfo.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
AppResources.Culture = culture;
The application works fine and picks the strings from AppResources.{language}.resx
My problem is when localising an image. As per Microsoft's suggestion I have added my image to Resources/drawable folders inside the android project. In my case, I added thanks.jpg to Resources/drawable and Resources/drawable-fr. But it only shows the image on Resources/drawable folder even when I select fr-FR as language, however I found out if instead of changing the application language(culture), I change the device language, the device show the correct image(the image inside Resources/drawable-fr). I was wondering if there is any way to fix this issue.
You can create a dependence service to fix it.
First of all, create a interface.
public interface IChangeService
{
void ChangeIanguage(string lang);
}
We used it in the this format code in the xamarin forms.
<StackLayout>
<TimePicker></TimePicker>
<Image WidthRequest="100">
<Image.Source>
<OnPlatform x:TypeArguments="ImageSource">
<On Platform="iOS, Android" Value="flag.png" />
<On Platform="UWP" Value="Assets/Images/flag.png" />
</OnPlatform>
</Image.Source>
</Image>
<Button Text="Change" Clicked="Button_Clicked"></Button>
</StackLayout>
Here is background code.
public partial class LocalizedXamlPage : ContentPage
{
public LocalizedXamlPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, System.EventArgs e)
{
DependencyService.Get<IChangeService>().ChangeIanguage("en");
}
}
Then achieve the interface in the android platform. If we change the localization, we need it to work at the runtime, we should restart our application.
[assembly: Dependency(typeof(ChangeLanguageService))]
namespace UsingResxLocalization.Droid
{
public class ChangeLanguageService : IChangeService
{
public void ChangeIanguage(string lang = "in")
{
LanguageManager.ChangeLanguage(MainActivity.instance, lang);
//restart your application.
Intent intent = new Intent(MainActivity.instance, typeof(MainActivity));
intent.SetFlags(ActivityFlags.ClearTask | ActivityFlags.NewTask);
MainActivity.instance.StartActivity(intent);
}
}
}
Then we need to create a BaseActivity(because we change the Locale in android, we should use the same Context.) and LanguageManager(change the localization at the runtime)
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.Support.V7.App;
using Android.Views;
using Android.Widget;
using Java.Util;
using Xamarin.Forms.Platform.Android;
namespace UsingResxLocalization.Droid
{
public class BaseActivity : FormsAppCompatActivity
{
protected override void AttachBaseContext(Context #base)
{
base.AttachBaseContext(LanguageManager.LoadLanguage(#base));
}
}
public class LanguageManager
{
private const string MYLANGUAGE = "myLanguage";
private const string MYPREF = "myPreference";
public static Context LoadLanguage(Context context)
{
var loadedLanguage = GetLanguage(context, Locale.Default.Language);
return ChangeLanguage(context, loadedLanguage);
}
public static Context ChangeLanguage(Context context, string language)
{
SaveLanguage(context, language);
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
return ChangeForAPI24(context, language);
}
return ChangeForLegacy(context, language);
}
private static string GetLanguage(Context context, string Language)
{
var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
return privatePreference.GetString(MYLANGUAGE, Language);
}
private static void SaveLanguage(Context context, string language)
{
var privatePreference = context.GetSharedPreferences(MYPREF, FileCreationMode.Private);
var editor = privatePreference.Edit();
editor.PutString(MYLANGUAGE, language);
editor.Apply();
}
private static Context ChangeForAPI24(Context context, string language)
{
// for api >= 24
var locale = new Locale(language);
Locale.Default = locale;
var configuration = context.Resources.Configuration;
configuration.SetLocale(locale);
configuration.SetLayoutDirection(locale);
return context.CreateConfigurationContext(configuration);
}
private static Context ChangeForLegacy(Context context, string language)
{
var locale = new Locale(language);
Locale.Default = locale;
var resources = context.Resources;
var configuration = resources.Configuration;
configuration.Locale = locale;
resources.UpdateConfiguration(configuration, resources.DisplayMetrics);
return context;
}
}
}
To make the mainAcitvity extend the BaseActivity.cs. And expose the public static MainActivity instance;,
[Activity(Label = "UsingResxLocalization", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : BaseActivity
{
public static MainActivity instance;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
instance = this;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
Here is runinng GIF.
========Update=========
I make a test with France flag by changing language to fr when the device language is English.
I upload my demo to you, you can test it.
https://github.com/851265601/LocalzationDemo/blob/master/LocalzationDemoWithFlag.zip
If you want to change the text of Button or other label, when you click the Button, Please add CultureInfo.CurrentUICulture = new CultureInfo("fr", false); as well in the click event. You can see this GIF.

how open a pdf file from assents in an xamarin Android forms

I want to open a PDF file from assents folder to activity in Xamarin Android
in MainActivity.cs
using Com.Joanzapata.Pdfview;
using Com.Joanzapata.Pdfview.Listener;
namespace openpdf
{
[Activity(Label = "openpdf", MainLauncher = true)]
public class MainActivity : Activity
{
PDFView pdf;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
**pdf = FindViewById<PDFView>(Resource.Id.pDFView1);
pdf.FromAsset("finished.pdf").Load();**
}
}
}
Main.Axml
<com.joanzapata.pdfview.PDFView
android:layout_width="match_parent"
android:layout_height="548.5dp"
android:id="#+id/pDFView1" />

What did I do wrong on setting up MvvmCross 6.0?

I am new to MvvmCross 6.0 and Xamarin.
I am trying to follow the tutorial here that for MvvmCrosss 5.5
I followed the explanation,
Created App.xaml as MvxFormsApplication
<?xml version="1.0" encoding="utf-8" ?>
<core:MvxFormsApplication xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:core="clr-namespace:MvvmCross.Forms.Core;assembly=MvvmCross.Forms"
x:Class="App3.App">
</core:MvxFormsApplication>
CoreApp.cs as MvxApplication and runs RegisterAppStart(); in my overrided Initialize()
public class CoreApp : MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
CreatableTypes()
.EndingWith("Client")
.AsInterfaces()
.RegisterAsLazySingleton();
// register the appstart object
RegisterAppStart<MainPageViewModel>();
}
}
MainPageViewModel to inherited MvxViewModel
public class MainPageViewModel : MvxViewModel
{
}
View that created as MvxContentPage with type MainPageViewModel
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="Center"
HorizontalOptions="Center" />
Removed MainActivity and created a file called MainApplication.cs as follow
[Activity(Label = "MvvmcrossGettingStarted", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize |
ConfigChanges.Orientation)]
public class MainActivity : MvxFormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
var startup = Mvx.Resolve<IMvxAppStart>();
startup.Start();
InitializeForms(bundle);
}
}
public class Setup : MvxFormsAndroidSetup
{
public Setup():base()
{
}
protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies
.Union(new[] { typeof(App).GetTypeInfo().Assembly })
.Except(new[] { this.GetType().Assembly })
);
protected override Application CreateFormsApplication()
{
return new App();
}
protected override IMvxApplication CreateApp() => new CoreApp();
}
However what I started the app, its gives me null exception saying "bundle" parameter is null in OnCreated method.
P.S. The tutorial mention to create the Setup.cs, but I have no idea how does that Setup.cs being run by the code.... I see no where that is referencing it.
I'm not sure why you're looking at the version 5.5 tutorial while working with v 6.0. Try following step by step guide, from same author, but for version 6.0
You might also want to download Nick's sample, from his GitHub repo, to check how things work.

Resources