C#是一种优秀的编程语言,语法之优雅,代码之简洁使得众多软粉多年来对她不离不弃。 但是如何将C#程序部署到Linux, Android等平台,这当然是得依靠众所周知的Mono。

本文Demo程序比较简单,实现了通过HttpRequest 查询天气,最终效果如下:

1. 下载并安装 Xamarin
http://xamarin.com/download
注册Xamarin账号, Role 选择 Academic(学者)即可;
运行 XamarinInstaller.exe在线安装程序,需要一个良好的网络环境,所需的安装程序体积大约 1.44G ,安装过程一路默认即可。

2.破解
网上找的破解:http://download.csdn.net/detail/flydoos/5820325
解压缩后,将文件覆盖到指定位置即可。

3.开发
开发Mono Android程序可以使用Xamarin Studio,也可以使用Visual Studio,建议使用VS,因为Xamarin对
VS提供有强大的插件 再配合VS本身强大的功能,会使开发工作如鱼得水,另外Xamarin Studio目前还不够完善,比如添加引用 之后,需要重
启。

a.创建 Android项目 ,如下图:

b.项目文件结构,如下图:

c.页面文件

XML/HTML code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1"
        android:layout_marginBottom="5dip"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:layout_marginTop="5dip">
        <TextView
            android:id="@+id/LblCity"
            android:text="@string/PressCity"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
        <EditText
            android:id="@+id/TxtWeather"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:lines="1" />
    </LinearLayout>

我们可以看出,所有的控件均放在LinearLayout中,这是一个部局控件,LinearLayout又分为水平布局和垂直布局,比如一行中需要放置多个控件,这时候就需要用到水平布局。
d. cs文件
    我们所熟悉的C#,将在这里大展拳脚,一切看上去都是那么亲切。

C# code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
 
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.IO;
 
 
namespace AndroidHelloWorld
{
    [Activity(Label = "EasyWeather", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
 
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
 
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            EditText txtWeather = FindViewById<EditText>(Resource.Id.TxtWeather);
             
            // 天气查询结果
            TextView lblCity = FindViewById<TextView>(Resource.Id.LblCityRst);                  // 城市 
            TextView lblCurTmp = FindViewById<TextView>(Resource.Id.LabCurTempRst);             // 当前温度  
            TextView lblWeather = FindViewById<TextView>(Resource.Id.LabWeatherRst);            // 天气
            TextView lblRange = FindViewById<TextView>(Resource.Id.LabRangeRst);                // 范围
            TextView lblUptTime = FindViewById<TextView>(Resource.Id.LabUptTimeRst);            // 更新时间
 
 
            button.Click += (sender, e) => {
                HttpHelper helper = new HttpHelper();
 
                string sUrl = String.Format(@"http://cgi.appx.qq.com/cgi/qqweb/weather/wth/weather.do?
                                            retype=1&city={0}&t={1}"
                                            Uri.EscapeDataString(txtWeather.Text), 
                                            DateTime.Now.ToFileTime().ToString());
 
                try
                {
                    var v = helper.HttpGetRequest(sUrl, null, 10000, null);
                    var rst = new StreamReader(v.GetResponseStream(), System.Text.Encoding.GetEncoding(v.CharacterSet));
 
 
                    var vWeather = Newtonsoft.Json.JsonConvert.DeserializeObject<EtWeather>(rst.ReadToEnd());
                    //var vWeather = jss.Deserialize<EtWeather>(rst.ReadToEnd());
 
                    lblCity.Text = vWeather.city;
                    lblCurTmp.Text = vWeather.now_temperature;
                    lblWeather.Text = vWeather.now_pic_name;
                    lblRange.Text = vWeather.temperature_range;
                    lblUptTime.Text = vWeather.update_time;
                }
                catch (Exception Err)
                {
                    var builder = new AlertDialog.Builder(this);
                    builder.SetMessage(Err.Message);
                    builder.SetCancelable(false);
                    builder.SetPositiveButton("OK"delegate { });
                    var dialog = builder.Create();
                    dialog.Show();
 
                }
                 
            };
        }
    }
}

需要注意的是,我们怎样使用前台页面所定义的控件?目前我知道的这种方法,比较繁琐,不知道是否还有更直接一点的方式:

C# code?
1
TextView lblCity = FindViewById<TextView>(Resource.Id.LblCityRst);

然后编写HttpHelper类:

C# code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class HttpHelper
{
private readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
 
public HttpWebResponse HttpGetRequest(string url, string referer, int? timeout, CookieCollection cookies)
{
    HttpWebRequest request = null;  
 
    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    {
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        request = WebRequest.Create(url) as HttpWebRequest;
        request.ProtocolVersion = HttpVersion.Version10;
    }
    else
        request = WebRequest.Create(url) as HttpWebRequest;
 
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";
    request.UserAgent = DefaultUserAgent;
    request.CookieContainer = new System.Net.CookieContainer();
 
    if (!string.IsNullOrEmpty(referer))
        request.Referer = referer;
 
    if (timeout.HasValue)
        request.Timeout = timeout.Value;
    else
        request.Timeout = 25000;
 
    if (cookies != null)
    {
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(cookies);
    }
 
    return request.GetResponse() as HttpWebResponse;  
}
 
private  bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
    return true;
}

接下来就是如何将Web Api返回的Json还原为对象,这里需要用到 Newtonsoft.Json,添加引用的方法如下:  1,右击解
决方案中的Components文件夹,选择view datails, 2.找到 jons.Net ,3.点击 Add to Projct(需要账
号验证,使用注册的学者账号即可)。

