如何将Xamarin.Android 與Windows Azure做結合,将Android APP上的資料丢到雲端去儲存。
1. 在Windows Azure上建立一個Mobile Service
首先到Windows Azure上去建立一個Mobile Service。這邊我建立了一個for Android的Mobile Service。
2. 在Mobile Service上面新增一個item資料庫
2.1 接下來我們要在剛剛建立的Mobile Service上面建立一個儲存資料的Table。 這裡可以使用Windows Azure上的模闆,點選到Azure上的Android,選擇底下的 [CONNECT AN EXISTING ANDROIP APP]。
2.2 在展開的網頁裡面會看到一個選項,[Create Item table], 點這個綠色的按鈕Windows Azure會幫我們在雲端上面建立一個資料庫。到目前為止在Windows Azure上的準備已經完成了。
2.3 新增完成後,可以在Windows Azure上面看到我們新增出來的Table,這個Table裡面有兩個字段,分别是 id還有Text。
3. 下載下傳安裝Azure Mobile Service
在Xamarin網站上下載下傳MobileService元件,将檔案下載下傳到你的計算機端後,解開壓縮。,後續要在我們的Android項目中引用MobileService檔案裡面的
4. 撰寫程式将資料寫進item Table
4.1 開啟Visual Studio 2012,去新增一個Android專案。
4.2 把剛剛下載下傳MobileService元件裡面的Microsoft.WindowsAzure.MobileServices.Android.dll元件加入參考。
4.3 在專案裡點MainActivity.cs檔案兩下,開啟編輯畫面,這邊建立一個Item Class。這個是稍後要用來儲存檔案到Windows Azure的對應類别。
public class Item {
public int Id;
public String Text;
}
4.4 接着在OnCreate事件中,我們建立以下程式。
//MobileService主要是用來連接配接到你的Windows Azure。連接配接的url可以在Windows Azure上的
// [CONNECT AN EXISTING ANDROIP APP]頁面裡找到你的URL網址。
mClient = new MobileServiceClient(
"https://benlutodolistforandroid.azure-mobile.net/",
"KRyAYJbLgxMDaKHdLaeIh88"
);
//建立一個Item的對象實體,然後儲存你要儲存的資料到item對象的Text屬性。
Item item = new Item();
item.Text = "Awesome";
//呼叫mClient.GetTable方法來取得Table,并且指定型别為Item。接着同步資料到Windows Azure。
var test = mClient.GetTable<Item>();
test.InsertAsync (item);
5. 編譯執行程式。
因為我們把寫入Windows Azure的程式寫在Oncreate事件裡面,是以當這隻APP被加載執行後, 就會觸發同步資料庫的事件
6. 浏覽Windows Azure上的資料庫
可以看到資料已經被寫入到裡Mobile Service下的item Table。