Xamarin Android : Change UI TextView text from Service or Receiver

妖精的绣舞 提交于 2019-12-30 11:35:12

问题


I have calling app using Twilio api, and i'm trying to change status TextView text after the service established, i searched to much but i didn't find any helpful solution, i want change the text from the service or broadcast receiver . My service code below :

  [Service]
    class CallService : IntentService
    {


        public static  MonkeyPhone phone ;

        protected override void OnHandleIntent(Intent intent)
        {
            throw new NotImplementedException();
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {

            // countine
            new Task(() =>
            {
                phone = new MonkeyPhone(ApplicationContext);


                 View view = View.Inflate(ApplicationContext, Resource.Layout.Main, null);
                TextView connectionStatus = view.FindViewById<TextView>(Resource.Id.connectionStatus);
                connectionStatus.Text = "Connected ..";

            }).Start();



            return StartCommandResult.Sticky;
        }


    }

The service working well and the phone connect is established well, just need to know how could i change the textView text

Attention : the textView is inside fragment


回答1:


The service working well and the phone connect is established well, just need to know how could i change the textView text

First of all, you need to implement this feature in Receiver, not in Service.

In your service, you should be able to send text for example like this:

[Service]
public class MyIntentService : IntentService
{
    public MyIntentService() : base("MyIntentService")
    {
    }

    protected override void OnHandleIntent(Intent intent)
    {
        //get data when service started.
        var value = intent.GetStringExtra("ServiceInfo");

        //send data to activity
        Intent myintent = new Intent("IntentServiceAndReceiver");
        myintent.PutExtra("NewInfo", "Connected...!");
        SendBroadcast(myintent);
    }
}

And create your Receiver and MainActivity for example like this:

public class MainActivity : Activity { private MyReceiver receiver;

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    receiver = new MyReceiver(this);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    //show fragment in framelayout container
    FragmentTransaction ft = this.FragmentManager.BeginTransaction();
    var myfragment = new MyFragment();
    ft.Add(Resource.Id.container, myfragment).AddToBackStack(null).Commit();
}

protected override void OnResume()
{
    base.OnResume();
    RegisterReceiver(receiver, new IntentFilter("IntentServiceAndReceiver"));
}

protected override void OnPause()
{
    UnregisterReceiver(receiver);
    base.OnPause();
}

    [BroadcastReceiver(Enabled = true, Exported = false)]
    [IntentFilter(new[] { "IntentServiceAndReceiver" })]

    public class MyReceiver : BroadcastReceiver
    {
        private Activity mactivity;

        public MyReceiver()
        {
        }

        public MyReceiver(Activity activity)
        {
            mactivity = activity;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            var value = intent.GetStringExtra("NewInfo");

            //update textview in fragment
            if (mactivity != null)
            {
                var myfragment = mactivity.FragmentManager.FindFragmentById<MyFragment>(Resource.Id.container);
                myfragment.UpdateText(value);
            }
        }
    }
}

I placed a Button to start service and a TextView to show text in the layout of Fragment and code like this:

public class MyFragment : Fragment
{
    private TextView tv;

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Use this to return your custom view for this Fragment
        var view = inflater.Inflate(Resource.Layout.FLayout, container, false);
        tv = view.FindViewById<TextView>(Resource.Id.tv);
        var btn = view.FindViewById<Button>(Resource.Id.startS);
        btn.Click += (sender, e) =>
        {
            // This code might be called from within an Activity, for example in an event
            // handler for a button click.
            Intent myintent = new Intent(this.Context, typeof(MyIntentService));

            // This is just one example of passing some values to an IntentService via the Intent:
            myintent.PutExtra("ServiceInfo", "This is the information!");

            this.Context.StartService(myintent);
        };
        return view;
    }

    public void UpdateText(string text)
    {
        tv.Text = text;
    }
}

Here is the result:



来源:https://stackoverflow.com/questions/46409563/xamarin-android-change-ui-textview-text-from-service-or-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!