Xamarin.Android其他类型的服务
一、前言
前面我们已经学了关于服务的很多知识,但是对于真实的开发那些远远不够,通过这节我们将学习其他类型的服务,比如前台服务、IntentService和消息服务。下面我们开始进入正题。
二、前台服务
顾名思义,就是拥有前台的优先等级。当然服务还是不可见的。因为前面我们介绍过Android系统会在低内存的情况下将一些长时间不用的应用关闭,如果还是不够,那么就会通过关闭服务服务来达到目的,然而对于某些应用而言,这样将会影响用户的正常使用。比如听音乐,我们基本上都会打开应用选择歌曲后将应用置为后台。但是你会发现通知栏中会存在这个通知并且无法移除,只有正确的退出这个应用了才会消失,而这节我们就要实现这个功能。
首先我们必须要用一个通知,通过这个通知我们的服务才能够变成前台服务,这里我们新建一个名为ForegroundService的服务,然后重写OnStartCommand方法。
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
var notify = new Notification(Resource.Drawable.Icon, "前台服务");
var activityIntent = new Intent(this, typeof(MainActivity));
var activityPintent = PendingIntent.GetActivity(this, , activityIntent, PendingIntentFlags.UpdateCurrent);
notify.SetLatestEventInfo(this, "标题", "内容", activityPintent);
StartForeground((int)NotificationFlags.ForegroundService, notify);
return StartCommandResult.Sticky;
}
很多代码都是我们在讨论通知的时候都已经掌握的了,既然是前台服务,自然最后发送这个方法是不同的,我们需要使用服务的StartForeground来发送这个通知,同时第一个参数也要设置为前台服务,这样我们就可以看到如图的结果了(需要在MainActivity的OnCreate方法中开启该服务)。
虽然已经是一个前台服务了,但是我们只能通过服务不断的更新这个通知,而无法接收用户的事件,下面我们还要实现一个自定义界面的通知,上面有一个Text和两个Button用户点击不同的按钮后将由服务去更新通知,从而改变Text中的值。
首先我们在Resources/layout/下新建一个NotificationLayout视图,并在其中写入如下的xml标记。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:p1="http://schemas.android.com/apk/res/android"
p1:minWidth="25px"
p1:minHeight="25px"
p1:layout_width="match_parent"
p1:layout_height="match_parent"
p1:id="@+id/relativeLayout1">
<TextView
p1:text="0"
p1:textAppearance="?android:attr/textAppearanceLarge"
p1:layout_width="wrap_content"
p1:layout_height="match_parent"
p1:id="@+id/textView1" />
<Button
p1:text="显示1"
p1:layout_width="wrap_content"
p1:layout_height="match_parent"
p1:layout_toRightOf="@id/textView1"
p1:id="@+id/button1" />
<Button
p1:text="显示2"
p1:layout_width="wrap_content"
p1:layout_height="match_parent"
p1:layout_toRightOf="@id/button1"
p1:id="@+id/button2" />
</RelativeLayout>
打开ForegroundService并在其中新建一个CreateNotify方法,并在其中写入如下代码。
public Notification CreateNotify(string text)
{
notify = new Notification(Resource.Drawable.Icon, "前台服务");
var sintent = new Intent(this, typeof(MainActivity));
sintent.SetFlags(ActivityFlags.LaunchedFromHistory);
notify.ContentView = new RemoteViews(PackageName, Resource.Layout.NotificationLayout);
notify.ContentIntent = PendingIntent.GetActivity(this, , sintent, PendingIntentFlags.NoCreate); var btn1Intent = new Intent(this, typeof(ForegroundService));
btn1Intent.PutExtra("showBtn1", true);
var btn1Pintent = PendingIntent.GetService(this, , btn1Intent, PendingIntentFlags.UpdateCurrent);
notify.ContentView.SetOnClickPendingIntent(Resource.Id.button1, btn1Pintent); var btn2Intent = new Intent(this, typeof(ForegroundService));
btn2Intent.PutExtra("showBtn2", true);
var btn2Pintent = PendingIntent.GetService(this, , btn2Intent, PendingIntentFlags.UpdateCurrent);
notify.ContentView.SetOnClickPendingIntent(Resource.Id.button2, btn2Pintent); notify.ContentView.SetTextViewText(Resource.Id.textView1, text);
return notify;
}
这里需要说明下,一旦通知发送出去了我们是无法同ContentView的Set去修改控件的,只能重新发送这个同时去更新旧的通知,所以笔者才需要一个单独的方法负责创建通知。上面的代码我们之前都已经学习过了,不理解的可以看这篇文件《Xamarin.Android通知详解》。笔者设置按钮的点击事件是打开服务本身,同时还通过Intent传递了一个参数,因为后面我们需要通过这些参数去区分哪个按钮按下了,同时还要注意PendingIntent的GetService方法的第二个参数,我们两者都是0那么会造成按下按钮1和按纽2都传递同样的参数。下面我们在OnStartCommand中实现响应。
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
if (notify == null)
{
notify = CreateNotify("初始化");
StartForeground((int)NotificationFlags.ForegroundService, notify);
}
bool isBtn1Click = intent.GetBooleanExtra("showBtn1", false);
bool isBtn2Click = intent.GetBooleanExtra("showBtn2", false);
if (isBtn1Click)
{
if (notify != null)
{
notify = CreateNotify("来自按钮1");
StartForeground((int)NotificationFlags.ForegroundService, notify);
}
}
else if (isBtn2Click)
{
if (notify != null)
{
notify = CreateNotify("来自按钮2");
StartForeground((int)NotificationFlags.ForegroundService, notify);
}
}
return StartCommandResult.Sticky;
}
可以看到我们通过GetBooleanExtra获取了通过意图传递的参数,当然笔者这里的用法不同于前面的方式,我还传入了第二个参数,这样做的目的就是在意图中不存在该值的时候将会把第二参数返回,下面就是进行不同的判断从而更新通知。
最终运行结果如下所示:
按下“显示1”后
按下“显示2”后
至此我们就完成了前台服务的学习。
三、IntentService
很多时候我们都需要利用服务进行耗时的操作,势必需要创建新的线程去处理。但是普通的Service并不会主动创建而需要开发者自行在OnStartCommand中去创建,为此就繁衍出了IntentService类,它会为我们创建好线程去执行我们的代码,从而避免一些代码。但是我们不能重写OnStartCommand方法而应该是OnHandleIntent方法。比如下面的代码。
[Service]
public class MainIntentService : IntentService
{
protected override void OnHandleIntent(Android.Content.Intent intent)
{
Thread.Sleep();
Toast.MakeText(this, "来自新线程" , ToastLength.Long).Show();
}
}
通过下面的截图我们可以看到OnHandleIntent中执行的代码是新建的一个线程
关于IntentService的使用非常简单。
四、通信服务
上一节关于绑定服务的学习中,活动必须确切的知道服务的类型才能使用,这样就加大了他们之间的耦合度,而通过本节我们将会学习如何通过消息机制将他们解耦,首先我们需要理解Handler类,它将会负责处理发送过来的消息,我们需要继承该类,并重写HandleMessage方法,我们新建一个MainHandler类并继承该类,然后重写。
public class MainHandler : Handler
{
public override void HandleMessage(Message msg)
{
Toast.MakeText(Application.Context, "接收到的消息的what为" + msg.What.ToString() + " 内容为" + msg.Data.GetString("_str"), ToastLength.Short).Show();
}
}
这里我们仅仅只是简单的输出了消息的类型以及消息传递的参数,下面我们还需要一个服务将这个消息传递给活动。
[Service]
public class MessengerService : Service
{
Messenger messenger; public MessengerService()
{
messenger = new Messenger(new MainHandler());
} public override Android.OS.IBinder OnBind(Android.Content.Intent intent)
{
return messenger.Binder;
}
}
这里我们还需要Messenger去封装MainHandler,因为MainHandler是无法在OnBind中直接返回的,只有Messenger的Binder属性可以,自然活动那边就需要接收这个接口,下面是IserviceConnection的实现。
public class MessengerServiceConnection : Java.Lang.Object , IServiceConnection
{
MainActivity mainActivity; public MessengerServiceConnection(MainActivity ma)
{
mainActivity = ma;
} public void OnServiceConnected(ComponentName name, Android.OS.IBinder service)
{
mainActivity.messenger = new Messenger(service);
} public void OnServiceDisconnected(ComponentName name)
{
mainActivity.messenger.Dispose();
mainActivity.messenger = null;
}
}
这里的方式依然是使用之前我们讲述绑定服务时候的方法,只是在我们接收接口的时候是用Messenger的去封装的,这样就统一了。我们的活动只要有Messenger,并且对应的服务都满足这个接口那么我们的活动就可以灵活的绑定任意服务,使用他们的功能了,最后是MainActivity的代码(需要在Main.axml中拖拽两个按钮,以便发送消息给服务)。
[Activity(Label = "OtherService", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
public Messenger messenger; protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
BindService(new Intent(this, typeof(MessengerService)), new MessengerServiceConnection(this), Bind.AutoCreate);
Button btn1 = FindViewById<Button>(Resource.Id.button1);
btn1.Click += (e, s) =>
{
Message msg = Message.Obtain();
Bundle b = new Bundle();
b.PutString("_str", "消息1");
msg.Data = b;
msg.What = ;
messenger.Send(msg);
}; Button btn2 = FindViewById<Button>(Resource.Id.button2);
btn2.Click += (e, s) =>
{
Message msg = Message.Obtain();
Bundle b = new Bundle();
b.PutString("_str", "消息2");
msg.Data = b;
msg.What = ;
messenger.Send(msg);
};
}
}
唯一要说的就是发送消息,我们需要实例化Messager(不是Messenger),设置它的what,如果我们还需要传递更多的参数我们可以实例化一个Bundle,然后通过其PutXXX方法赋值,最后赋给Message的Data类型,最后要通过Messenger实例的Send方法发送这个消息,那么MainHandler就可以处理这个消息了。
下面是实际的运行图。
点击“发送消息1”按钮后
点击“发送消息2”按钮后
Xamarin.Android其他类型的服务的更多相关文章
- [译]:Xamarin.Android平台功能——位置服务
返回索引目录 原文链接:Location Services. 译文链接:Xamarin.Android平台功能--位置服务 本部分介绍位置服务以及与如何使用位置提供商服务 Location Servi ...
- Xamarin.Android开发实践(八)
Xamarin.Android其他类型的服务 一.前言 前面我们已经学了关于服务的很多知识,但是对于真实的开发那些远远不够,通过这节我们将学习其他类型的服务,比如前台服务.IntentService和 ...
- Xamarin.Android服务的实现
一.服务的生命周期 服务与活动一样,在它的整个生命周期中存在着一些事件,下图可以很好解释整个过程以及涉及到的方法: 在真实的使用中,Service来还包含一个OnBind方法,并且必须要使用该方法,但 ...
- Xamarin.Android编译CPU类型选择方式
Xamarin.Android编译CPU类型选择方式 在Xamarin.Android编译的时候,默认提供了5种CPU类型供大家选择.它们分别为armeabi.armeabi-v7a.arm64-v8 ...
- Xamarin Android设置界面提示类型错误
Xamarin Android设置界面提示类型错误 错误信息:Integer types not allow (at ‘padding’ with value ’10’)Android界面属性的长度和 ...
- Android开发-API指南-Bound 类型的服务
Bound Services 英文原文:http://developer.android.com/guide/components/bound-services.html 采集(更新)日期:2014- ...
- xamarin android如何将Java.Lang.Object类型转成C#类型
问题起源 其实这个标题也可以换一个更准确一点,因为我遇到的问题是: xamarin android中的Class继承了Java.Lang.Object ,将json序列化成c#类型时发现无法赋值,序列 ...
- XAMARIN.ANDROID SIGNALR 实时消息接收发送示例
SignalR 是一个开发实时 Web 应用的 .NET 类库,使用 SignalR 可以很容易的构建基于 ASP.NET 的实时 Web 应用.SignalR 支持多种服务器和客户端,可以 Host ...
- APP并非一个人在战斗,还有API—Xamarin.Android回忆录
前言 一般来说,一个客户端APP并非独立存在的,很多时候需要与服务器交互.大体可分为两方面的数据,常规字符串数据和文件数据,因为这两种数据很可能传输方式不一样,比如字符串之类的数据,使用HTTP协议, ...
随机推荐
- 全文居中及DIV居中
第一种方案(全文档): body { text-align: center; } body div { margin: 0 auto; } 第二种方案(某DIV): .testing- ...
- hdu4753 Fishhead’s Little Game 状态压缩,总和一定的博弈
此题和UVA 10891 Game of Sum 总和一定的博弈,区间dp是一个道理,就是预处理麻烦 这是南京网络赛的一题,一直没做,今天做了,虽然时间有点长,但是1ac,这几乎是南京现场赛的最后一道 ...
- 在PC上像普通winform程序调试WINCE程序
在PC上像普通winform程序调试WINCE程序 步骤: 1. 在VS2008中到 工具→选项→设备工具→设备,选择对应的平台,另存为新的名称,如CEDesktopRun,关闭VS2008.(如果不 ...
- Libnids读书笔记 (转)
一.当日工作(或学习)内容及进展情况(以条目式陈述,必要时配图说明) Libnids读书笔记: Libnids(Library Network Intusion Detection System)网络 ...
- [leetcode]Surrounded Regions @ Python
原题地址:https://oj.leetcode.com/problems/surrounded-regions/ 题意: Given a 2D board containing 'X' and 'O ...
- Java系列:JVM中的OopMap(zz)
调用栈里的引用类型数据是GC的根集合(root set)的重要组成部分:找出栈上的引用是GC的根枚举(root enumeration)中不可或缺的一环. JVM选择用什么方式会影响到GC的实现: 如 ...
- Triangle leetcode java
题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...
- C#将数据集DataSet中的数据导出到EXCEL文件的几种方法
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.W ...
- 转:EM算法总结
https://applenob.github.io/em.html EM算法总结 在概率模型中,最常用的模型参数估计方法应该就是最大似然法. EM算法本质上也是最大似然,它是针对模型中存在隐变量的情 ...
- List 集合的交集
private void Test() { List<string> lsA = new List<string>(); lsA.Add("A"); lsA ...