How to open location settings in android using xamarin - c#

I try to open location settings in android using this tutorial, but in this method:
public void OpenSettings()
{
}
I don't know what to write to openned location settings.
Do I need additional libraries ?
I write this code:
public interface ILocSettings
{
void OpenSettings();
}
public void OpenSettings()
{
}
In the GPS button method I write this code:
var myAction = await DisplayAlert("Location", "Please Turn On Location", "OK", "CANCEL");
if (myAction)
{
if (Device.RuntimePlatform == global::Xamarin.Forms.Device.Android)
{
//DependencyService.Get<ISettingsService>().OpenSettings();
global::Xamarin.Forms.DependencyService.Get<ILocSettings>().OpenSettings();
}
else
{
_ = DisplayAlert("Device", "You are using some other shit", "YEP");
}
}
else
{
_ = DisplayAlert("Alert", "User Denied Permission", "OK");
}
So the message appear, but I don't know what to write in the OpenSettings() to open GPS location settings on the phone..

There is a package that will make opening the App settings way easier.
just write:
CrossPermissions.Current.OpenAppSettings();
Plugin name Plugin.Permissions :)

Opening other Activities on Android is done through Intents. To open Location Settings you can use the ACTION_LOCATION_SOURCE_SETTINGS intent.
Something like this would probably work:
var intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings);
Android.App.Application.Context.StartActivity(intent);
If Android doesn't like the Application Context, you might need to resolve the top Activity and use that as your Context instead.
If you are using Xamarin.Essentials you can get the top activity with: Platform.CurrentActivity:
var intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings);
Platform.CurrentActivity.StartActivity(intent);

Related

PCLStorage NuGetPackage not allow creating folder or file on device

I have a problem with creating folder with nuget package PCLStorage, I cannot create folder.
Nothing appear inside my files folder. I,m using my device not emulator there is android version 8.0
public async Task WriteDataAsync(string filename, string data)
{
string folderName = "SignatureSotrage";
IFolder folder = FileSystem.Current.LocalStorage;
folder = await folder.CreateFolderAsync(folderName, CreationCollisionOption.ReplaceExisting);
}
Here is a code where I run this function:
public ICommand AddCustomerCommand => new Command(async () =>
{
Signature = await SignatureFromStream();
// Signature should be != null
var customer = new Customer()
{
FullName = this.FullName,
IsAccepted = this.IsAccepted,
Birthday = this.Birthday
};
if(Signature != null)
{
customer.Image = this.Signature.ToString();
}
else
{
await Application.Current.MainPage.DisplayAlert("Błąd", "Nie wszystkie pola zostały poprawnie wypełnione", "OK");
return;
}
await DependencyService.Get<IFileHelper>().WriteDataAsync("signature.txt", "this is file");
//_context.Customers.Add(customer);
//_context.SaveChanges();
});
did you debug your code & check if the file/folder is actually getting created by your code or else it enters the catch block and goes with the normal flow?
Check for UserPermissions every time for reading & write permission before doing any operations on the storage. You can add the Nugget packet Plugin.Permission it handles everything for you, it adds both the permission in the manifest.
For checking user permissions always try calling CheckForStoragePermissions() before performing any operations on storage.(*DialogService is CustomDialogBox)
if( !await CheckForStoragePermissions() )
{
DialogService.Alert("Invalid Permission", "User declined permission for this action");
return;
}
private async Task<bool> CheckForStoragePermissions()
{
PermissionStatus storagePermissionStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storagePermissionStatus != PermissionStatus.Granted)
{
Dictionary<Permission, PermissionStatus> storagePermissionResult = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Storage);
if (storagePermissionResult.ContainsKey(Permission.Storage))
{
storagePermissionStatus = storagePermissionResult[Permission.Storage];
}
}
return storagePermissionStatus == PermissionStatus.Granted;
}
I test the sample code on GitHub. https://github.com/dsplaisted/PCLStorage
Based on my test the folder path would like:
/data/user/0/PCLStorage.Test.Android/files/
It is a internal storage. You couldn't see the files without root permission. https://learn.microsoft.com/en-us/xamarin/android/platform/files/#working-with-internal-storage
If you want to see the files in internal storage, you could use adb tool. Please refer to the way in the link. How to write the username in a local txt file when login success and check on file for next login?

How can I open a .pdf file in the browser from a Xamarin UWP project?

