Resources raw folder localize in xamarin.forms - c#

I'm Xamarin Developer
I want to play *.mp3 or *.wav file in the localized application
so I divided the file like that
and I implement code in dependency service like
public void OnePlaySound()
{
_mediaPlayer = MediaPlayer.Create(context, Resource.Raw.wavone);
_mediaPlayer.Start();
_mediaPlayer.Completion += delegate
{
if (_mediaPlayer != null)
{
_mediaPlayer.Stop();
_mediaPlayer.Release();
_mediaPlayer = null;
}
};
}
but _mediaPlayer always returns null..
is there any solution to use the localizing raw files?

I understand from your description that you want to use MediaPlayer to play an audio file in the Resource/Raw folder using dependencyservice in Xamarin.Forms. Here is an example:
First, create interface named IPlayAudio in .Net standard library project(shared code).
public interface IPlayAudio
{
void playaudio();
}
Then create one class that implements IPlayAudio in the Android platform, the platform implementations must be registered with the DependencyService, so that Xamarin.Forms can locate them at runtime.
[assembly: Dependency(typeof(PlayAudiomethod))]
namespace playvideo.Droid
{
public class PlayAudiomethod : IPlayAudio
{
private MediaPlayer _player;
public void playaudio()
{
_player = MediaPlayer.Create(MainActivity.mac, Resource.Raw.MyAudio);
_player.Start();
}
}
}
For MainActivity.mac, please create static member called "mac" in MainActivity and set it after the call to LoadApplication.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity mac;
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);
LoadApplication(new App());
mac = this;
}
}
Now you can play audio from the Xamarin.Forms shared code.
private void mediaplayer_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IPlayAudio>().playaudio();
}
Note: please set xxx.mp3 Build Action as AndroidResource.

Related

NotificationCompat.Builder is giving Error :Java.Lang.IllegalStateException: 'System services not available to Activities before onCreate()

I wrote a code in a class to notify me using the notificationCompat.Builder and it's giving me this error, It's telling me that I've done something before OnCreate(), Inside MainActivity I'm declaring another class in order to Inherit CountDownTimer class and inside the OnFinished () method I wrote this small code and it's giving me an Error. Can anyone help me ? I believe using this.activity is causing the problem but I don't know a workaround for this :
public NotificationCompat.Builder builder;
MainActivity activity = new MainActivity();
NotificationManagerCompat notificationManager;
public override void OnFinish()
{
Toast.MakeText(Application.Context ,"Finished",ToastLength.Short).Show();
builder = new NotificationCompat.Builder(this.activity, CHANNEL_ID).SetAutoCancel(true)
.SetContentTitle("CountDownTimer !!")
.SetSmallIcon(Resource.Drawable.abc_ic_star_black_48dp)
.SetContentText($" Stopped"); // display.
notificationManager = NotificationManagerCompat.From(this.activity); Error // Java.Lang.IllegalStateException: 'System services not available to Activities...
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
}
This is code is just to illustrate Reference to current Activity :
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
static Context context;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
context = this;
}
public class CountDown1 : CountDownTimer
{
public NotificationCompat.Builder builder;
NotificationManagerCompat notificationManager;
public override void OnFinish()
{
Toast.MakeText(Application.Context ,"Finished",ToastLength.Short).Show();
builder = new NotificationCompat.Builder(context, CHANNEL_ID).SetAutoCancel(true)
.SetContentTitle("CountDownTimer !!")
.SetSmallIcon(Resource.Drawable.abc_ic_star_black_48dp)
.SetContentText($" Stopped"); // the message to display.
notificationManager = NotificationManagerCompat.From(context);// Java.Lang.IllegalStateException: 'System services not available to Activities before onCreate()'
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
}
}
}
}

Xamarin.Forms - change device orientation based on device resolution

