Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing string data from Android MainActivity to PCL TabbedPage xamarin.form

Tags:

Hello everyone Good Day how do I pass string value or data from Android MainActivity to PCL TabbedPage?

MainActivity.cs

 using System;
 using Android.App;
 using Android.Content;
 using Android.Content.PM;
 using Android.Runtime;
 using Android.OS;
 using Android.Telephony;
 using Xamarin.Forms;

   namespace NegDrClient.Droid
   {
   [Activity (Label = "Neg Client", Icon = "@drawable/logo", MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait)]
   public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
   {

       protected override void OnCreate (Bundle bundle)
       {
           base.OnCreate (bundle);
           global::Xamarin.Forms.Forms.Init (this, bundle);
           global::ZXing.Net.Mobile.Forms.Android.Platform.Init ();
           LoadApplication (new App ());
        }

       public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
       {
           global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult (requestCode, permissions, grantResults);           
       }

       public string GetNumber()
       {
          TelephonyManager telephonyManager =
            (TelephonyManager) Forms.Context.GetSystemService(Android.Content.Context.TelecomService);
          var number = telephonyManager.Line1Number;
          return number.ToString(); 
       }
     }
   }

I need to call the GetNumber() method so I can assign it to my login entry, Thanks.

like image 902
jake talledo Avatar asked Jul 12 '16 10:07

jake talledo


1 Answers

You can do this via a Dependency Service.

Add the following interface to your Xamarin.Forms project:

public interface IPhone
{
    string GetNumber();
}

Add that interface to your existing MainActivity within your Xamarin.Android project:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity, IPhone

Register that Dependency class (above your namespace NegDrClient.Droid):

[assembly: Xamarin.Forms.Dependency(typeof(MainActivity))]

Now you can call it in your Xamarin.Forms project:

var GetNumberButton = new Button()
{
    Command = new Command(() => {
        Device.BeginInvokeOnMainThread(() =>
        {
            var number = DependencyService.Get<IPhone>().GetNumber();
            System.Diagnostics.Debug.WriteLine(number);
        });
    })
};

Note: Your GetNumber method has an error in it, should be:

public string GetNumber()
{
    var telephonyManager = (TelephonyManager)Forms.Context.GetSystemService(Context.TelephonyService);
    return telephonyManager.Line1Number;
}
like image 193
SushiHangover Avatar answered Sep 28 '22 03:09

SushiHangover