前面我们已经学了关于服务的很多知识,但是对于真实的开发那些远远不够,通过这节我们将学习其他类型的服务,比如前台服务、IntentService和消息服务。下面我们开始进入正题。
二、前台服务
顾名思义,就是拥有前台的优先等级。当然服务还是不可见的。因为前面我们介绍过Android系统会在低内存的情况下将一些长时间不用的应用关闭,如果还是不够,那么就会通过关闭服务服务来达到目的,然而对于某些应用而言,这样将会影响用户的正常使用。比如听音乐,我们基本上都会打开应用选择歌曲后将应用置为后台。但是你会发现通知栏中会存在这个通知并且无法移除,只有正确的退出这个应用了才会消失,而这节我们就要实现这个功能。
首先我们必须要用一个通知,通过这个通知我们的服务才能够变成前台服务,这里我们新建一个名为ForegroundService的服务,然后重写OnStartCommand方法。
1 public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) 2 { 3 var notify = new Notification(Resource.Drawable.Icon, "前台服务"); 4 var activityIntent = new Intent(this, typeof(MainActivity)); 5 var activityPintent = PendingIntent.GetActivity(this, 0, activityIntent, PendingIntentFlags.UpdateCurrent); 6 notify.SetLatestEventInfo(this, "标题", "内容", activityPintent); 7 StartForeground((int)NotificationFlags.ForegroundService, notify); 8 return StartCommandResult.Sticky; 9 }
很多代码都是我们在讨论通知的时候都已经掌握的了,既然是前台服务,自然最后发送这个方法是不同的,我们需要使用服务的StartForeground来发送这个通知,同时第一个参数也要设置为前台服务,这样我们就可以看到如图的结果了(需要在MainActivity的OnCreate方法中开启该服务)。
虽然已经是一个前台服务了,但是我们只能通过服务不断的更新这个通知,而无法接收用户的事件,下面我们还要实现一个自定义界面的通知,上面有一个Text和两个Button用户点击不同的按钮后将由服务去更新通知,从而改变Text中的值。
首先我们在Resources/layout/下新建一个NotificationLayout视图,并在其中写入如下的xml标记。
1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:p1="http://schemas.android.com/apk/res/android" 3 p1:minWidth="25px" 4 p1:minHeight="25px" 5 p1:layout_width="match_parent" 6 p1:layout_height="match_parent" 7 p1:id="@+id/relativeLayout1"> 8 <TextView 9 p1:text="0" 10 p1:textAppearance="?android:attr/textAppearanceLarge" 11 p1:layout_width="wrap_content" 12 p1:layout_height="match_parent" 13 p1:id="@+id/textView1" /> 14 <Button 15 p1:text="显示1" 16 p1:layout_width="wrap_content" 17 p1:layout_height="match_parent" 18 p1:layout_toRightOf="@id/textView1" 19 p1:id="@+id/button1" /> 20 <Button 21 p1:text="显示2" 22 p1:layout_width="wrap_content" 23 p1:layout_height="match_parent" 24 p1:layout_toRightOf="@id/button1" 25 p1:id="@+id/button2" /> 26 </RelativeLayout>