Showing posts with label Xamarin.Android. Show all posts

Introduction:  In this article, we will see how to use Zxing Intent Integrator in Xamarin Android Applications. We have seen a lot o...

How to use Zxing Intent Integrator in Xamarin.Android How to use Zxing Intent Integrator in Xamarin.Android

A blog about android developement

Xamarin.Android

tite-banner

Introduction: 

In this article, we will see how to use Zxing Intent Integrator in Xamarin Android Applications. We have seen a lot of articles about how to integrate Zxing Plugin in Android & iOS Applications. But integration of Zxing Intent Integrator is available for Java Android Apps only. So, I have created a Xamarin Library for Xamarin.Android to Zxing Intent Integrator. 

Zxing Intent Integrator: 

This plugin is a port of official Zxing Intent Integrator and it is not just a binding project. I have converted the library code from java to C#. We will see, how to use the same in Coding Part. 

Coding Part: 

Steps: 

I have split this article into 3 steps as in the following. 
Step 1: Creating new Xamarin.Android Projects. 
Step 2: Setting up the plugin for Xamarin.Android Application. 
Step 3: Implementing Zxing Intent Integrator in Xamarin.Android Application.

Step 1: Creating new Xamarin.Android Projects

Create New Project by Selecting New -> Project -> Select Android App and Click OK.

new project

Step 2: Setting up the plugin for Xamarin.Android Application

In this step, we will include the Zxing plugin for Xamarin.Android Project. 
  1. You can download the plugin by clicking here.
  2. Right click on the reference and click add reference.
  3. Then click browse and go to the folder to choose the plugin you downloaded.
add reference 1

add reference 2

Step 3: Implementing Zxing Intent Integrator in Xamarin.Android Application 

  1. I have created a button and added click event.
  2. Then added OnActivityResult Override method as shown below. 
    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
    
     IntentResult result = IntentIntegrator.ParseActivityResult(requestCode, (int)resultCode, data);
     if (result != null)
     {
      if (result.Contents == null)
      {
       Log.Debug("MainActivity", "Cancelled scan");
       Toast.MakeText(this, "Cancelled", ToastLength.Long).Show();
      }
      else
      {
       Log.Debug("MainActivity", "Scanned");
       Toast.MakeText(this, "Scanned: " + result.Contents, ToastLength.Long).Show();
      }
     }
     else
     {
      base.OnActivityResult(requestCode, resultCode, data);
     }
    }
  3. Here we can handle the results returned from Zxing Scanner App.
  4. Then add the following lines in click event, which is help us to call the Zxing app to scan the barcodes.
    button.Click += (s, e) =>
    {
     IntentIntegrator intentIntegrator = new IntentIntegrator(this);
     intentIntegrator.InitiateScan();
    };
  5. The working principle is similar to the official Zxing Java Library.

Full Code

You can find full code here.
namespace ZxingSample
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            LinearLayout ll = new LinearLayout(this);
            Button button = new Button(this);
            button.Text = "Click to Scan using Zxing";
            button.Click += (s, e) =>
            {
                IntentIntegrator intentIntegrator = new IntentIntegrator(this);
                intentIntegrator.InitiateScan();
            };
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent,
                Android.Views.ViewGroup.LayoutParams.WrapContent);
            ll.AddView(button, lp);
            SetContentView(ll);
        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {

            IntentResult result = IntentIntegrator.ParseActivityResult(requestCode, (int)resultCode, data);
            if (result != null)
            {
                if (result.Contents == null)
                {
                    Log.Debug("MainActivity", "Cancelled scan");
                    Toast.MakeText(this, "Cancelled", ToastLength.Long).Show();
                }
                else
                {
                    Log.Debug("MainActivity", "Scanned");
                    Toast.MakeText(this, "Scanned: " + result.Contents, ToastLength.Long).Show();
                }
            }
            else
            {
                base.OnActivityResult(requestCode, resultCode, data);
            }
        }
    }
}

Demo

zxing app 1

zxing app 2

zxing app 3

zxing app 4

Download Code

