Tried this
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
webView.Source = "https://www.example.com/";
webView.Navigating += WebView_Navigating;
}
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
// Set the User-Agent string to a desktop browser user agent
webView.Eval("navigator.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'");
}
}
please help in changing to desktop mode using Xamarin
In Android you have to implement a custom renderer.
Create a Custom Renderer(DesktopWebViewRenderer.cs) in Android folder:
[assembly: ExportRenderer(typeof(WebView), typeof(DesktopWebViewRenderer))]
namespace forms.Droid
{
public class DesktopWebViewRenderer : WebViewRenderer
{
public DesktopWebViewRenderer(Context context): base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
Control.Settings.UserAgentString
= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36";
}
}
}
Related
So far my code looks like this:
1. Dowload the APK file and save it into internal storege:
Using DependencyServices
App.xaml.cs
IDownloader downloader = DependencyService.Get<IDownloader>();
protected override void OnStart(){
downloader.OnFileDownloaded+=OnFileDownloaded;
downloader.DownloadFile("http://localhost:8080/download","folder");
}
private void OnFileDownloaded(object sender,DownloadEventArgs e) {
if(e.FileSaved) {
App.Current.MainPage.DisplayAlert("XF Downloader","File Saved Successfully","Close");
} else {
App.Current.MainPage.DisplayAlert("XF Downloader","Error while saving the file","Close");
}
}
Android : AndroidDownloader.cs
[assembly: Dependency(typeof(NoguianaNucleo.Droid.AndroidDownloader))]
namespace NoguianaNucleo.Droid {
public class AndroidDownloader: IDownloader {
public event EventHandler<DownloadEventArgs> OnFileDownloaded;
public void DownloadFile(string url,string folder) {
string pathToNewFolder = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),folder);
Directory.CreateDirectory(pathToNewFolder);
try {
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted+=new AsyncCompletedEventHandler(Completed);
string pathToNewFile = Path.Combine(pathToNewFolder,"nucleo.apk");
webClient.DownloadFileAsync(new Uri(url),pathToNewFile);
} catch(Exception ex) {
if(OnFileDownloaded!=null)
OnFileDownloaded.Invoke(this,new DownloadEventArgs(false));
}
}
private void Completed(object sender,AsyncCompletedEventArgs e) {
if(e.Error!=null) {
App.Current.MainPage.DisplayAlert("Error", e.Error.Message,"Ok");
if(OnFileDownloaded!=null)
OnFileDownloaded.Invoke(this,new DownloadEventArgs(false));
} else {
if(OnFileDownloaded!=null)
OnFileDownloaded.Invoke(this,new DownloadEventArgs(true));
}
}
}
}
2. Intall the APK file from the internal storege:
App.xaml.cs
public void OpenApk(string filepath) {
Java.IO.File file = new Java.IO.File(filepath);
Intent install = new Intent(Intent.ActionView);
// Old Approach
if(Android.OS.Build.VERSION.SdkInt<Android.OS.BuildVersionCodes.N) {
install.SetFlags(ActivityFlags.NewTask|ActivityFlags.GrantReadUriPermission);
install.SetDataAndType(Android.Net.Uri.FromFile(file),"application/vnd.android.package-archive"); //mimeType
} else {
Android.Net.Uri apkURI = Android.Support.V4.Content.FileProvider.GetUriForFile(Android.App.Application.Context,Android.App.Application.Context.ApplicationContext.PackageName+".fileprovider",file);
install.SetDataAndType(apkURI,"application/vnd.android.package-archive");
install.AddFlags(ActivityFlags.NewTask);
install.AddFlags(ActivityFlags.GrantReadUriPermission);
}
Android.App.Application.Context.StartActivity(install);
}
This last function doesn't work. I think Android.Support its not support any more.
I also tried this:
var downloadUri = Android.Net.Uri.Parse("/data/user/0/noguiana.nucleo/files/noguiana/nucleo.apk");
Intent install = new Intent(Intent.ActionInstallPackage);
install.AddFlags(ActivityFlags.GrantReadUriPermission);
install.AddFlags(ActivityFlags.GrantWriteUriPermission);
install.AddFlags(ActivityFlags.GrantPersistableUriPermission);
install.SetDataAndType(downloadUri,"application/vnd.android.package-archive");
context.StartActivity(install);
Nothing works
Do you know other way to install APK by programmatically in Xamarin.Forms (Android)?
Use PackageInstaller instead.
ActionView and ACTION_INSTALL_PACKAGE had been deprecated in API level 29.
Have you tried this solution?
Android PackageInstaller not installing APK
I have a WinForms Application in C# and I am trying to get the HTML-Code of a page via a GET-Request with the HTTPS-Protocol, but I am not able to get any value.
I have tried several solutions, but I can not fix this issue on my own.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using System.IO;
namespace sharpFUT
{
public partial class frmShapfut : Form
{
string HTMLCode;
public frmShapfut()
{
InitializeComponent();
}
private async void btnSearch_Click(object sender, EventArgs e)
{
try
{
HTMLCode = await getHTMLCode(tbxPlayerURL.Text);
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
MessageBox.Show(HTMLCode);
}
private async Task<string> getHTMLCode(string url)
{
var handler = new HttpClientHandler()
{
AllowAutoRedirect = true
};
HttpClient httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
var result = await httpClient.GetStringAsync(url);
return result;
}
}
}
Edit: Added link to project I created:
https://drive.google.com/file/d/1A4XGKdxeC22_wqtNEtenLxYbgCp3I_dA/view?usp=sharing
I have a very basic multi-platform application created I Visual Studio 2019 (Windows 10) with 4 projects:
Source Project
Android
iOS
UWP
I added the MacOS project following these instructions:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/other/mac
The application compiles but loads a blank form and does not show any of the Xamarin forms as per the UWP, iOS and Android apps.
I next created an empty Multi-Platform application natively on a Mac - added the MacOS as per the above instructions and get the same outcome, a blank form loading.
The code I am using in the Mac project is the link above.
// AppDelelegate.cs
using AppKit;
using Foundation;
using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;
using pbTrader;
namespace pbTrader.MacOS
{
[Register("AppDelegate")]
public class AppDelegate : FormsApplicationDelegate
{
NSWindow window;
public AppDelegate()
{
var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled;
var rect = new CoreGraphics.CGRect(200, 1000, 1024, 768);
window = new NSWindow(rect, style, NSBackingStore.Buffered, false);
window.Title = "Xamarin.Forms on Mac!"; // choose your own Title here
window.TitleVisibility = NSWindowTitleVisibility.Hidden;
}
public override NSWindow MainWindow
{
get { return window; }
}
public override void DidFinishLaunching(NSNotification notification)
{
Forms.Init();
LoadApplication(new App());
base.DidFinishLaunching(notification);
}
public override void WillTerminate(NSNotification notification)
{
// Insert code here to tear down your application
}
}
}
// Main.cs
using AppKit;
namespace pbTrader.MacOS
{
static class MainClass
{
static void Main(string[] args)
{
NSApplication.Init();
NSApplication.SharedApplication.Delegate = new AppDelegate(); // add this line
NSApplication.Main(args);
}
}
}
I'm creating an Android App in C# Xamarin.
Is there a way to "listen" for volume up/down key presses when an App goes into "background" mode, i.e. when a user "locks" their phone?
I've created several Service objects and made them "resident" by issuing the command 'StartCommandResult.Sticky'.
Any sample C# Xamarin code would be much appreciated.
You do not need to create a background service, just start a another task to listen the volume control. If the application do not be killed the task will run on the background.
public class MainActivity : Activity
{
private int currentVolume;
public AudioManager mAudioManager;
private int maxVolume;
private bool isDestory;
Android.Media.MediaPlayer player;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
player = Android.Media.MediaPlayer.Create(this, Resource.Raw.SampleAudio);
SetContentView (Resource.Layout.Main);
mAudioManager = (AudioManager)GetSystemService(Context.AudioService);
maxVolume = mAudioManager.GetStreamMaxVolume(Stream.Music);
onVolumeChangeListener();
player.Start();
}
protected override void OnDestroy()
{
base.OnDestroy();
isDestory = true;
}
private Task voluemChangeTask;
public void onVolumeChangeListener()
{
currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
voluemChangeTask = new Task(ChangeVolume);
voluemChangeTask.Start();
}
public void ChangeVolume()
{
while (!isDestory)
{
int count = 0;
try
{
Thread.Sleep(20);
}
catch (Exception e)
{
}
if (currentVolume < mAudioManager.GetStreamVolume(Stream.Music))
{
System.Console.WriteLine("volunm+");
count++;
currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
mAudioManager.SetStreamVolume(Stream.Music, currentVolume, VolumeNotificationFlags.RemoveSoundAndVibrate);
}
if (currentVolume > mAudioManager.GetStreamVolume(Stream.Music))
{
System.Console.WriteLine("volunm-");
count++;
currentVolume = mAudioManager.GetStreamVolume(Stream.Music);
mAudioManager.SetStreamVolume(Stream.Music, currentVolume, VolumeNotificationFlags.RemoveSoundAndVibrate);
}
}
}
}
I have tested it in the real device with screen lock and got the log:
Good morning everybody.
I simply want to automatical login to the website when I start the C# program.
So I started a new Webform project, simply added a button and a website frame.
Main:
namespace SG_Helper
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
And the form with a function behind the button:
namespace SG_Helper
{
public partial class Form1 : Form
{
public string cookie = string.Empty;
public WebClient wc = new WebClient();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string loginData = "loginname=***&loginpwd=***&switch=login";
wc.BaseAddress = #"http://wbk2.schulterglatze.de/";
string cookie = string.Empty;
wc.Headers.Add("Content-Type: application/x-www-form-urlencoded");
wc.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
wc.Headers.Add("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
wc.Headers.Add("Accept-Encoding: identity");
wc.Headers.Add("Accept-Language: en-US,en;q=0.8");
wc.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3");
wc.Headers.Add("Cookie", cookie);
string response = wc.UploadString("http://wbk2.schulterglatze.de/?ref=0", "POST", loginData);
cookie = wc.ResponseHeaders["Set-Cookie"].ToString();
//System.Windows.Forms.MessageBox.Show(response);
webBrowser1.DocumentText = wc.DownloadString("http://wbk2.schulterglatze.de/masterfile/");
//webBrowser1.Navigate("http://wbk2.schulterglatze.de/masterfile");
}
}
}
I am unsure how to debug to find the correct way.
Can anyone tell me how to approach the problem?
Where do I need to debug to get the hint to the problem?
Thanks and greets
Daniel