d. 调试及部署
    按F5运行, 第一次需要创建一个Android模拟器,这里只需要稍微注意一下你所选择Android系统版本,推荐使用2.2, 因为Mono For Android项目默认情况下使用的是2.2 的API。 

Mono框架没有JIT(个人对这个没有研究,可能表达得不准确,欢迎拍砖),因此在断点调试的时候你会发现与平时调试C#略有不同,无法拖动断点,无法修改代码。
    关于部署,必须使用Release进行编译,将并生成的APK文件传到手机安装后即可运行,UI与速度与Java开发的应用无差。

Mono for Android, Android开发我是新手中的新手,向大家学习,让C# running anywhere.

C#程序部署到Android的更多相关文章

  1. .net程序部署(mono方式)

    某一次 我同事用了这个词 ,说这样才显得够专业 擦.把某某项目 部署到服务器上 .擦 不就是拷个文件过去运行么.月亮 还是绵羊  我搞不清楚了 咱英文不好,绵羊叫的声音?.你就叫我山寨程序猿 随意 一 ...

  2. deployment与Web应用程序部署

    定义用于支持 Web 应用程序部署的配置设置. <deployment retail="true|false" /> retail属性:设置一个值,该值指定是否以发布模 ...

  3. 使用VS Code 开发.NET Core 应用程序 部署到Linux 跨平台

    使用VS Code 开发.NET Core 应用程序 部署到Linux 跨平台. 前面讲解了VSCode开发调试 .NET Core.都只是在windows下运行. .NET Core真正的核心是跨平 ...

  4. IIS安装与MVC程序部署

    最近在做访客系统,虽然说不是什么多大的项目,但麻雀虽小五脏俱全,使用EF Code First+Mysql+Frozenui响应式布局,感觉通过这个项目学到好多东西,Mysql的使用.EF映射Mysq ...

  5. SNF开发平台WinForm之八-自动升级程序部署使用说明-SNF快速开发平台3.3-Spring.Net.Framework

    9.1运行效果: 9.2开发实现: 1.首先配置服务器端,把“SNFAutoUpdate2.0\服务器端部署“目录按网站程序进行发布到IIS服务器上. 2.粘贴语句,生成程序 需要调用的应用程序的Lo ...

  6. [翻译][MVC 5 + EF 6] 5:Code First数据库迁移与程序部署

    原文:Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application 1.启用 ...

  7. 十大免费移动程序测试框架(Android/iOS)

    十大免费移动程序测试框架(Android/iOS) 概述:本文将介绍10款免费移动程序测试框架,帮助开发人员简化测试流程,一起来看看吧. Bug是移动开发者最头痛的一大问题.不同于Web应用程序开发, ...

  8. (12)Visual Studio 2012如何透过电子邮件部署Xamarin.Android App

    原文 Visual Studio 2012如何透过电子邮件部署Xamarin.Android App Android App在部署到实机的时候不像iOS的App限制你一定要使用向Apple申请的开发者 ...

  9. 小程序员在android移动应用上的赚钱经历

    先说说我自己吧,二线城市(以外包为主)的小程序员,工作多年了,月收入5-6K.主要从事asp.net web网站开发,java,c++,php,ruby都懂一些,属于那种对问题不求甚解型,爱好电脑游戏 ...

随机推荐

  1. C# 内存法图像处理

    内存法通过把图像储存在内存中进行处理,效率大大高于GetPixel方法,安全性高于指针法. 笔者当初写图像处理的时候发现网上多是用GetPixel方法实现,提到内存法的时候也没有具体实现,所以笔者在这 ...

  2. linux系统防火墙对访问服务器的影响

    一.刚部署好的linux服务器默认开启了防火墙,这时假如你在该服务器装一个tomcat并启动,在别的机器访问该tomcat是不成功的.需要关闭服务器防火墙才可以 二.service iptables ...

  3. ZOJ 2702 Unrhymable Rhymes(DP)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1702 题目大意:给定有很多数字组成的诗,譬如 “AABB”, “AB ...

  4. 对C++ Primer的10.3.9单词转换的思考

    这篇代码有几个知识点可以复习一下,而且小白学到了新知识o(╯□╰)o #include <iostream> #include <string> #include <ma ...

  5. Google C++编程风格指南

    作者:Hawstein 出处:http://hawstein.com/posts/google-cpp-style-guide.html 前言 越来越发现一致的编程风格的重要性,于是把Google的C ...

  6. Java编写的C语言词法分析器

    Java编写的C语言词法分析器 这是java编写的C语言词法分析器,我也是参考很多代码,然后核心代码整理起来,放在QQ空间和博客上,目的是互相学习借鉴,希望可以得到高手改进.这个词法分析器实现的功能有 ...

  7. 字符串匹配算法——KMP、BM、Sunday

    KMP算法 KMP算法主要包括两个过程,一个是针对子串生成相应的“索引表”,用来保存部分匹配值,第二个步骤是子串匹配. 部分匹配值是指字符串的“前缀”和“后缀”的最长的共有元素的长度.以“ABCDAB ...

  8. GitHub命令精简教程

    Github其实也可以作为文件分享的地方,但是免费空间只有300M,所以不能存放大文件,否则可以成为一个分享资源的下载站,而且非常方便. 常用命令: git add .   //添加所有的文件到索引 ...

  9. ASP.net+MVC--2

    1.ASP.NET MVC控制器 1)在Controllers文件夹下新建控制类 public class HelloWorld2Controller : Controller { public st ...

  10. css3怎么隐藏dom:4种方法

    1.display:none; 2.position:absolute; left:-99999px; 3.visibility:hidden; 4.opacity:0;