Use android package manager in Xamarin.Forms - c#

Trying to check if a particular application is installed in the android phone or not.
In android studio, I used Package manager to get the installation status of the application. But I need to use Xamarin.Forms for development.

yes,you could use DependencyService to achive this:
first,define a Interface :
public interface IsInstallApplication
{
bool IsInstall(string packageName);
}
then in Droid.project create a class which implement the interface :
[assembly: Dependency(typeof(AndroidIsInstallApplication))]// do not miss the line
namespace App18.Droid
{
class AndroidIsInstallApplication : IsInstallApplication
{
public bool IsInstall(string packageName)
{
... //here you could use Package manager to get the installation status of the application like in native android
return true;
}
}
}
finally you could call it in you page like :
DependencyService.Get<IsInstallApplication>().IsInstall(packageName);

Related

Can I check available storage in the Device on Xamarin Forms?

I am trying to make an app that requires that I frequently send recorded data to a firebase. When network goes out or battery is about to die, I am saving all of the data that wasn't stored into firebase locally. However, to do this I require about 20 MB of data (my data is pretty big). That being said, I want to find a way to check the available storage (and the battery if possible) to give the user a warning. Is this possible using Xamarin Forms? Also, is there a way that I can make this solution universal (i.e. I don't need a separate piece of code for iOS vs. Android)? (I am new to Xamarin and C#)
Use the following code to check the free size of a device:
For iOS:
NSFileManager.DefaultManager.GetFileSystemAttributes (Environment.GetFolderPath (Environment.SpecialFolder.Personal)).FreeSize;
For Android:
var freeExternalStorage = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;
There is no universal option, but you can wrap it an interface like so and implement it on each project:
public interface IStorage
{
double GetRemainingStorage();
}
It would be great if a feature like this could be added in Xamarin.Essentials - there was a request on GitHub but it never really made it.
If there are any issues with the code - please tell me.
Hope this helped,
Instructions
Create an interface in your shared project titled IStorage.
In your Android project create a class titled AndroidStorageManager (you can name it however you would like). Make it so it extends IStorage. The method GetRemainingStorage() should be of return type double.
public class AndroidStorageManager : IStorage
{
public double GetRemainingStorage()
{
var freeExternalStorage = Android.OS.Environment.ExternalStorageDirectory.UsableSpace;
return freeExternalStorage;
}
}
For iOS
Create a class in your iOS project titled iOSStorageManager which extends IStorage:
public class iOSStorageManager : IStorage
{
public double GetRemainingStorage()
{
return NSFileManager.DefaultManager.GetFileSystemAttributes(Environment.GetFolderPath(Environment.SpecialFolder.Personal)).FreeSize;
}
}
In your Android implementation - add the following code above the namespace:
[assembly: Xamarin.Forms.Dependency(
typeof(AndroidStorageManager))]
For iOS:
[assembly: Xamarin.Forms.Dependency(
typeof(iOSStorageManager))]
To get the storage:
IStorage storageManager = DependencyService.Get<IStorage>();
double remaining = storageManager.GetRemainingStorage();
Hope this clarified things.

How to launch Camera app from Unity in android?

I want to launch camera app in android from Unity3d app. I can do it by building an Android app through Android Studio. I want to create a jar plugin of that android studio project and call the code through Unity game.
Unity C# code
public class UnityAndroidPluginExample : MonoBehaviour
{
AndroidJavaObject javaClass;
public void CallPlugin()
{
javaClass = new AndroidJavaObject("com.mycompany.pluginexample.CameraPluginClass");
javaClass.Call("LaunchCameraApp");
}
}
Android Studio Code
package com.mycompany.pluginexample;
import android.content.Intent;
import android.provider.MediaStore;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class CameraPluginClass extends AppCompatActivity
{
public void LaunchCameraApp()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
}
I am getting error
AndroidJavaException: java.lang.ClassNotFoundException:com.mycompany.pluginexample.CameraPluginClass
AndroidJavaException: java.lang.NoClassDefFoundError:Failed resolution of: Landroidx/appcompat/app/AppCompatActivity
Here is my Android Studio code that worked for Android
btnCaptureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
Please help, I am stuck here. In short, I cannot call a method of the Java class that extends AppCompatACtivity. If I remove extends AppCompatActivity and call a method in that Java Class from Unity, it works, only if I use extends AppCompatActivty, I cannot call any method inside that class from Unity. I am using Unity version 2019.1.7f1.
Any help would be much appreciated.
Changing "AppCompatActivity" to just "Activity" worked for me, though I'm not sure why. If you ever figure out why, let me know!

Share the app feature implement using dependency service in xamarin forms android project

I am implementing Share the App feature in Xamarin forms project. Yes, there are libraries which are available, But library conflicts with a version of Xamarin forms package and I have already completed all the stuff and don't want any issue, and I want to implement using dependency service by doing platform specific coding in Android and iOS without any package.
Here, I am using intent for share the app from Android project by making custom renderer. But I am getting error.
public class ShareTheAppRenderer : IShareTheApp
{
public void ShareApp()
{
var mainActivity = new MainActivity();
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.PutExtra(Intent.ExtraText, "Check out our app at: https://play.google.com/store/apps/details?id=");
sendIntent.SetType("text/plain");
mainActivity.StartActivity(sendIntent);
}
}
Please give some suggestions to resolve this issue.
Thank you for your reply. But I got the solution for this. Here I don't want to use any other libraries to achieve this.
My Working solution is as below:
public class ShareTheAppRenderer : IShareTheApp
{
public void ShareApp()
{
var appPackageName = Forms.Context.PackageName;
var myIntent = new Intent(Android.Content.Intent.ActionSend);
myIntent.SetType("text/plain");
myIntent.PutExtra(Intent.ExtraText, "Check out our app at: https://play.google.com/store/apps/details?id=" + appPackageName);
Forms.Context.StartActivity(Intent.CreateChooser(myIntent, "Choose an App"));
}
}
This solution works for me.

How do I use the AppGlideModule in Xamarin.Android?

Using the Glide library on Xamarin.Android, I was hoping someone could shed some light on how to use the AppGlideModule. According to the documentation, I need to register my custom ModelLoader using the AppGlideModule.
Here is a link to the example in the Glide documentation:
http://bumptech.github.io/glide/tut/custom-modelloader.html#writing-the-modelloader
Here is my custom AppGlideModule class:
public class MyCustomGlideModule : AppGlideModule
{
public override void ApplyOptions(Context context, GlideBuilder builder)
{
base.ApplyOptions(context, builder);
}
public override void RegisterComponents(Context context, Glide glide, Registry registry)
{
registry.Prepend(
Java.Lang.Class.FromType(typeof(Java.IO.OutputStream)),
Java.Lang.Class.FromType(typeof(Drawable)),
new MyCustomImageStreamModelLoaderFactory()
);
}
}
I don't know if it's necessary, but if you'd like to see the classes I made for the ModelLoader, please let me know in the comments.
Old question but here is the trick. You will need to create an Android/Java library that contains an AppGlideModule wrapper. This library contains nothing else and is simply used to generate the GlideApp class. It needs to contain a static instance of your final AppGlideModule. Basically, it will look like this :
#GlideModule
public class XamarinGlideModule extends AppGlideModule {
public static AppGlideModule InjectedModule;
#Override
public void registerComponents(Context context, Glide glide, Registry registry) {
if(InjectedModule != null) {
InjectedModule.registerComponents(context, glide, registry);
}
}
}
You will then need to wrap this library in an Android binding library. Nothing is worthy of mention in this step, simply drop your built AAR in the binding project, add the matching version of the Glide Nuget and build.
You can then add a reference to that binding library in your app project. In your Android Application class, you will need to setup the InjectedModule static property to inject your Xamarin implementation. You must do this before any call to Glide, something similar to this :
public override void OnCreate()
{
base.OnCreate();
XamarinGlideModule.InjectedModule = new MyLoaderModule();
var temp = GlideApp.Get(this); // Init Glide, it will register your Xamarin module
}
Now there's one more option to use custom glide module from C# code. Just install package of this project:
https://github.com/KDD-Digital-Healthcare-GmbH/Kdd.Glide.AppModuleInjector
NOTE: if you need custom AppModule for glide just to accept self-signed certificates, you can install this package as well, it already has implementation of such module:
https://github.com/KDD-Digital-Healthcare-GmbH/Kdd.Glide.UnsafeUrlLoadingAppGlideModule

How to integrate an external library (i.e.: FacebookSDK) properly while creating a Unity Android plugin?

I'm trying to add a missing functionality (App Invites) to the Unity Facebook SDK
I've followed this post in order to create a basic Unity Android plugin by using Android Studio: http://www.thegamecontriver.com/2015/04/android-plugin-unity-android-studio.html. Everything worked as expected and I was able to run the plugin in my project.
Then, I've added the FacebookSDK and a static method accessible by Unity:
public static void inviteContacts(Activity root, String linkURL, String previewImageURL)
{
if (AppInviteDialog.canShow()) {
Log.i(TAG, "AppInviteDialog.canShow()!");
AppInviteContent content = new AppInviteContent.Builder()
.setApplinkUrl(linkURL)
.setPreviewImageUrl(previewImageURL)
.build();
AppInviteDialog.show(root, content);
}
}
Unfortunately, when I try to run my plugin, I'm getting this error:
I/Unity﹕ AndroidJavaException: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/facebook/share/widget/AppInviteDialog;
I took a look at the classes included in my compiled jar plugin, and in fact, there's no facebook classes in it. So, I suspect that there's something wrong with my project setup or my gradle file.
This is my gradle file:
apply plugin: 'com.android.library'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
sourceSets {
main {
//Path to your source code
java {
srcDir 'src/main/java'
}
}
}
defaultConfig {
minSdkVersion 15
targetSdkVersion 22
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
compile project(':facebook')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.1'
compile files('libs/classes.jar')
}
//task to delete the old jar
task deleteOldJar(type: Delete) {
delete 'release/AppInvite.jar'
}
//task to export contents as jar
task exportJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('release/')
include('classes.jar')
///Rename the jar
rename('classes.jar', 'AppInvite.jar')
}
exportJar.dependsOn(deleteOldJar, build)
I've also followed these instructions in order to import the module and create the dependency:
Add library project (module) in Android Studio
File -> Import Module
Add library project (module) in build path
File -> Project Structure
Dependency:
app -> Dependencies tab -> green + button -> Module dependency
What am I missing here? What do I need to change in order to compile and export the FacebookSDK classes integrated on my plugin?
Thanks in advance.
Facebook unity SDK supports App Invites.
You can use Facebook AppRequest API to invite to use app. https://developers.facebook.com/docs/unity/reference/current/FB.AppRequest

Categories

Resources