Xamarin.Forms入門中~UWPアプリのライブタイルの置き換え①~

Posted by 技術ブログ by Strawhat.net on Thursday, December 1, 2016

TOC

Windows 10 UWPアプリのタイル通知を、Androidではウィジェットに置き換える方法を調べてたので、そのメモ。

XamarinでのAndroidウィジェット作成

作成方法

調べた範囲では、プラットフォーム固有機能のAndroidウィジェットは Xamarin.Formsで作成できなくて、公式サンプルのSimple Widgetのように、Xamarin.Androidで作成できる模様。

サンプルの構成

重要なファイルは以下の模様。

  • Resources/xml/widget_word.xml

ウィジェットの設定をするファイル。更新間隔はandroid:updatePeriodMillisで指定する。

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dip"
    android:minHeight="72dip"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/widget_message" />
  • Resources/layout/widget_word.xml

ウィジェットのレイアウトを定義するファイル。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    style="@style/WidgetBackground">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:src="@drawable/star_logo" />
   ...
</RelativeLayout>
  • WordWidget.cs

Android.Appwidget.AppWidgetProviderを継承したクラスで、更新時に呼ばれるOnUpdateを定義。更新処理はAndroid.App.Serviceを継承したUpdateServiceで実装している。

using System;
using Android.App;
using Android.Appwidget;
using Android.Content;

namespace SimpleWidget
{
	[BroadcastReceiver (Label = "@string/widget_name")]
	[IntentFilter (new string [] { "android.appwidget.action.APPWIDGET_UPDATE" })]
	[MetaData ("android.appwidget.provider", Resource = "@xml/widget_word")]
	public class WordWidget : AppWidgetProvider
	{
		public override void OnUpdate (Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
		{
			// To prevent any ANR timeouts, we perform the update in a service
			context.StartService (new Intent (context, typeof (UpdateService)));
		}
	}
}
  • UpdateService.cs

Android.App.Serviceを継承している。OnStartで更新処理を実装。

20161201072941png

Xamarin.Formsとの共存

新しいプロジェクトの追加>Visual C#>Windowsから"クラスライブラリ(iOS、Android、Windowsのポータブル)“を選択して追加したPCLを、Xamarin.Androidから参照して利用できるので、Xamarin.Formsで作成するアプリ本体とXamarin.Androidのウィジェットで共通利用するライブラリの実装は問題なさそう。

20161130073630png

詳しい検証は週末にコードを書いて検証してみます。

データの更新方法

Resources/xml/widget_word.xmlで指定した時間間隔で定期的に呼ばれてウィジェットを更新するのですが、UWPのライブタイルのようにアプリからデータを更新したいのですが、それは調査中です。

Androidアプリの一般的な話になると思うので、程なく情報を見つけられそうです。