is there any chance to force change screen orientation based device screen resolution?
Have app for tablets, but I want to run app on mobile device too. I have a few pages, where I need to change orientation to landscape on phone, because then is my listview a litle bit messy.
Thank you for any advice and I apologize for the bad English :)
You can use MessagingCenter to achieve that .
For example , when navigating from MainPage to PageTwo in Forms , the content page of PageTwo as follow :
public partial class PageTwo : ContentPage
{
public PageTwo()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send(this, "allowLandScape");
}
//during page close setting back to portrait
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Send(this, "quitLandScape");
}
}
In Android , need to modify MainActivity as follow :
[Activity(Label = "ForceOrientation", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
//allowing the device to change the screen orientation based on the rotation
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);
LoadApplication(new App());
MessagingCenter.Subscribe<PageTwo>(this, "allowLandScape", sender =>
{
RequestedOrientation = ScreenOrientation.Landscape;
});
//during page close setting back to portrait
MessagingCenter.Subscribe<PageTwo>(this, "quitLandScape", sender =>
{
RequestedOrientation = ScreenOrientation.Portrait;
});
}
}
In iOS , we need to create a PageTwoRenderer as follow :
[assembly: ExportRenderer(typeof(PageTwo), typeof(PageTwoRenderer))]
namespace ForceOrientation.iOS
{
public class PageTwoRenderer : PageRenderer
{
public PageTwoRenderer()
{
MessagingCenter.Subscribe<PageTwo>(this, "allowLandScape", sender =>
{
UIDevice.CurrentDevice.SetValueForKey(NSNumber.FromNInt((int)(UIInterfaceOrientation.LandscapeLeft)), new NSString("orientation"));
});
//during page close setting back to portrait
MessagingCenter.Subscribe<PageTwo>(this, "quitLandScape", sender =>
{
UIDevice.CurrentDevice.SetValueForKey(NSNumber.FromNInt((int)(UIInterfaceOrientation.Portrait)), new NSString("orientation"));
});
}
}
}
==============================Update=============================
We can use Xamarin.Essentials: Device Information to check whether the device is Phone , Tablet or other devices .
DeviceInfo.Idiom correlates a constant string that maps to the type of device the application is running on. The values can be checked with the DeviceIdiom struct:
DeviceIdiom.Phone – Phone
DeviceIdiom.Tablet – Tablet
DeviceIdiom.Desktop – Desktop
DeviceIdiom.TV – TV
DeviceIdiom.Watch – Watch
DeviceIdiom.Unknown – Unknown
Modiied PageTwo as follow :
protected override void OnAppearing()
{
base.OnAppearing();
var idiom = DeviceInfo.Idiom;
if (idiom == DeviceIdiom.Phone)
{
MessagingCenter.Send(this, "allowLandScape");
}
}
//during page close setting back to portrait
protected override void OnDisappearing()
{
base.OnDisappearing();
var idiom = DeviceInfo.Idiom;
if (idiom == DeviceIdiom.Phone)
{
MessagingCenter.Send(this, "quitLandScape");
}
}
You can force set orientation on these few pages
// on IOS -> AppDelegate.cs
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
{
if (Device.Idiom == TargetIdiom.Phone ) {
{
return UIInterfaceOrientationMask.Landscape;
}
else
{
return UIInterfaceOrientationMask.Portrait;
}
}
// and on Android -> MainActivity.cs do the same if else in here
protected override void OnCreate(Bundle savedInstanceState)
{
if (Device.Idiom == TargetIdiom.Phone)
{
RequestedOrientation = ScreenOrientation.Landscape;
}
else
{
RequestedOrientation = ScreenOrientation.Portrait;
}
}
You can check about Device class more in documentation https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/device#deviceidiom

How to capture an image in xamarin android using the camera in fragment

I am a beginner in xamarin android.I want to take photo using my device camera,I am using the following code to to capture the image but, I got an exception when running the code
Here is my Fragment.CS
public class ScanFragments : Fragment
{
ImageView imageView;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public static ScanFragments NewInstance()
{
var scan = new ScanFragments { Arguments = new Bundle() };
return scan;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
imageView =View.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
var btnCamera =View. FindViewById<Button>(Resource.Id.btnCamera);
btnCamera.Click += BtnCamera_Click;
return inflater.Inflate(Resource.Layout.ScanLayout, null);
}
private void BtnCamera_Click(object sender, EventArgs e)
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 0);
}
}
Well now I see your mistake its actually very simple you get the null reference because of the following reasons
1.OnCreateView does not contain a definition of View basically what I mean here is View is a class which you are using as an object of that class.
2.The actual way I recommend using fragments is first you define it an XML or an AXML as its foreground view in on OnCreateView as follows :
return inflater.Inflate(Resource.Layout.ScanLayout, null);
3.Override the OnViewCreated method and use its View to do all your work as follows :
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
imageView =view.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
var btnCamera =view. FindViewById<Button>(Resource.Id.btnCamera);
btnCamera.Click += BtnCamera_Click;
}
4.For details related to the Android Activity and Fragment lifecycle check here
Goodluck!

There was a prblm parsing the package while installing .apk file of xamarin

There was a problem parsing the package while installing .apk file.
Given below is configuration and code.
VS2015
MainActivity.cs
namespace WebAp
{
[Activity(Label = "TC", MainLauncher = true, Theme ="#android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
private WebView web_view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
web_view = FindViewById<WebView>(Resource.Id.webview);
web_view.Settings.JavaScriptEnabled = true;
web_view.LoadUrl("http://www.tc.com");
web_view.SetWebViewClient(new HelloWebViewClient());
}
public class HelloWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
}
public override bool OnKeyDown(Android.Views.Keycode keyCode, Android.Views.KeyEvent e)
{
if (keyCode == Android.Views.Keycode.Back && web_view.CanGoBack())
{
web_view.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
}
Configurataion :
enter image description here
Thats it my code. I was also try different API for Compile, Min and target version.
Please help me thanks.

Can't reference to newly added layout in Xamarin

I wanna point out that i'm a total newbie in Xamarin.
My goal is to create simple app that after you push the button, it will jump to another layout. My problem is, that after i created a new layout(called layout1) and new activity, I can't reference to this layout in my MainActivity.
freshly created Activity:
namespace Layouts
{
[Activity(Label = "Activity1")]
public class Activity1 : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
}
}
}
And my MainActivity:
namespace Layouts
{
[Activity(Label = "Layouts", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button>(Resource.Id.button);
button1.Click += delegate
{
StartActivity(typeof(layout1)); //can't reference layout1 there
};
}
}
}
Any help will be great, thanks :)
StartActivity(typeof(Activity1));

Categories