简体   繁体   中英

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

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM