Xamarin Plugin Geolocator not working on Xamarin Forms android - c#

I have installed the following nuget:
Xamarin.Forms.Maps Version => 3.1.0.697729
Plugin.CurrentActivity => 2.1.0.4
Xam.Plugin.Geolocator => 4.5.0.6
Plugin.Permissions => 3.0.0.12
I have the following class:
public class MainApplication : Application
{
public MainApplication(IntPtr handle, JniHandleOwnershiptranser): base(handle, transer)
{
}
public override void OnCreate()
{
base.OnCreate();
CrossCurrentActivity.Current.Init(this);
}
}
I have the code in my MainActivity class:
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Forms.Init(this, bundle);
FormsMaps.Init(this, bundle);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
Android manifest
<application android:label="MyApp.Android" android:icon="#drawable/icon">
<meta-data android:name="com.google.android.maps.v2.API_KEY " android:value="AIza..." />
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/file_paths"></meta-data>
</provider>
</application>
Android manifest - permission
< uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
< uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
< uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"
/>
< uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
< uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
< uses-permission android:name="android.permission.ACCESS_WIFI_STATE"
/>
< uses-permission android:name="android.permission.INTERNET" />
I try use meta-data android:name="com.google.android.geo.API_KEY"
instead of meta-data android:name="com.google.android.maps.v2.API_KEY"
Also adding this line below < meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
I have one View where I have my map:
<ContentPage.Content>
<maps:Map x:Name="Map" />
</ContentPage.Content>
And the code behind:
private async Task LoadMap()
{
if (await Utils.Utils.CheckPermissions(Permission.Location))
{
var currentLocation = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
// MORE CODE
}
}
And I use this class https://github.com/jamesmontemagno/PermissionsPlugin/blob/master/samples/PermissionsSample/PermissionsSample/Utils.cs for ask the permission
I get the api key from here https://developers.google.com/maps/documentation/android-sdk/signup?hl=en (Maps SDK for Android)
The version of my Xamarin Forms is 3.1.0.697729
I have created another project empty and the location on android is still not working.
In iOS I have no problem. The location is working.
I read this, https://jamesmontemagno.github.io/GeolocatorPlugin/GettingStarted.html.
When I run the app and the next line of code try to execute the method, it no longer executes the following lines of the method.The application works, but do not skip any exceptions.
await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
This line does not return anything.
Any idea why it fails?

Related

Directory.GetFiles does not return files copied from a computer (Android MAUI)

I'm developing an app in VS MAUI which is supposed to handle files and subfolders in the Download folder (external card) on an Android. The phones File Manager app reports 3 files in the folder, but my app lists only 1.
var f1 = Directory.GetFiles("/storage/8186-1418/Download");
The listed file has been created by the app itself, using File.WriteAllText, so I know I have access to the folder. The 2 files that aren't listed have been copied from a computer over USB to this folder, so I'm suspecting I'm missing some permissions.
The following permissions have been specified in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_USB" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
What do I need to do to see all files?
This is related to the manage_external_storage permission in your file so you need to use the ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent action to direct users to a system settings page where they can enable the following option for your app: Allow access to manage all files.
Firstly, use following code to judge current version and pop a in method of .SnackbarOnCreateMainActivity
public class MainActivity : AppCompatActivity
{
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);
if (Android.OS.Build.VERSION.SdkInt >=
Android.OS.BuildVersionCodes.R)
{
if (!Environment.IsExternalStorageManager)
{
Snackbar.Make(FindViewById(Android.Resource.Id.Content),
"Permission needed!", Snackbar.LengthIndefinite)
.SetAction("Settings", new
ClickHandler(this)).Show();
}
}
}
Then you can achieve the ( execute ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION intent action to direct users to a system settings page) to grand the permission.MyClickHandlerManage_External_Storage
internal class ClickHandler:Java.Lang.Object ,View.IOnClickListener
{
private MainActivity mainActivity;
public ClickHandler()
{
}
public ClickHandler(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
}
public void OnClick(View v)
{
try
{
Uri uri = Uri.Parse("package:" +
Application.Context.ApplicationInfo.PackageName);
Intent intent = new
Intent(Android.Provider.Settings.
ActionManageAppAllFilesAccessPermission,
uri);
mainActivity.StartActivity(intent);
}
catch (Exception ex)
{
Intent intent = new Intent();
intent.SetAction
(Android.Provider.Settings.ActionManageAppAllFilesAccessPermission);
mainActivity.StartActivity(intent);
}
}
}

