目标:
单击 开始自动刷新 按钮 ,每5秒自动刷新设备状态
实现:
正好学到了服务,所以不在本活动中实现,而是利用服务实现,从而学习以下三个知识点:一 定时 二 服务 三 通知
完整的服务类代码:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Util;
using System.Threading;
using Android.Support.V4.App;
using Android.Media;
using System.Net.Sockets;
using System.Net;
namespace JCFlat
{
[Service]
public class AutoRefreshLightService : Service
{
DateTime startTime;
Handler handler;
Action runnable;
bool bRun;
public override void OnCreate()
{
base.OnCreate();
bRun = true;
handler = new Handler();
runnable = new Action(ShowRunStatu); //非常不喜欢将程序直接写到new Action过程中,所以建立独立函数
}
public void ShowRunStatu()
{
if (bRun == false) //本过程循环读设备状态,用时较长,handler.RemoveCallbacks(runnable)有失败的可能,所以加了额外控制变量
return;
Socket socket; //用于连接到平板,平板有程序在监听某个端口
ISharedPreferences preMy = GetSharedPreferences("Settings", 0); //获取内部存储
string strcurrStore = preMy.GetString("currStore", "");
string[] LocalStoreArgs;
LocalStoreArgs = strcurrStore.Split("|");
string strStoreIp = LocalStoreArgs[5]; //仓房平板ip
int iStorePort = int.Parse(LocalStoreArgs[6]); //仓房平板监听端口号
string[] strLights;
strLights = LocalStoreArgs[13].Split(" "); //号码在数组项13 格式为11 12
string[] arrLightStatu = new string[strLights.Length];
for (int i = 0; i < strLights.Length; i++)
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //准备连接到仓房监听的端口
IPAddress ip = IPAddress.Parse(strStoreIp);
IPEndPoint point = new IPEndPoint(ip, iStorePort);
socket.SendTimeout = 2000;
socket.ReceiveTimeout = 2000;
socket.Connect(point);
byte[] var = new byte[1];
var[0] = byte.Parse(strLights[i].Substring(0, 1));
string msg = JCToolSet.MakeSendCmdStr(0, 0XD0, var.Length, var); // 发送读状态命令,格式为"55AA55AA00B00001000B7316E916E9
byte[] buffer = new byte[1024 * 1024 * 3];
buffer = System.Text.Encoding.UTF8.GetBytes(msg);
socket.Send(buffer);
//这里循环等待0.3秒,直到数据返回
Thread.Sleep(300);
byte[] bufferRec = new byte[1024 * 1024 * 3];
int len = socket.Receive(bufferRec); //实际接收到的有效字节数
string str = System.Text.Encoding.UTF8.GetString(bufferRec, 0, len);
socket.Close();
string[] arrLight = new string[1];
JCToolSet.AnaMoveWindMachineData(str, arrLight); //分析数据
byte bSubNum = byte.Parse(strLights[i].Substring(1, 1));
if (arrLight[0].Substring((bSubNum - 1), 1) == "0")
{
arrLightStatu[i] = "0";
}
else
{
arrLightStatu[i] = "1";
}
}
catch (Exception mye)
{
Console.WriteLine(mye.Message);
continue;
}
}
InCludeLight.ChangeTvStatu(" 刷新中..."); //启动这个服务的活动中的函数
InCludeLight.DisplayLightStatu(arrLightStatu); //启动这个服务的活动中的函数
handler.PostDelayed(runnable, 5000);
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
startTime = DateTime.UtcNow;
DispatchNotificationThatServiceIsRunning("启动时间: " + startTime.ToString("yyyy-MM-dd HH:mm:ss")); //弹出通知
InCludeLight.ChangeTvStatu(" 启动...");
handler.PostDelayed(runnable, 5000); //重要
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
DateTime stopTime = DateTime.UtcNow;
DispatchNotificationThatServiceIsRunning("启动时间: " + startTime.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + "停止时间: " + stopTime.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + "刷新用时: " + stopTime.Subtract(startTime)); //弹出通知
InCludeLight.ChangeTvStatu(" 停止...");
bRun = false;
handler.RemoveCallbacks(runnable);
base.OnDestroy();
}
public override IBinder OnBind(Intent intent)
{
// Return null because this is a pure started service. A hybrid service would return a binder that would
// allow access to the GetFormattedStamp() method.
return null;
}
void DispatchNotificationThatServiceIsRunning(string strActionAndTime)
{
//通道
NotificationChannel channel = new NotificationChannel(BaseContext.PackageName, "Testing Messages", NotificationImportance.High);
channel.EnableVibration(true);
channel.EnableLights(true);
channel.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification), new AudioAttributes.Builder().SetUsage(AudioUsageKind.Notification).Build());
channel.LockscreenVisibility = NotificationVisibility.Public;
//管理器
NotificationManager notificationManager = NotificationManager.FromContext(BaseContext);
notificationManager.CreateNotificationChannel(channel);
//构造器
Notification.Builder builder = new Notification.Builder(BaseContext, BaseContext.PackageName);
builder.SetContentTitle("刷新记录");
builder.SetContentText(strActionAndTime);
builder.SetAutoCancel(true);
builder.SetSmallIcon(Resource.Drawable.splash_logo);
//通知风格
var textStyle = new Notification.BigTextStyle();
textStyle.BigText(strActionAndTime);
builder.SetStyle(textStyle);
//通知
Notification notification = builder.Build();
//发起通知
notificationManager.Notify(1010, notification);
}
}
}
调用的活动:InCludeLight.cs中的部分内容
类变量:
Button btnStartAutoRefresh;
Button btnStopAutoRefresh;
static TextView tvStatu;
Intent serviceToStart;
OnCreate:
....
btnStartAutoRefresh = FindViewById<Button>(Resource.Id.buttonStartAutoRefresh);
btnStartAutoRefresh.Click += BtnStartAutoRefresh_Click;
btnStopAutoRefresh = FindViewById<Button>(Resource.Id.buttonStopAutoRefresh);
btnStopAutoRefresh.Click += BtnStopAutoRefresh_Click;
btnStopAutoRefresh.Enabled = false;
tvStatu= FindViewById<TextView>(Resource.Id.textViewStatu);
serviceToStart = new Intent(this, typeof(AutoRefreshLightService));
其他函数:
private void BtnStartAutoRefresh_Click(object sender, EventArgs e)
{
StartService(serviceToStart);
btnStartAutoRefresh.Enabled = false;
btnStopAutoRefresh.Enabled = true;
}
private void BtnStopAutoRefresh_Click(object sender, EventArgs e)
{
StopService(serviceToStart);
btnStartAutoRefresh.Enabled = true;
btnStopAutoRefresh.Enabled = false;
}
protected override void OnDestroy()
{
StopService(serviceToStart);
base.OnDestroy();
}
public static void ChangeTvStatu(string strStatu)
{
tvStatu.Text = strStatu;
}
public static void DisplayLightStatu(string [] arrLightStatu)
{
for (int i = 0; i < adapter.ItemCount; i++)
{
//try
//{
if (arrLightStatu[i] == "0")
{
adapter.SetItemImage(i, Resource.Drawable.LightClose);
}
else
{
adapter.SetItemImage(i, Resource.Drawable.LightOpen);
}
//}
//catch (Exception mye)
//{
// Console.WriteLine(mye.Message);
// continue;
//}
}
adapter.NotifyDataSetChanged();
}
单击 开始自动刷新
稍后
单击 停止自动刷新
单击 下箭头