You can download the full source code from GitHub. If you like the post, do like and share the article and star the repo on GitHub.

Introduction: In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, ...

How to Send Mail directly from Android Application in Xamarin.Android How to Send Mail directly from Android Application in Xamarin.Android

A blog about android developement

Xamarin.Android



Introduction:

In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, we can MailKit to send mail directly.

MailKit:

MailKit is a cross-platform mail client library built on top of MimeKit. MailKit is a personal open source project that I have put thousands of hours into perfecting with the goal of making it the very best email framework for .NET.

Coding Part:

Steps:

I have split this article into 3 steps as in the following.
Step 1: Creating new Xamarin.Android Projects.
Step 2: Setting up the plugin for Xamarin.Android Application.
Step 3: Implementing Mail functionalities in Xamarin.Android Application.

Step 1: Creating new Xamarin.Android Projects

Create New Project by Selecting New  Project  Select Android App and Click OK.

fig1

Step 2: Setting up the plugin for Xamarin.Android Application

In this step, we will include the Mailkit plugin for Xamarin.Android Project. Open Nuget Package Manager against the project and do search for Mailkit and click install to add the library or Paste the following in Package Manager Console to install the Nuget plugin.

Install-Package MailKit
fig2

Step 3: Implementing Mail Functionalities in Xamarin.Android Application

In this part, we will see how to implement Mail functions to send mail.

  • Open your MainActivity.cs and Import the Following Packages.
    using MimeKit;
    using MailKit.Net.Smtp;
    
  • Then add/create an Async task class named as “MailAsyncTask” and add implement the override functions.
    • OnPreExecute
    • OnPostExecute
    • DoInBackground
  • Then add/paste the following code in DoInBackground method.
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
    message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
    message.Subject = mainActivity.edtSubject.Text;
    
    message.Body = new TextPart("plain")
    {
     Text = mainActivity.edtMessage.Text
    };
    
    using (var client = new SmtpClient())
    {
     // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
     client.ServerCertificateValidationCallback = (s, c, h, e) => true;
    
     client.Connect(host, port, false);
    
     // Note: only needed if the SMTP server requires authentication
     client.Authenticate(username, password);
     client.Send(message);
     client.Disconnect(true);
    }
  • Here, we should provide host address, port and username & password if the SMTP server needs authentication.
  • The Mail Connections needed to be run with separate thread. So, I had done the call with “AsyncTask”. You can find the full code below.

Full code of the MailAsyncClass:

The following code shows how to implement Direct Mail functions in Xamarin.Android with AsyncTask.

class MailAsyncTask : AsyncTask
{
 string username = "mail-id or username", password = "password", host = "smtp.gmail.com";
 int port = 25;
 MainActivity mainActivity;
 ProgressDialog progressDialog;

 public MailAsyncTask(MainActivity activity)
 {
  mainActivity = activity;
  progressDialog = new ProgressDialog(mainActivity);
  progressDialog.SetMessage("Sending...");
  progressDialog.SetCancelable(false);
 }

 protected override void OnPreExecute()
 {
  base.OnPreExecute();
  progressDialog.Show();
 }

 protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
 {
  try
  {
   var message = new MimeMessage();
   message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
   message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
   message.Subject = mainActivity.edtSubject.Text;

   message.Body = new TextPart("plain")
   {
    Text = mainActivity.edtMessage.Text
   };

   using (var client = new SmtpClient())
   {
    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

    client.Connect(host, port, false);

    // Note: only needed if the SMTP server requires authentication
    client.Authenticate(username, password);
    client.Send(message);
    client.Disconnect(true);
   }
   return "Successfully Sent";
  }
  catch (System.Exception ex)
  {
   return ex.Message;
  }
 }

 protected override void OnPostExecute(Java.Lang.Object result)
 {
  base.OnPostExecute(result);
  progressDialog.Dismiss();
  mainActivity.edtFrom.Text = null;
  mainActivity.edtTo.Text = null;
  mainActivity.edtSubject.Text = null;
  mainActivity.edtMessage.Text = null;
  Toast.MakeText(mainActivity, "Email Succesfully Sent...", ToastLength.Short).Show();
 }
}