SocketException: "access denied" while opening port using UdpClient

I'm trying to start listening on one of UDP ports on Android device. I'm using Xamarin.Forms and I'm testing it on physical android phone.
public void StartListening(int port = 13000)
{
ListenerPort = port;
udpClient = new UdpClient(ListenerPort);
udpClient.BeginReceive(new AsyncCallback(handleIncomingMessages), null);
}
This function is being used on application start:
public partial class App : Application
{
[...]
protected override void OnStart()
{
network.StartListening(LISTENING_ON_PORT);
}
}
The are many similar questions on SO, but most of them were solved by adding INTERNET permission to android manifest. Here is mine:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.ddand">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="ddAnd.Android" android:theme="#style/MainTheme"></application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
</manifest>
What I see after deploying my app is:
System.Net.Sockets.SocketException: 'Access denied'
and no other details provided.
I've thought my port is being used by another process, but I've check many of them (outside of 1-1024 range) and using all of them gave the same results.
Are there any other reasons for this exception? Do you have any ideas how can I throubleshoot the problem (e.g. how to find available port)?
EDIT:
As suggested in comments, I tried to gain access at runtime (though it should not be necessary, INTERNET permission is granted by default by Xamarin in Debug mode).
This line returns information that permission is granted.
var havePermission = ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet);
Nevertheless I tried to manually get access at runtime
ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Internet }, 1);
Result is the same as before.
Can you try with the following code? (adapted from the documentation)
public void StartListening(int port = 13000)
{
ListenerPort = port;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ListenerPort);
udpClient = new UdpClient(ipEndPoint);
UdpState udpState = new UdpState();
udpState.e = ipEndPoint;
udpState.u = udpClient;
udpState.BeginReceive(new AsyncCallback(handleIncomingMessages), udpState);
}

Program type already present: com.android.installreferrer.api.InstallReferrerClient$1