I have a Xamarin Project where I generate a .pdf file from scratch and save it in my local storage. This works perfectly fine and can find it and open it in the disk where I saved it. However, I need to open the .pdf file immediately after creation programmatically.
I already tried different variations using Process and ProcessStartInfo but these just throw errors like "System.ComponentModel.Win32Exception: 'The system cannot find the file specified'" and "'System.PlatformNotSupportedException'".
This is basically the path I am trying to open using Process.
var p = Process.Start(#"cmd.exe", "/c start " + #"P:\\Receiving inspection\\Inspection Reports\\" + timestamp + ".pdf");
I also tried ProcessStartInfo using some variations but I'm getting the same errors all over and over.
var p = new Process();
p.StartInfo = new ProcessStartInfo(#"'P:\\Receiving inspection\\Inspection Reports\\'" + timestamp + ".pdf");
p.Start();
The better way is that use LaunchFileAsync method to open file with browser. You could create FileLauncher DependencyService to invoke uwp LaunchFileAsync method from xamarin share project.
Interface
public interface IFileLauncher
{
Task<bool> LaunchFileAsync(string uri);
}
Implementation
[assembly: Dependency(typeof(UWPFileLauncher))]
namespace App14.UWP
{
public class UWPFileLauncher : IFileLauncher
{
public async Task<bool> LaunchFileAsync(string uri)
{
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri);
bool success = false;
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not
}
return success;
}
}
}
Usage
private async void Button_Clicked(object sender, EventArgs e)
{
await DependencyService.Get<IFileLauncher>().LaunchFileAsync("D:\\Key.pdf");
}
Please note if you want to access D or C disk in uwp, you need add broadFileSystemAccess capability. for more please refer this .
Update
If the UWP files are network based, not local zone based, you could use Xamarin.Essentials to open file with browser. And you must specify the privateNetworkClientServer capability in the manifest. For more please refer this link.

uwp close browser programmatically

I'm creating a simple news feed, it i want it can open the browser to show the details of the news, but i don't know how to close the browser , here is the code of how I open the browser,anyone can teach me how to off the browser using uwp? '
public async void test()
{
RootObject mynews = await NewsProxy.GetNews();
string website = mynews.articles[i].url;
var uriWeb = new Uri(websites);
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
if (success)
{
//Uri launched
}
else
{
// uri launch failed
}
}
var success = await Windows.System.Launcher.LaunchUriAsync(uriWeb);
Your code is actually telling the OS to Launch the given url and the OS in turn launches the default browser with the given URL. So you are not actually launching the browser.
In order to have full control over the browser behavior you can implement your own WebView and then use the url to navigate your WebView.
webView1.Navigate("http://www.contoso.com");
(MSDN Documentation for WebView)

How to dowload/upload file onto a users onedrive

I am in a Highschool club where we create windows store apps. I am in charge of the code that allows the user to either download files from their online onedrive storage, or upload files. So far I have successfully logged the user in and gained access to onedrive and display the users name with the following code:
private async void LoadProfile()
{
bool connected = false;
string text = "No Error:";
try
{
var authClient = new LiveAuthClient();
LiveLoginResult result = await authClient.LoginAsync(new List<string>() {"wl.signin", "wl.skydrive"});
if (result.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
var connectClient = new LiveConnectClient(result.Session);
var meResult = await connectClient.GetAsync("me");
dynamic meData = meResult.Result;
Textblock_profilename.Text = meData.name;
}
}
catch (LiveAuthException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
catch (LiveConnectException ex)
{
//Set text to corresponding error
text = ex.ToString();
}
if (text[0].ToString() != "N")
{
var dialog = new Windows.UI.Popups.MessageDialog(text);
await dialog.ShowAsync();
}
}
I gained the code from the following MSDN tutorial: http://msdn.microsoft.com/en-us/library/dn631823.aspx
However when I try to follow the next step, downloading and uploading files, I cannot get it to work. Right now I am just trying to press a button, and have the code download a test file:
private async void Button_downloadFile_Click(object sender, RoutedEventArgs e)
{
try
{
LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync("skydrive/documents/enter_path");
var result = await operation.StartAsync();
//DO SOMETHING WITH RESULT HERE
}
catch
{
// Handle any errors.
}
}
However this code throws the following errors:
This is straight from the MSDN tutorial, and can't figure out how to fix the error. My best guess is I'm missing a "using" statement, but can't figure out what I am missing. Thanks for any and all help!
Make sure you're updated to use the Live SDK 5.6 binary. Be sure to let us know if you have any other problems with OneDrive integration!

How to allow usage of FilePicker in WindowsStore App?

Using c#, Windows Store App, VS 2013
Try to open File Picker, using next simple code:
private async void OkBtnClick(IUICommand command)
{
if (this.EnsureUnsnapped())
{
FileOpenPicker fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".png");
fop.FileTypeFilter.Add(".jpg");
fop.FileTypeFilter.Add(".jpeg");
fop.ViewMode = PickerViewMode.Thumbnail;
fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile requestedFile = await fop.PickSingleFileAsync();
if (requestedFile != null)
{
//TODO:
}
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped)
|| ApplicationView.TryUnsnap());
if (!unsnapped)
{
Extensions.NotifyUser("Cannot unsnap app...", statusNotificationBlock);
}
return unsnapped;
}
Also add capability in appmanifest file for Pictures Library:
But during running got exception : System.UnauthorizedAccessException on line StorageFile requestedFile = await fop.PickSingleFileAsync();.
Question: Why I got this exception if all required access provided, Also i try to launch VS2013 with Administrator rights - result - same.
For creating this code use this article

Categories