Xamarin.Android开发实践(七)

原文:Xamarin.Android开发实践(七)html

Xamarin.Android广播接收器与绑定服务

1、前言

学习了前面的活动与服务后,你会发现服务对于活动而言彷佛就是透明的,相反活动对于服务也是透明的,因此咱们还须要一中机制可以将服务和活动之间架起一座桥梁,经过本节的学习,你将会学到广播与绑定服务,这两种方式偏偏是解决上面问题的关键。java

 

2、简单的广播接收器

实现一个最简单的广播接收器须要继承BroadcastReceiver类,而且还要实现OnReceive方法,咱们能够在项目中新建一个MainReceiver类,而后写入以下代码:c#

1     public class MainReceiver : BroadcastReceiver 2  { 3 public override void OnReceive(Context context, Intent intent) 4  { 5 6  } 7 }

 上面其实已经实现了一个简单的广播接收器,而且可使用。咱们还须要注册广播接收器,不然广播接收器就没法接收广播,因此咱们须要在MainActivity.cs中注册这个广播接收器。固然为了可以接近现实,咱们须要在OnResume中注册,在OnPause中注销。异步

首先咱们在OnResume中注册ide

1         protected override void OnResume() 2  { 3 base.OnResume(); 4 receiver = new MainReceiver(); 5 RegisterReceiver(receiver, new IntentFilter("xamarin-cn.main.receiver")); 6 }

 接着咱们在OnPause中注销post

1         protected override void OnPause() 2  { 3 base.OnPause(); 4  UnregisterReceiver(receiver); 5 }

 所有代码以下所示学习

 1     [Activity(Label = "BroadcastStudy", MainLauncher = true, Icon = "@drawable/icon")]  2 public class MainActivity : Activity  3  {  4 private MainReceiver receiver;  5  6 protected override void OnCreate(Bundle bundle)  7  {  8 base.OnCreate(bundle);  9  SetContentView(Resource.Layout.Main); 10  } 11 12 protected override void OnResume() 13  { 14 base.OnResume(); 15 receiver = new MainReceiver(); 16 RegisterReceiver(receiver, new IntentFilter("xamarin-cn.main.receiver")); 17  } 18 19 protected override void OnPause() 20  { 21 base.OnPause(); 22  UnregisterReceiver(receiver); 23  } 24 }

 注册好了广播接收器,咱们还须要一个可以发送广播的地方,既然咱们说了这节重点解决的是服务与活动的通讯,那么咱们就实现一个服务来发送广播。为了可以贴近现实,咱们的服务中将会新建一个线程,让这个线程发送一个广播给这个广播接收器。this

 1  [Service]  2 public class MainService : Service  3  {  4 public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)  5  {  6 new Thread(() =>  7  {  8 Thread.Sleep(1000);  9 var sintent = new Intent("xamarin-cn.main.receiver"); 10 sintent.PutExtra("_str", "来自服务"); 11  SendBroadcast(sintent); 12  }).Start(); 13 return StartCommandResult.Sticky; 14  } 15 16 public override IBinder OnBind(Intent intent) 17  { 18 return null; 19  } 20 }

这里咱们经过意图传递了一个参数,而在服务中发送广播的方法是SendBroadcast。其实咱们能够看到在建立意图的时候传入了一个字符串,而这个字符串必须与注册广播接收器时指定的字符串一致,不然对应的广播接收器是没法接收到这个广播的,下面咱们修改广播接收器的OnReceive方法,以便获取传递过来的字符串并显示。url

1         public override void OnReceive(Context context, Intent intent) 2  { 3 string str = intent.GetStringExtra("_str"); 4 new Handler().Post(() => 5  { 6  Toast.MakeText(Application.Context, str, ToastLength.Long).Show(); 7  }); 8 }

其中咱们经过意图的GetXXXX方法获取传递过来的参数,而后建立了一个Handler对象并使用Toast发送了一个提示,这里使用Handler是为了与UI线程同步。由于前面讲过只用UI线程才可以访问控件等等对象,而这里并无RunOnUiThread方法,因此咱们须要使用Handler对象的Post方法来实现。spa

 

最后有了服务还不行,咱们还须要开启这个服务。固然咱们依然仍是要在OnResume中开启,在OnPause中暂停。

 1         protected override void OnResume()  2  {  3 base.OnResume();  4 receiver = new MainReceiver();  5 RegisterReceiver(receiver, new IntentFilter("xamarin-cn.main.receiver"));  6 StartService(new Intent(this, typeof(MainService)));  7  }  8  9 protected override void OnPause() 10  { 11 base.OnPause(); 12  UnregisterReceiver(receiver); 13 StopService(new Intent(this, typeof(MainService))); 14 }

