星空网 > 软件开发 > 操作系统

【Android】17.4 Activity与IntentService的绑定

分类:C#、Android、VS2015;

创建日期:2016-03-03

一、简介

本示例通过AlarmManager类以固定的时间间隔调用服务(每隔2秒更新一次随机生成的股票数据)。如果将此示例的代码改为定期调用一次Web服务,就能轻松实现股票在线更新的功能。

二、示例3运行截图

本示例在Android 4.4.2(API 19)中运行正常(右侧屏幕中的数据会自动每2秒更新一次),但在Android 6.0(API 23)模拟器中AlarmManager不起作用,原因未知,所以这里截取的是在Android 4.4.2模拟器中运行的效果。

【Android】17.4 Activity与IntentService的绑定  【Android】17.4 Activity与IntentService的绑定

三、主要实现步骤

1、添加Json引用

有些股票数据是以JSON格式提供的,如果希望读取JSON格式的数据,需要添加Json引用。

由于本例子实际并未使用它,所以不添加也可以。

具体添加办法如下:鼠标右击项目中的“引用”,然后选择Systm.Json:

【Android】17.4 Activity与IntentService的绑定

2、添加Internet访问权限

股票一般都是通过Internet发布的,如果访问股票的Web服务,还需要添加Internet访问权限(如果已经添加过就不用添加了):

<uses-permission android:name="android.permission.INTE.NET" />

当然,由于这个例子中并没有真正访问Internet,不添加这个权限也可以。

3、添加ch1703_main.<??><TextView ="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="15dp" android:text="test" />

4、添加ch1703SockService.cs

using System;using System.Collections.Generic;using Android.App;using Android.Content;using Android.OS;namespace MyDemos.SrcDemos{  [Service]  [IntentFilter(new string[] { StocksUpdatedAction })]  public class ch1703StockService : IntentService  {    IBinder binder;    public List<Stock> Stocks { get; private set; }    public const string StocksUpdatedAction = "StocksUpdated";    List<string> stockSymbols = new List<string>() { "联动A股", "深深B股", "宇平A股", "塔塔B股", "乖乖A股", "果果C股" };    Random r = new Random();    protected override void OnHandleIntent(Intent intent)    {      UpdateStocks();      var stocksIntent = new Intent(StocksUpdatedAction);      SendOrderedBroadcast(stocksIntent, null);    }    public override IBinder OnBind(Intent intent)    {      binder = new StockServiceBinder(this);      return binder;    }    //此处调用股票的Web服务返回结果,为简化起见,这里用随机数直接返回了模拟的结果    private void UpdateStocks()    {      Stocks = new List<Stock>();      for (int i = 0; i < stockSymbols.Count; i++)      {        Stocks.Add(new Stock() { Symbol = stockSymbols[i], LastPrice = r.Next(10, 151) });      }    }  }  public class StockServiceBinder : Binder  {    public ch1703StockService service { get; private set; }    public StockServiceBinder(ch1703StockService service)    {      this.service = service;    }  }  public class Stock  {    public string Symbol { get; set; }    public float LastPrice { get; set; }    public override string ToString()    {      return string.Format("[Stock: Symbol={0}, LastPrice={1}]", Symbol, LastPrice);    }  }}

5、添加ch1703MainActivity.cs

注意该类继承自ListActivity。

using Android.App;using Android.Content;using Android.OS;using Android.Widget;namespace MyDemos.SrcDemos{  [Activity(Label = "【例17-3】绑定到IntentService")]  public class ch1703MainActivity : ListActivity  {    bool isBound = false;    StockServiceBinder binder;    StockServiceConnection stockServiceConnection;    StockReceiver stockReceiver;    Intent stockServiceIntent;    protected override void OnCreate(Bundle savedInstanceState)    {      base.OnCreate(savedInstanceState);      stockReceiver = new StockReceiver(this);      stockServiceIntent = new Intent(ch1703StockService.StocksUpdatedAction);      stockServiceConnection = new StockServiceConnection(this);      BindService(stockServiceIntent, stockServiceConnection, Bind.AutoCreate);      var intentFilter = new IntentFilter();      intentFilter.AddAction(ch1703StockService.StocksUpdatedAction);      intentFilter.Priority = (int)IntentFilterPriority.HighPriority;      RegisterReceiver(stockReceiver, intentFilter);      var alarm = (AlarmManager)GetSystemService(AlarmService);      var a = PendingIntent.GetService(        this, 0, stockServiceIntent, PendingIntentFlags.UpdateCurrent);      //每2秒更新一次      alarm.SetRepeating(AlarmType.Rtc, 0, 2000, a);    }    protected override void OnDestroy()    {      if (isBound == true)      {        UnbindService(stockServiceConnection);        isBound = false;      }      UnregisterReceiver(stockReceiver);      base.OnDestroy();    }    private void UpdateStocks()    {      if (isBound)      {        var stocks = binder.service.Stocks;        if (stocks != null)        {          ListAdapter = new ArrayAdapter<Stock>(this,            Resource.Layout.ch1703_main, stocks);        }      }    }    private class StockReceiver : BroadcastReceiver    {      ch1703MainActivity activity;      public StockReceiver(ch1703MainActivity activity)      {        this.activity = activity;      }      public override void OnReceive(Context context, Intent intent)      {        activity.UpdateStocks();      }    }    private class StockServiceConnection : Java.Lang.Object, IServiceConnection    {      ch1703MainActivity activity;      public StockServiceConnection(ch1703MainActivity activity)      {        this.activity = activity;      }      public void OnServiceConnected(ComponentName name, IBinder service)      {        var stockServiceBinder = service as StockServiceBinder;        if (stockServiceBinder != null)        {          var binder = (StockServiceBinder)service;          activity.binder = binder;          activity.isBound = true;        }      }      public void OnServiceDisconnected(ComponentName name)      {        activity.isBound = false;      }    }  }}




原标题:【Android】17.4 Activity与IntentService的绑定

关键词:Android

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

进口跨境电商有哪些:https://www.goluckyvip.com/tag/34815.html
进口跨境电商怎么做:https://www.goluckyvip.com/tag/34816.html
进口跨境电子商务:https://www.goluckyvip.com/tag/34817.html
进口奶粉:https://www.goluckyvip.com/tag/34818.html
进口配额:https://www.goluckyvip.com/tag/34819.html
进口清关空运:https://www.goluckyvip.com/tag/34820.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流