Unity 2018.4.15. Build project for Android platform with error:
CommandInvokationFailure: Gradle build failed. J:\Program
Files\2018.4.15f1\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\OpenJDK\Windows\bin\java.exe
-classpath "J:\Program Files\2018.4.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-5.1.1.jar"
org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m"
"assembleRelease"
stderr[ D8: Program type already present:
com.android.installreferrer.api.InstallReferrerClient$1
FAILURE: Build failed with an exception.
What went wrong: Execution failed for task ':transformDexArchiveWithExternalLibsDexMergerForRelease'.
There is only one lib with name "installreferrer-1.0.aar" in Assets/Plugins/Android/ folder. I use Facebook plugin (7.18.0), GoogleMobileAds (4.2.1), Applovin SDK (9.11.1) with Facebook mediation (5.6.1.0).
If I deleted installreferrer-1.0.aar - project compile ok, but it crashes after running on device. If I rollback library & delete the Facebook plugin the project compiles ok, but crashes as well. I think that FB connect is causing my error, but I cannot resolve it.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
<supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
<application android:theme="#style/UnityThemeSelector" android:icon="#mipmap/app_icon" android:label="#string/app_name" android:networkSecurityConfig="#xml/network_security_config"
android:name="android.support.multidex.MultiDexApplication" tools:replace="android:icon">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<activity android:name="com.facebook.unity.FBUnityLoginActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
<activity android:name="com.facebook.unity.FBUnityDialogsActivity" android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen" />
<activity android:name="com.facebook.unity.FBUnityAppLinkActivity" android:exported="true" />
<activity android:name="com.facebook.unity.FBUnityDeepLinkingActivity" android:exported="true" />
<activity android:name="com.facebook.unity.FBUnityGameRequestActivity" />
<activity android:name="com.facebook.unity.FBUnityCreateGameGroupActivity" />
<activity android:name="com.facebook.unity.FBUnityJoinGameGroupActivity" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="fb2575328535843348" />
<meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled" android:value="true" />
<meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled" android:value="true" />
<provider android:name="com.facebook.FacebookContentProvider" android:authorities="com.facebook.app.FacebookContentProvider2575328535843348" android:exported="true" />
<receiver android:name="com.appsflyer.SingleInstallBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="com.android.vending.BILLING" />
</manifest>
mainTeplate.gradle
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
**BUILD_SCRIPT_DEPS**}
}
allprojects {
repositories {
google()
jcenter()
flatDir {
dirs 'libs'
}
}
}
// Android Resolver Repos Start
([rootProject] + (rootProject.subprojects as List)).each {
ext {
it.setProperty("android.useAndroidX", true)
it.setProperty("android.enableJetifier", true)
}
}
([rootProject] + (rootProject.subprojects as List)).each { project ->
project.repositories {
def unityProjectPath = $/file:///**DIR_UNITYPROJECT**/$.replace("\\", "/")
maven {
url "https://maven.google.com"
}
maven {
url "https://maven.google.com/" // Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:7
}
maven {
url "https://adcolony.bintray.com/AdColony" // Assets/MaxSdk/Mediation/AdColony/Editor/Dependencies.xml:8
}
maven {
url "https://applovin.bintray.com/Android-Adapter-SDKs" // Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml:8, Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml:8
}
maven {
url "https://s3.amazonaws.com/smaato-sdk-releases/" // Assets/MaxSdk/Mediation/Smaato/Editor/Dependencies.xml:8
}
mavenLocal()
jcenter()
mavenCentral()
}
}
// Android Resolver Repos End
apply plugin: 'com.android.application'
**APPLY_PLUGINS**
dependencies {
implementation 'com.android.support:multidex:1.0.1'
implementation fileTree(dir: 'libs', include: ['*.jar'])
// Android Resolver Dependencies Start
implementation 'com.android.support:appcompat-v7:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
implementation 'com.android.support:appcompat-v7:28.+' // Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml:10
implementation 'com.android.support:cardview-v7:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
implementation 'com.android.support:customtabs:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
implementation 'com.android.support:recyclerview-v7:28.+' // Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml:9
implementation 'com.android.support:support-v4:25.3.1' // Facebook.Unity.Editor.AndroidSupportLibraryResolver.addSupportLibraryDependency
implementation 'com.applovin.mediation:adcolony-adapter:4.1.2.1' // Assets/MaxSdk/Mediation/AdColony/Editor/Dependencies.xml:8
implementation 'com.applovin.mediation:facebook-adapter:[5.6.1.0]' // Assets/MaxSdk/Mediation/Facebook/Editor/Dependencies.xml:8
implementation 'com.applovin.mediation:fyber-adapter:7.5.0.0' // Assets/MaxSdk/Mediation/Fyber/Editor/Dependencies.xml:8
implementation 'com.applovin.mediation:google-adapter:[17.2.1.7]' // Assets/MaxSdk/Mediation/Google/Editor/Dependencies.xml:5
implementation 'com.applovin.mediation:ironsource-adapter:6.13.0.1.0' // Assets/MaxSdk/Mediation/IronSource/Editor/Dependencies.xml:8
implementation 'com.applovin.mediation:mintegral-adapter:10.1.51.2' // Assets/MaxSdk/Mediation/Mintegral/Editor/Dependencies.xml:4
implementation 'com.applovin.mediation:smaato-adapter:21.3.1.0' // Assets/MaxSdk/Mediation/Smaato/Editor/Dependencies.xml:8
implementation 'com.applovin.mediation:tapjoy-adapter:12.4.0.0' // Assets/MaxSdk/Mediation/Tapjoy/Editor/Dependencies.xml:4
implementation 'com.applovin.mediation:unityads-adapter:3.4.0.1' // Assets/MaxSdk/Mediation/UnityAds/Editor/Dependencies.xml:4
implementation 'com.applovin:applovin-sdk:9.11.1' // Assets/MaxSdk/AppLovin/Editor/Dependencies.xml:4
implementation 'com.facebook.android:facebook-applinks:[5,6)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:6
implementation 'com.facebook.android:facebook-core:[5,6)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:5
implementation 'com.facebook.android:facebook-login:[5,6)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:7
implementation 'com.facebook.android:facebook-share:[5,6)' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:8
implementation 'com.google.android.gms:play-services-ads:18.2.0' // Assets/GoogleMobileAds/Editor/GoogleMobileAdsDependencies.xml:7
implementation 'com.google.android.gms:play-services-ads-identifier:[16.0.0]' // Assets/MaxSdk/AppLovin/Editor/Dependencies.xml:5
implementation 'com.parse.bolts:bolts-android:1.4.0' // Assets/FacebookSDK/Plugins/Editor/Dependencies.xml:4
// Android Resolver Dependencies End
**DEPS**}
// Android Resolver Exclusions Start
android {
packagingOptions {
exclude ('/lib/armeabi/*' + '*')
exclude ('/lib/mips/*' + '*')
exclude ('/lib/mips64/*' + '*')
exclude ('/lib/x86/*' + '*')
exclude ('/lib/x86_64/*' + '*')
}
}
// Android Resolver Exclusions End
android {
compileSdkVersion **APIVERSION**
buildToolsVersion '**BUILDTOOLS**'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
multiDexEnabled true
minSdkVersion **MINSDKVERSION**
targetSdkVersion **TARGETSDKVERSION**
applicationId '**APPLICATIONID**'
ndk {
abiFilters **ABIFILTERS**
}
versionCode **VERSIONCODE**
versionName '**VERSIONNAME**'
}
dexOptions {
javaMaxHeapSize "16g"
}
lintOptions {
abortOnError false
}
aaptOptions {
noCompress = ['.unity3d', '.ress', '.resource', '.obb'**STREAMING_ASSETS**]
}**SIGN**
buildTypes {
debug {
minifyEnabled **MINIFY_DEBUG**
useProguard **PROGUARD_DEBUG**
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD**
jniDebuggable true
}
release {
minifyEnabled **MINIFY_RELEASE**
useProguard **PROGUARD_RELEASE**
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'**USER_PROGUARD****SIGNCONFIG**
}
}**PACKAGING_OPTIONS****SPLITS**
**BUILT_APK_LOCATION**
bundle {
language {
enableSplit = false
}
density {
enableSplit = false
}
abi {
enableSplit = true
}
}
}**SPLITS_VERSION_CODE****REPOSITORIES****SOURCE_BUILD_SETUP**
Change your Facebook android dependencies from "[5,6)" to "5.13.0". This was included into your mainTemplate.gradle from file
Assets/FacebookSDK/Plugins/Editor/Dependencies.xml
Resolve problem:
Remove FB plugin, FB Mediation from project and manifest
Exit from Unity
Remove Library folder
Launch Unity and compile without FB!
Install FB
Change your Facebook android dependencies from "[5,6)" to "5.13.0"
Assets -> GooglePlayResolver -> Android Resolver -> Settings -> Force Resolve
Profit!

