Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> 【Android】17.4 Activity與IntentService的綁定,activity綁定service

【Android】17.4 Activity與IntentService的綁定,activity綁定service

編輯:關於android開發

【Android】17.4 Activity與IntentService的綁定,activity綁定service


分類: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模擬器中運行的效果。

 

三、主要實現步驟

1、添加Json引用

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

由於本例子實際並未使用它,所以不添加也可以。

具體添加辦法如下:鼠標右擊項目中的“引用”,然後選擇Systm.Json:

2、添加Internet訪問權限

股票一般都是通過Internet發布的,如果訪問股票的Web服務,還需要添加Internet訪問權限(如果已經添加過就不用添加了):

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

當然,由於這個例子中並沒有真正訪問Internet,不添加這個權限也可以。

3、添加ch1703_main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="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;
            }
        }
    }
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved