如何在Android Wear设备上运行Xamarin.Forms应用程序

时间:2015-04-17 06:52:10

标签: android xamarin wear-os xamarin.forms runtimeexception

如何在Android Wear设备上运行Xamarin.Forms.Platform.Android.FormsApplicationActivity?我班级的base.OnCreate(bundle)方法内的调用onCreate总是抛出一个RuntimeException“你不能在手表上使用不确定的进度”。

这是我的代码:

namespace Test
{
    [Activity (Label = "Temp.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            global::Xamarin.Forms.Forms.Init (this, bundle);

            LoadApplication (new App ());
        }
    }
}

App的实现应该无关紧要,因为超级onCreate的调用已经抛出了异常,而不是通过调用LoadApplication (new App ())来加载应用程序。但它是由Xamarin Mobile Application的项目向导生成的基本实现。

2 个答案:

答案 0 :(得分:3)

您不会在可穿戴设备上运行Xamarin.Forms应用程序。您需要在本机Xamarin.Android中创建一个新的Android Wear应用程序。可穿戴应用程序使用特殊主题,特殊控件,并具有特殊API。一个很好的样本是我如何使用Hanselman.Forms,这是一个Xamarin.Forms主要应用程序,但也绑定在Android Wear应用程序中:https://github.com/jamesmontemagno/Hanselman.Forms

答案 1 :(得分:3)

尽管James Montemagno的答案我发现可以在Xamarin Forms中同步数据。我使用Vincent Maverick的方法并将其合并到Xamarin Forms中。首先要注意安装正确的Android SDK(Android Wear Tutorial - A Comprehensive Introduction)。 假设您使用标准应用程序,建议在单独的Xamarin Forms Cross Platform应用程序中创建Wear应用程序。这是因为磨损尺寸与手机尺寸不同。

在Wear应用和手机应用程序中,右键单击Android项目的参考,然后选择MANAGE NUGET PACKAGES。浏览磨损并选择
 Xamarin.GooglePlayServices.Wearable Version 29.0.0(更高版本会出现问题)。

enter image description here

在两个应用程序中单击Android项目的属性。确保默认命名空间(应用程序选项卡)和包名称(Android清单选项卡)相同。另外,请确保包名称没有大写字母,这会导致将应用程序发布到Android商店时出现问题。 更改"使用Android版本进行编译"到" API Level 21(Xamarin.Android v5.0支持)。

enter image description here

在两个项目的Android MainActivity中添加使用

using Android.Gms.Wearable;
using Android.Gms.Common.Apis;
using Android.Support.V4.Content;

然后将两个应用程序的MainActivity更改为以下内容:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IDataApiDataListener, IMessageApiMessageListener
{
    private static GoogleApiClient client;
    const string _syncPath = "/MySyncPath/Data";
    static string device = "Watch";
    static string text= "";

    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());

        client = new GoogleApiClient.Builder(this)
              .AddApi(WearableClass.API)
              .Build();
        IntentFilter filter = new IntentFilter(Intent.ActionSend);
        MessageReciever receiver = new MessageReciever(this);
        LocalBroadcastManager.GetInstance(this).RegisterReceiver(receiver, filter);
    }

    internal class MessageReciever : BroadcastReceiver
    {
        MainActivity _main;
        public MessageReciever(MainActivity owner) { this._main = owner; }
        public override void OnReceive(Context context, Intent intent)
        {
            _main.ProcessMessage(intent);
        }

    }

    public void OnDataChanged(DataEventBuffer dataEvents)
    {
        var dataEvent = Enumerable.Range(0, dataEvents.Count)
                                  .Select(i => dataEvents.Get(i).JavaCast<IDataEvent>())
                                  .FirstOrDefault(x => x.Type == DataEvent.TypeChanged && x.DataItem.Uri.Path.Equals(_syncPath));
        if (dataEvent == null)
            return;
        //do stuffs here
    }

    public override void OnBackPressed()
    {
           base.OnBackPressed();
    }

    protected override void OnStart()
    {
        base.OnStart();
        Android.Util.Log.Info("WearIntegration", "Received Message");

        client.Connect();
    }

    public void OnConnected(Bundle p0)
    {
        WearableClass.DataApi.AddListener(client, this);
    }

    public void OnConnectionSuspended(int reason)
    {
        Android.Util.Log.Error("GMSonnection suspended " + reason, "");
        WearableClass.DataApi.RemoveListener(client, this);
    }

    public void OnConnectionFailed(Android.Gms.Common.ConnectionResult result)
    {
        Android.Util.Log.Error("GMSonnection failed " + result.ErrorCode, "");
    }


    protected override void OnStop()
    {
        base.OnStop();
        client.Disconnect();
    }

    public void OnMessageReceived(IMessageEvent messageEvent)
    {
        if (messageEvent.Path.Equals(_syncPath))
        {
            var msg = System.Text.Encoding.UTF8.GetString(messageEvent.GetData());

            this.RunOnUiThread(() =>
                Android.Widget.Toast.MakeText(this, msg, ToastLength.Long).Show());
        }
    }

    public void ProcessMessage(Intent intent) 
    {
        if (intent.GetStringExtra("Device") != device)
        {
            text = intent.GetStringExtra("WearMessage");
            //do stuffs here

        }
    }

    public void SendData() {
        try {
            var request = PutDataMapRequest.Create(_syncPath);
            var map = request.DataMap;
            map.PutString("Device", device);
            map.PutString("Message", "Xamarin Forms says Hello from Wearable!");
            map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);
            WearableClass.DataApi.PutDataItem(_client, request.AsPutDataRequest());
        }
        finally {
            _client.Disconnect();
        }

}

在您的手机应用程序中,将静态字符串设备更改为手机,并根据需要更改消息文本:

    static string device = "Phone";

            map.PutString("Message", "Xamarin Forms says Hello from Phone!");

然后将WearService类添加到您的Android项目中,添加添加到MAinActivity的相同用途,更改Wearservice,如下所示:

[Service]
[IntentFilter(new[] { "com.google.android.gms.wearable.BIND_LISTENER" })]
public class WearService : WearableListenerService
{
    const string _syncPath = "/KorfballTimer/Data";
    GoogleApiClient _client;

    public override void OnCreate()
    {
        base.OnCreate();
        _client = new GoogleApiClient.Builder(this.ApplicationContext)
                .AddApi(WearableClass.API)
                .Build();

        _client.Connect();

        Android.Util.Log.Info("WearIntegrationreated", "");
    }

    public override void OnDataChanged(DataEventBuffer dataEvents) 
    {
        var dataEvent = Enumerable.Range(0, dataEvents.Count)
                                  .Select(i => dataEvents.Get(i).JavaCast<IDataEvent)
                                  .FirstOrDefault(x => x.Type == DataEvent.TypeChanged && x.DataItem.Uri.Path.Equals(_syncPath));
        if (dataEvent == null)
            return;

        //get data from wearable
        var dataMapItem = DataMapItem.FromDataItem(dataEvent.DataItem);
        var map = dataMapItem.DataMap;
        string message = dataMapItem.DataMap.GetString("Message");

        Intent intent = new Intent();
        intent.SetAction(Intent.ActionSend);
        intent.PutExtra("WearMessage", message);
        intent.PutExtra("Device", map.GetString("Device"));
        LocalBroadcastManager.GetInstance(this).SendBroadcast(intent);
    }
}

最后,在元素:

下的AndroidManifest.xml中添加元数据
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

如果您不想在Wear应用程序中使用IOS和Windows项目,只需将其删除即可。现在,您可以像使用手机应用程序一样在Xamarin Forms中构建Wear应用程序。快乐的编码。