Showing PDF-File with MVVM Cross on Android and IOS

I want to open a PDF on the Phone via the File-Path but i cant figure out how i could do this properly without using 3rd party packages.
You have any suggestion for this?
I already tried to use this on Android:
public void OpenFile(string filePath)
{
var fileToOpen = new Java.IO.File(filePath);
var uri = FileProvider.GetUriForFile(Application.Context, Application.Context.PackageName + ".fileprovider", fileToOpen);
var intent = new Intent();
var mime = IOUtil.GetMimeType(uri.ToString());
intent.SetAction(Intent.ActionView);
intent.SetDataAndType(uri, mime);
intent.SetFlags(ActivityFlags.NewTask);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
Application.Context.StartActivity(intent);
}
But i get the following Error:
Unhandled Exception:
Java.Lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.XmlResourceParser
android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager,
java.lang.String)' on a null object reference
first you should addd this code to your manifest file :
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.easyphotopicker.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths"
tools:replace="android:resource"/>
</provider>
and create filepaths :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<root-path name="root" path="" /> //root directory of the device new File("/");
<files-path name="files" path="" /> //context.getFilesDir()
<cache-path name="cache" path="" /> //context.getCacheDir()
<external-path name="external" path="" /> //Environment.getExternalStorageDirectory()
<external-files-path name="name" path="path" /> //context.getExternalFilesDirs()
<external-cache-path name="name" path="path" /> //getExternalCacheDirs()
</paths>
Your error is telling us that there is no file at the location matching that's passed into the function. There's a few ways of doing this, one of them is as shown. After accepting permissions to access folders and files, this should be one of the simplest ways. You seem to be close:
public void OpenPdfFile(string filename)
{
var f = new Java.IO.File(filename);
if (f.Exists())
{
System.Diagnostics.Debug.WriteLine("File exists!");
try
{
var openFileIntent = new Intent(Intent.ActionView);
openFileIntent.SetDataAndType(Android.Net.Uri.FromFile(f), "application/pdf");
openFileIntent.SetFlags(ActivityFlags.NoHistory);
StartActivity(Intent.CreateChooser(openFileIntent, "Open pdf file"));
}
catch (ActivityNotFoundException)
{
//handle when no available apps
}
}
}
I haven't tested your work, but the first thing would be to see if you added this to the Manifest file
android:authorities="com.{package}.{name}.fileprovider"
since your code says Application.Context.PackageName + ".fileprovider"