最后咱们运行以后的结果以下所示

 

3、服务向活动发送消息

上面的例子咱们仅仅只是打通了服务与广播接收器的通讯,而咱们今天的主题是服务与活动的双向通讯,可是为了可以按部就班学习,因此咱们先学习了服务与广播接收器怎么通讯,而这节咱们将学习广播接收器如何与活动通讯。

 

由于c#并无java的部分语言的特性,因此咱们无法直接经过匿名的方法建立一个继承自BroadcastReceiver类的实例,因此咱们须要先建立一个继承自BroadcastReceiver的具体类,而后在其中定义活动须要响应的方法的委托(Action或者Func),这样咱们能够在实例化这个具体类的同时将活动中的方法赋给广播接收器,这样广播接收器在OnReceive中就能够调用活动中的方法了,天然而言就打通了广播接收器与活动的通讯。固然还有其余的方法,但愿读者能够在留言中留下,以便更多的人进行学习。

首先修改MainReceiver类:

 1     public class MainReceiver : BroadcastReceiver  2  {  3 public Action<string> Alert;  4  5 public override void OnReceive(Context context, Intent intent)  6  {  7 string str = intent.GetStringExtra("_str");  8 if (Alert != null)  9  { 10  Alert(str); 11  } 12  } 13 }

在这里咱们定义了一个委托(Action<string>  Alert)以便活动能够重写,同时还修改了OnReceive中的代码,从而使用活动的方法来显示提示,有了接口以后,咱们就能够回到活动中进行重写了。由于广播被实例化的步骤是在OnResume中,因此咱们这里直接给出这个方法中的代码(这里咱们使用了一个TextView控件tv读者能够须要自行添加下)。

 1         protected override void OnResume()  2  {  3 base.OnResume();  4 receiver = new MainReceiver()  5  {  6 Alert = (s) =>  7  {  8 RunOnUiThread(() =>  9  { 10 tv.Text = s; 11  }); 12  } 13  }; 14 RegisterReceiver(receiver, new IntentFilter("xamarin-cn.main.receiver")); 15 StartService(new Intent(this, typeof(MainService))); 16 }

如今咱们就打通了广播接收器与活动的桥梁,若是有多个方法也是同样的道理,咱们现 在运行程序能够发现一切正常,下面笔者还要介绍另外一种使用接口的方法,首先咱们须要一个接口去规定活动须要实现哪些方法,而后在初始化广播接收器的同时将 活动的实例赋广播接收器的对应接口变量。下面咱们将上面的例子改写,先定义个含有Alert的接口。

1     public interface IMainInterface 2  { 3 void Alert(string s); 4 }

而后让活动实现该接口

    public class MainActivity : Activity, IMainInterface { private MainReceiver receiver; private TextView tv; public void Alert(string s) { RunOnUiThread(() => { tv.Text = s; }); }

接着咱们修改广播接收器,公开一个该接收的属性,一遍在广播接收器被初始化的时候能够复制。

 1     public class MainReceiver : BroadcastReceiver  2  {  3 public IMainInterface mainInterface;  4  5 public override void OnReceive(Context context, Intent intent)  6  {  7 string str = intent.GetStringExtra("_str");  8 if (mainInterface != null)  9  { 10  mainInterface.Alert(str); 11  } 12  } 13 }

回到MainActivity中修改OnResume方法。

 1         protected override void OnResume()  2  {  3 base.OnResume();  4 receiver = new MainReceiver()  5  {  6 mainInterface = this  7  };  8 RegisterReceiver(receiver, new IntentFilter("xamarin-cn.main.receiver"));  9 StartService(new Intent(this, typeof(MainService))); 10 }

最后效果同样的,读者能够根据实际的状况选择。毕竟他们各自都有或多或少的缺点。

 

4、绑定服务

其实绑定服务就是将服务中的功能公开给活动,只有这样活动才能调用服务中的方法。而这一过程须要通过一个绑定。首先咱们须要一个继承自Binder的类,这样才能将服务经过接口传递给活动。如下为继承自Binder的类,其中咱们须要在初始化时将服务传入,而后公开一个方法将服务的实例返回。

 1     public class MainBinder : Binder  2  {  3  MainService mainService;  4  5 public MainBinder(MainService ms)  6  {  7 mainService = ms;  8  }  9 10 public MainService GetService() 11  { 12 return mainService; 13  } 14 }

接下来咱们打开MainService文件,实现OnBind方法,并将上面类返回。

 1  [Service]  2 public class MainService : Service  3  {  4 public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)  5  {  6 return StartCommandResult.Sticky;  7  }  8  9 public override IBinder OnBind(Intent intent) 10  { 11 return new MainBinder(this); 12  } 13 }