The Mail class can be executed by the following code

new MailAsyncTask(this).Execute();

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

In this article, we will learn how to apply custom fonts to Views in Android like Toolbar, MenuItem apart from the views like TextView...

How to custom fonts to Views - Android How to custom fonts to Views - Android

A blog about android developement

Xamarin.Android


In this article, we will learn how to apply custom fonts to Views in Android like Toolbar, MenuItem apart from the views like TextView, EditText.

FontUtils:

FontUtils is a tiny font utility library used to apply custom fonts to Views. It supports the following views.
  • Toolbar
  • NavigationView
  • Menu
  • Submenu
  • Other Views like EditText, TextView, etc.
This library is support the following Languages.
  • Android – Java
  • Android – Kotlin
  • Android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Setting up the Library for Android Views.
Step 3: Applying Custom fonts to Android Views.

Step 1:Creating New Project with Empty Activity

  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select Empty activity.
  3. Click “finish” button to create new project in Android Studio.

Step 2:Setting up the Library for Android Views

In this part, we will see how to setup the library for the project.
  1. Open your app level build.gradle file and add the following lines to download the library.
    …
    implementation 'com.ajts.androidmads.fontutils:fontutils:1.0.1'
    …
    
  2. Then Click “Sync Now” to download the library.
  3. We need to use “compile” instead of “implementation” if we have using Android Studio Version below 3.0.

Step 3:Applying Custom fonts to Android Views

In this part, we will see how to apply custom fonts to Views. Here, we have to use “Typeface” and to more about “TypeFace” Click here.
  1. In this article, I am assigning the fonts from Assets folder. To create assets folder, right on the app folder and select New. Then select Folder and click assets folder.
  2. Then Copy and Paste the fonts you want to use with your application.
  3. The following line shows how to initialize the library.
    // Applying Custom Font
    Typeface typeface = Typeface.createFromAsset(getAssets(), "custom_font.ttf");
    // Init Library
    FontUtils fontUtils = new FontUtils();
  4. Then Initialize your Views and apply the fonts to the Views. The following example shows how to apply the fonts to Toolbar of your application.
    // Apply font to Toolbar
    fontUtils.applyFontToToolbar(toolbar, typeface);
  5. You can apply custom fonts to other views like NavigationView, Menu, Submenu, TextView like in following example.
    // Apply font to NavigationView
    fontUtils.applyFontToNavigationView(navigationView, typeface);
    // Apply font to Menu
    fontUtils.applyFontToMenu(menu, typeface);
    // Apply font to Other Views like TextView...
    fontUtils.applyFontToView(textview, typeface);
    fontUtils.applyFontToView(editText, typeface);
    fontUtils.applyFontToView(radioButton, typeface);
    fontUtils.applyFontToView(checkBox, typeface);

For Kotlin

We need to do the same steps mentioned. But we need to include Kotlin support while creating the project. Apply font to Views in Kotlin as show below.
// Applying Custom Font
val typeface = Typeface.createFromAsset(assets, "custom_font.ttf")
// Init Library
val fontUtils = FontUtils()
// Apply font to Toolbar
fontUtils.applyFontToToolbar(toolbar, typeface)
// Apply font to NavigationView
fontUtils.applyFontToNavigationView(navigationView, typeface)
// Apply font to Menu
fontUtils.applyFontToMenu(menu, typeface)
// Apply font to Other Views like TextView...
fontUtils.applyFontToView(textview, typeface)
fontUtils.applyFontToView(editText, typeface)
fontUtils.applyFontToView(radioButton, typeface)
fontUtils.applyFontToView(checkBox, typeface)

For Xamarin.Android

We can apply the same with Xamarin.Android. To know more Click Here.


Download Code

The article is informative do like and star the repo in GitHub. You can download the code here.
Note:
Java and Kotlin Android Support
https://github.com/androidmads/FontUtils
Xamarin.Android Support
https://github.com/Xamarin-Gists/XAFontUtilsLibrary