PushWoosh Xamarin Forms Android exception on registration

I've been trying to implement PushWoosh's push notifications system in my existing Xamarin Forms (PCL) project and so far, it works perfectly with iOS.
When it comes to adding it to Android, I'm facing a crash at launch despite the fact that I have followed letter by letter the guide for Xamarin Forms for Android.
The app simply crashes on launch due to an Unhandled exception.
I've had fun commenting line by line to find what caused this error and it seems it is manager.RegisterForPushNotifications(); that executes the code responsible for that crash.
After further investigation in the debug log, it seems to be a problem with the ShortcutBadger being unable to resolve an intent.
I've ran the app on physical devices, fully up-to-date:
Samsung Galaxy S4
(Asus) Google Nexus 7
I am using Visual Studio 2017 Community.
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package.awesome"
android:versionCode="1"
android:versionName="4.0"
android:installLocation="auto">
<uses-sdk android:minSdkVersion="15" />
<!-- Badges -->
<!-- Common -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS"/>
<!-- Apex -->
<uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT"/>
<!-- Samsung -->
<uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />
<!-- Sony -->
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
<!-- HTC -->
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" />
<!-- Solid -->
<uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE"/>
<!-- Huawei -->
<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE"/>
<uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS"/>
<!-- ZUK -->
<uses-permission android:name="android.permission.READ_APP_BADGE"/>
<!-- OPPO -->
<uses-permission android:name="com.oppo.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS"/>
<!-- EvMe -->
<uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_READ"/>
<uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_WRITE"/>
<!-- /Badges -->
<!-- Location tracking -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- Boot permission for rescheduling local notifications and location tracking -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- GCM Part -->
<permission android:name="com.package.awesome.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.package.awesome.permission.C2D_MESSAGE"/>
<application android:label="#string/app_name"
android:icon="#mipmap/ic_launcher">
<meta-data android:name="com.google.android.gms.version"
android:value="8487000" />
<meta-data android:name="PW_APPID"
android:value="A1B2C-3D4E5" />
<meta-data android:name="PW_PROJECT_ID"
android:value="awesome-app" />
<!-- GCM Part -->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.package.awesome" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity.cs:
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Pushwoosh;
using Android.Content.PM;
using Android.Util;
namespace Project.Droid
{
class LocalMessageBroadcastReceiver : BasePushMessageReceiver
{
public MainActivity activity { get; set; }
protected override void OnMessageReceive(Intent intent)
{
activity.doOnMessageReceive(intent.GetStringExtra(BasePushMessageReceiver.JsonDataKey));
}
}
[Activity(Label = "#string/app_name", Theme = "#style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new string[] { "com.package.awesome.MESSAGE" }, Categories = new string[] { "android.intent.category.DEFAULT" })]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
LocalMessageBroadcastReceiver mMessageReceiver;
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
mMessageReceiver = new LocalMessageBroadcastReceiver();
mMessageReceiver.activity = this;
registerReceivers();
PushManager manager = PushManager.GetInstance(this);
manager.OnStartup(this);
// Register for push!
manager.RegisterForPushNotifications();
// Reset application icon badge number
manager.BadgeNumber = 0;
checkMessage(Intent);
}
protected override void OnNewIntent(Intent intent)
{
checkMessage(intent);
}
public void checkMessage(Intent intent)
{
if (null != intent)
{
if (intent.HasExtra(PushManager.PushReceiveEvent))
{
doOnMessageReceive(intent.Extras.GetString(PushManager.PushReceiveEvent));
}
resetIntentValues();
}
}
public void doOnMessageReceive(String message)
{
// hadle push open here
Log.Debug("PushwooshSample", "Push opened: " + message);
}
private void resetIntentValues()
{
Intent mainAppIntent = Intent;
if (mainAppIntent.HasExtra(PushManager.PushReceiveEvent))
{
mainAppIntent.RemoveExtra(PushManager.PushReceiveEvent);
}
else if (mainAppIntent.HasExtra(PushManager.RegisterEvent))
{
mainAppIntent.RemoveExtra(PushManager.RegisterEvent);
}
else if (mainAppIntent.HasExtra(PushManager.UnregisterEvent))
{
mainAppIntent.RemoveExtra(PushManager.UnregisterEvent);
}
else if (mainAppIntent.HasExtra(PushManager.RegisterErrorEvent))
{
mainAppIntent.RemoveExtra(PushManager.RegisterErrorEvent);
}
else if (mainAppIntent.HasExtra(PushManager.UnregisterErrorEvent))
{
mainAppIntent.RemoveExtra(PushManager.UnregisterErrorEvent);
}
Intent = mainAppIntent;
}
protected override void OnResume()
{
base.OnResume();
registerReceivers();
}
protected override void OnPause()
{
base.OnPause();
unregisterReceivers();
}
public void registerReceivers()
{
IntentFilter intentFilter = new IntentFilter(PackageName + ".action.PUSH_MESSAGE_RECEIVE");
RegisterReceiver(mMessageReceiver, intentFilter);
}
public void unregisterReceivers()
{
UnregisterReceiver(mMessageReceiver);
}
}
}
Crash log:
07-31 10:12:09.182 D/Pushwoosh(29231): [RequestManager] Try To send: getInApps
07-31 10:12:09.185 V/Pushwoosh(29231): [GCMRegistrationService] Intent action = com.pushwoosh.gcm.intent.REGISTER
07-31 10:12:09.190 E/Pushwoosh(29231): [ShortcutBadger] Unable to execute badge
07-31 10:12:09.190 E/Pushwoosh(29231): com.pushwoosh.thirdparty.a.b: Unable to execute badge
07-31 10:12:09.190 E/Pushwoosh(29231): at com.pushwoosh.thirdparty.a.c.b(Unknown Source)
07-31 10:12:09.190 E/Pushwoosh(29231): at com.pushwoosh.thirdparty.a.c.a(Unknown Source)
07-31 10:12:09.190 E/Pushwoosh(29231): at com.pushwoosh.internal.PushManagerImpl$2.run(Unknown Source)
07-31 10:12:09.190 E/Pushwoosh(29231): at android.os.Handler.handleCallback(Handler.java:739)
07-31 10:12:09.190 E/Pushwoosh(29231): at android.os.Handler.dispatchMessage(Handler.java:95)
07-31 10:12:09.190 E/Pushwoosh(29231): at android.os.Looper.loop(Looper.java:148)
07-31 10:12:09.190 E/Pushwoosh(29231): at android.app.ActivityThread.main(ActivityThread.java:5417)
07-31 10:12:09.190 E/Pushwoosh(29231): at java.lang.reflect.Method.invoke(Native Method)
07-31 10:12:09.190 E/Pushwoosh(29231): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-31 10:12:09.190 E/Pushwoosh(29231): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-31 10:12:09.190 E/Pushwoosh(29231): Caused by: com.pushwoosh.thirdparty.a.b: unable to resolve intent: Intent { act=android.intent.action.BADGE_COUNT_UPDATE (has extras) }
07-31 10:12:09.190 E/Pushwoosh(29231): at com.pushwoosh.thirdparty.a.a.d.a(Unknown Source)
07-31 10:12:09.190 E/Pushwoosh(29231): ... 10 more
Please note that I've renamed the project name, package, PushWoosh app ID and FCM app ID for confidentiality purposes.
I solved my problem by updating the Xamarin.GooglePlayServices.Gcm dependency to the latest version 42.1021.1 while mine was 29.x.x.
As Mike said in the comments, I had to make sure that everything is up-to-date since PushWoosh does not require a high version of critical dependencies such as Google Play Services while they could potentially crash the app if obsolete. They should be more restrictive on that point !

Categories

Resources