到此为止,服务这边已经作好了准备。既然是绑定天然不能经过简单的StartService方法开启,由于咱们还须要OnBind返回的接口,不然活动没法与服务沟通。这就须要在活动中经过BindService方法进行绑定,可是该方法还须要一个实现了IserviceConnection接口的类,由于经过BindService方法进行绑定的操做是异步的,也就意味着不会阻塞当前调用该方法的线程,而是在服务成功开启并而且OnBind方法返回接口后会回调IserviceConnection中的方法,咱们能够看下该接口的方法。

1     public interface IServiceConnection : IJavaObject, IDisposable 2  { 3 void OnServiceConnected(ComponentName name, IBinder service); 4 void OnServiceDisconnected(ComponentName name); 5 }

关于接口的方法,大体的解释以下:

OnServiceConnected:当服务中的OnBind方法返回接口后将回调该方法,而且经过service参数将OnBind返回的值传递给这个方法。

OnServiceDisconnected:当服务被关闭或者主动断开链接后回调该方法,若是咱们利用这个方法从新恢复链接,或者发出异常并关闭对应的活动。

 

下面咱们实现该接口

 1     public class MainServiceConnection : Java.Lang.Object , IServiceConnection  2  {  3 public void OnServiceConnected(ComponentName name, Android.OS.IBinder service)  4  {  5  6  }  7  8 public void OnServiceDisconnected(ComponentName name)  9  { 10 11  } 12 }

 

这里咱们没有实现任何代码,该类与活动尚未关联起来,因此咱们须要在活动中新建一个公开的变量去保存服务的接口。

1     [Activity(Label = "BroadcastStudy", MainLauncher = true, Icon = "@drawable/icon")] 2 public class MainActivity : Activity 3  { 4 private TextView tv; 5 public MainBinder mainBinder;

接着咱们就能够实现MainServiceConnection类了。

 1     public class MainServiceConnection : Java.Lang.Object , IServiceConnection  2  {  3  MainActivity mainActivity;  4 public MainServiceConnection(MainActivity ma)  5  {  6 mainActivity = ma;  7  }  8  9 public void OnServiceConnected(ComponentName name, Android.OS.IBinder service) 10  { 11 mainActivity.mainBinder = (MainBinder)service; 12  } 13 14 public void OnServiceDisconnected(ComponentName name) 15  { 16 mainActivity.mainBinder = null; 17  } 18 }

最后咱们在活动中就能够进行绑定了。


 1     [Activity(Label = "BroadcastStudy", MainLauncher = true, Icon = "@drawable/icon")]  2 public class MainActivity : Activity  3  {  4 private IServiceConnection serviceConnection;  5 private TextView tv;  6 public MainBinder mainBinder;  7  8  9 protected override void OnCreate(Bundle bundle) 10  { 11 base.OnCreate(bundle); 12  SetContentView(Resource.Layout.Main); 13 tv = FindViewById<TextView>(Resource.Id.textView1); 14  } 15 16 protected override void OnResume() 17  { 18 base.OnResume(); 19 serviceConnection = new MainServiceConnection(this); 20 BindService(new Intent(this, typeof(MainService)), serviceConnection, Bind.AutoCreate); 21  } 22 23 protected override void OnPause() 24  { 25 base.OnPause(); 26  UnbindService(serviceConnection); 27  } 28 }

经过上面的步骤咱们还不能看到实际的效果,下面咱们须要在服务中实现一个简单的方法,只是返回一段字符串。

1         public string GetString() 2  { 3 return "来自服务"; 4 }

而后在Main.axml中拖放一个按钮,并在活动中进行绑定。

 1         protected override void OnCreate(Bundle bundle)  2  {  3 base.OnCreate(bundle);  4  SetContentView(Resource.Layout.Main);  5 Button btn = FindViewById<Button>(Resource.Id.button1);  6 btn.Click += (e, s) =>  7  {  8 if (mainBinder != null)  9  { 10 string str = mainBinder.GetService().GetString(); 11 Toast.MakeText(this, str, ToastLength.Long).Show(); 12  } 13  }; 14 }

这样咱们就完成了活动调用服务中的方法,可是现实开发中。若是是耗时的任务。都是活动调用服务公开的方法后当即返回,而后服务在完成以后经过广播将处理的结果返回给活动,整个过程都是异步的。

相关文章
相关标签/搜索