经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
.NET平台下的Xamarin开发 - Android
来源:cnblogs  作者:Yanbo.Hu  时间:2020/11/9 15:13:09  对本文有异议

       对Android的应用开发,如果熟悉Java,那么Android studio或Eclipse将是不错的选择。而对熟悉.net平台开发人员,在强大的Visual Studio帮助下,开发Android应用不再是难题。本文基于Visual Studio 2017及以上的版本讨论,如果低于2017的版本,因为xamarin并未集成,需要单独安装,所以在搭建开发环境上会有些麻烦。

      本文假设你有一定的开发经验,对Android的有基础的了解。假如你还不熟悉,建议先从MSDN上的Hello, Android开始,将是不错的入门。

1. 开发环境搭建

 在Windows 10,仅需要做下面两个就足够了:

    a. 在Visual studio上开发,需要Mobile development with .NET组件,详细的过程可参考Installing Xamarin in Visual Studio。也可以通过Visual studio installer,修改已有的安装。在最小安装的情况下,对components的选择,需要注意开发不同Android版本的应用,其API Level也不一样,Android API levels详见MSDN。如果需要原生支持,那么NDK也需要一并安装。

  

    b. Android Emulator:在模拟器的选择上,这里推荐Genymotion,对个人是免费的,资源占用下,启动迅速,对调试、可操作性都非常便利。虽然在visual studio的Mobile development with .NET默认安装情况下,会有一个hardware accelerated emulator,但,这里非常不推荐。MSDN上Android Emulator Setup这篇文章提到的模拟器,在硬件不是特别强大的情况下,都不建议去尝试。

       Notes:如果硬件不够强大,vs自带的hardware accelerated emulator启动会非常慢,每次编译调试会很费时。在T480笔记本上(i5-7300U+16G+SSD),默认的模拟器j仅成功了几次,后来修改了程序,旋转了一次模拟器,再启动就卡在应用加载上,模拟器无法响应或者无法加载应用。因为这个,曾一度怀疑是不是程序那里修改错了或者开发环境哪里少了步骤而没有搭建完成,折腾了近一下午的时间。第二天,安装了Genymotion模拟器,一切都清爽了

  Gemymotion模拟器的安装步骤:

  • 从官网下载后(对首次下载,建议选择带有Virtualbox的版本),注册账号。因为在安装完成,启动该软件,仍然需要登录账号,才可以创建模拟器。在安装完成后,可以看到:

  • 启动Genymotion, 创建模拟器。如下图所示,可根据需要创建不同Android版本的模拟器:
      

      上面两步完成后,开发环境就搭建成功了。

      启动新建的Genymotion虚拟设备,打开Android project后,在visual studio的调试设备列表中,默认就是该模拟器,否则将是hardware accelerated emulator。

  

2. 应用程序

   这里会有些不同于MSDN上的Hello, Android,稍微有些复杂,将从Activity,View(axml),Intent相关点介绍。

   2.1 程序开发 - 应用程序结构及代码结构:

  

  •  Logon activity & logon view:登录相关,应用程序启动后,此为主activity启动 一个main activity。其对应的view放在axml文件中
  •  Main activity & view:登录后的相关操作,此处呈现简单的click计数器,并提供导航到history activity和返回logon的操作。其对应的view放在axml文件中
  •  History list activity:此activity继承自Built-in Control ListView, 不单独创建xml结构的view

   初步介绍程序结构后,接下来从创建该程序开始:

   A. 在visual studio中,新建一个Xamarin project

  

 

    B. 在接下来的向导中,选择空白模板。对最小Android版本,其字面直译,表示该应用程序运行所需的最低版本。根据开发环境搭建步骤a中所选择安装的API Level不同,该列表呈现的可选版本也不同。

  

   C. 完成后,可见到程序默认结构。在Resource/Layout目录下,Activity_main.axml为默认的启动的activity设图。这里,将其作为main activity的视图(非程序启动后的第一个页面)。为了保持一致,可将其重命名为其它试图的activity。为了简化,这里不做改名。

默认的布局结构为RelativeLayout, 这里将其修改为LinearLayout,并设置属性android:orientation="vertical"纵向线性布局结构。本axml使用嵌套LinearLayout布局,

     

完整的代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:layout_margin="5dip">
  7. <TextView
  8. android:id="@+id/form_title"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/logon_title_tip" />
  12. <LinearLayout
  13. android:id="@+id/layout_login_name"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content"
  16. android:layout_margin="5.0dip"
  17. android:layout_marginTop="10.0dip"
  18. android:orientation="horizontal">
  19. <TextView
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="@string/logon_usr" />
  23. <EditText
  24. android:id="@+id/txt_login_name"
  25. android:layout_width="fill_parent"
  26. android:layout_height="wrap_content"
  27. android:textSize="15.0sp" />
  28. </LinearLayout>
  29. <LinearLayout
  30. android:id="@+id/login_pwd_layout"
  31. android:layout_width="fill_parent"
  32. android:layout_height="wrap_content"
  33. android:layout_below="@id/layout_login_name"
  34. android:layout_centerHorizontal="true"
  35. android:layout_margin="5.0dip"
  36. android:orientation="horizontal">
  37. <TextView
  38. android:id="@+id/login_pass_edit"
  39. android:layout_width="wrap_content"
  40. android:layout_height="wrap_content"
  41. android:text="@string/logon_pwd"
  42. android:textSize="15.0sp" />
  43. <EditText
  44. android:id="@+id/txt_login_pwd"
  45. android:layout_width="fill_parent"
  46. android:layout_height="wrap_content"
  47. android:password="true"
  48. android:textSize="15.0sp" />
  49. </LinearLayout>
  50. <Button
  51. android:id="@+id/btn_login"
  52. android:layout_width="fill_parent"
  53. android:layout_height="wrap_content"
  54. android:layout_gravity="center"
  55. android:gravity="center"
  56. android:text="@string/logon_logonBtnText" />
  57. </LinearLayout>
View Code

   D. Logon对应的Activity, 其默认继承自AppCompatActivity,且其被ActivityAttribute修饰为MainLauncher = true。在Android程序中,并没有主程序的入口点,理论上,任何一个activity都可以被作为主入口。在xaml开发中,做了更为易于理解的标注( AppCompatActivity, MainLauncher = true)。完整的代码:

  1. [Activity(Label = "LogonActivity", MainLauncher = true)]
  2. public class LogonActivity : AppCompatActivity
  3. {
  4. protected override void OnCreate(Bundle savedInstanceState)
  5. {
  6. base.OnCreate(savedInstanceState);
  7. // Create your application here
  8. SetContentView(Resource.Layout.activity_logon);
  9. EditText usr = FindViewById<EditText>(Resource.Id.txt_login_name);
  10. usr.KeyPress += Usr_KeyPress;
  11. var logonBtn = FindViewById<Button>(Resource.Id.btn_login);
  12. logonBtn.Click += LogonBtn_Click;
  13. CreateNotificationChannel();
  14. }
  15. private void Usr_KeyPress(object sender, View.KeyEventArgs e)
  16. {
  17. e.Handled = false;
  18. if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
  19. {
  20. var msg = FindViewById<EditText>(Resource.Id.txt_login_name).Text;
  21. Toast.MakeText(this, msg, ToastLength.Short).Show();
  22. EditText pwdTxt = FindViewById<EditText>(Resource.Id.txt_login_pwd);
  23. pwdTxt.Text = msg;
  24. e.Handled = true;
  25. #region notification
  26.  
  27. var builder = new NotificationCompat.Builder(this, "location_notification")
  28. .SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
  29. //.SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
  30. .SetContentTitle("Button Clicked") // Set the title
  31. //.SetNumber(count) // Display the count in the Content Info
  32. .SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha) // This is the icon to display
  33. .SetContentText("只有图标、标题、内容:" + FindViewById<EditText>(Resource.Id.txt_login_name).Text); // the message to display.
  34. // Finally, publish the notification:
  35. var notificationManager = NotificationManagerCompat.From(this);
  36. notificationManager.Notify(1000, builder.Build());
  37. #endregion
  38. }
  39. }
  40. private void LogonBtn_Click(object sender, EventArgs e)
  41. {
  42. var intent = new Intent(this, typeof(MainActivity));
  43. intent.PutExtra("username", FindViewById<EditText>(Resource.Id.txt_login_name).Text);
  44. StartActivity(intent);
  45. }
  46. void CreateNotificationChannel()
  47. {
  48. //in case API 26 or above
  49. if (Build.VERSION.SdkInt < BuildVersionCodes.O) return;
  50. var channel = new NotificationChannel("location_notification", "Noti_name", NotificationImportance.Default)
  51. {
  52. Description = "Hello description"
  53. };
  54. var notificationManager = (NotificationManager)GetSystemService(NotificationService);
  55. notificationManager.CreateNotificationChannel(channel);
  56. }
  57. }
LogonActivity

    这里,User name的输入框中,增加了按键press down事件,用回车键按下后,触发Toast及通知栏展示(此处仅为演示用)。对通知栏,在API 26以后,需要首先注册Channel。

  1. var channel = new NotificationChannel("location_notification", "Noti_name", NotificationImportance.Default)
  2. {
  3. Description = "Hello description"
  4. };
  5. var notificationManager =(NotificationManager)GetSystemService(NotificationService);
  6. notificationManager.CreateNotificationChannel(channel);
Channel Registration - API 26

   E. 输入user name后,点击Logon,跳转到Main activity页面。此页面,Enter code默认呈现user name。在Click me按钮点击后,内部计数器增加,消息呈现在Enter code并记录到Intent中。

      

    axml完整代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical" >
  8. <TextView
  9. android:text="Enter code"
  10. android:textAppearance="?android:attr/textAppearanceLarge"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:minWidth="25px"
  14. android:minHeight="25px"
  15. android:id="@+id/textView1" />
  16. <EditText
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:id="@+id/editText1" />
  20. <Button
  21. android:text="Click ME"
  22. android:layout_width="match_parent"
  23. android:layout_height="wrap_content"
  24. android:id="@+id/button1" />
  25. <Button
  26. android:text="@string/callhistory"
  27. android:layout_width="match_parent"
  28. android:layout_height="wrap_content"
  29. android:id="@+id/callhistoryBtn"
  30. android:enabled="false"
  31. />
  32. <Button
  33. android:text="Logout"
  34. android:layout_width="match_parent"
  35. android:layout_height="wrap_content"
  36. android:id="@+id/switchBtn" />
  37. </LinearLayout>
Main_View axml

   F. Main Activity, 视图对应的代码实现

  1. [Activity(Label = "@string/app_name", Theme = "@style/AppTheme")]
  2. public class MainActivity:Activity
  3. {
  4. static readonly List<string> phoneNumbers = new List<string>();
  5. protected override void OnCreate(Bundle savedInstanceState)
  6. {
  7. base.OnCreate(savedInstanceState);
  8. // Set our view from the "main" layout resource
  9. SetContentView(Resource.Layout.activity_main);
  10. Button btn = FindViewById<Button>(Resource.Id.button1);
  11. btn.Click += Btn_Click;
  12. Button callhis = FindViewById<Button>(Resource.Id.callhistoryBtn);
  13. callhis.Click += Callhis_Click;
  14. FindViewById<Button>(Resource.Id.switchBtn).Click+= (obj, e)=> {
  15. //SetContentView(Resource.Layout.activity_logon);
  16. StartActivity(typeof(LogonActivity));
  17. };
  18. //set user name
  19. EditText usr = FindViewById<EditText>(Resource.Id.editText1);
  20. usr.Text = Intent.Extras?.Get("username")?.ToString();
  21. }
  22. private void Callhis_Click(object sender, System.EventArgs e)
  23. {
  24. var intent = new Intent(this, typeof(CallHistoryActivity));
  25. intent.PutStringArrayListExtra("phone_numbers", phoneNumbers);
  26. StartActivity(intent);
  27. }
  28. private int counter = 1;
  29. private void Btn_Click(object sender, System.EventArgs e)
  30. {
  31. var cl = FindViewById<EditText>(Resource.Id.editText1);
  32. cl.Text = $"your counter is {counter++}";
  33. phoneNumbers.Add(cl.Text);
  34. FindViewById<Button>(Resource.Id.callhistoryBtn).Enabled = true;
  35. }
  36. }
Main Actitity

 对该页面,当点击"Click ME"按钮后,计数器自增,Call History的按钮可用。当点击Call History,页面跳转到view list页面,呈现计数器Counter的变化历史。

    

   G. 在Call History,该activity继承自ListView,数据源为计数器Counter的变化历史记录。详细的代码为:

  1. [Activity(Label = "@string/callhistory")]
  2. public class CallHistoryActivity : ListActivity
  3. {
  4. protected override void OnCreate(Bundle savedInstanceState)
  5. {
  6. base.OnCreate(savedInstanceState);
  7. // Create your application here
  8. var phoneNumbers = Intent.Extras.GetStringArrayList("phone_numbers") ?? new string[0];
  9. this.ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, phoneNumbers);
  10. }
  11. }
Call History Activity

 除了这里演示的ListView, 还有LinearLayoutRelativeLayout , TableLayout , RecyclerViewGridViewGridLayoutTabbed Layouts多种布局构建页面。

   2.2 程序部署

   和传统的windows程序有些不太一样(DEBUG/RELEASE模式下,直接编译后得到的为dll而非.apk文件),在程序需要发布的时候,在project右键或者Tools -> Arhive Manager,可以看到已经创建的Archive或者新的Archive。

   NOTE:右键菜单中的Deploy按钮,对没有多少经验的开发者有些不太友好,在模拟器环境中,通常会报不支持CPU型号的错误。这是由于deploy会依赖Simulation列表设备的选择。如果是Gemymotion模拟器,基本会失败。如果连接的硬件(usb调试模式下的硬件),会直接部署到对应的设备上

 

 在Archive Manger中,选择相应的Archive,将其分发到本地或者应用市场:

       

对Ad Hoc选项,可以创建/选择已有的签名,对所要发布的程序进行签名。

3. 所涉及的要点

    3.1 Activity & axml

    这里更多的是从设计的角度考虑,Activity和axml以一对一的形式构建。单从程序实现角度,一个activity可使用多个axml文件以构建不同业务场景的试图(同一个时刻,content view只会有一个),这种情况下多个axml的事件或业务,将只能在对应的那个Activity中实现(调用SetContentView的地方)。在设计上,这种很难理解维护,即使以partial这种投机的方式达到可维护性,对OO的设计模式也是一种破坏(或美其名曰反设计模式)。

    3.2 Activity lifecycle

    在Android应用程序中(不像传统的桌面/web程序,有指定的程序入口点Main),任何activity都可以成为入口点。在vs中,Xamarin.Android很好的照顾了刚入门的开发人员,将activity及对应的axml文件直接以main关键字命名。借用MSDN上的这幅图,形象生动说明整个actity的生命周期。

      

    对各个关键点,提供了相应的重写方法。如默认的OnCreate, 执行activity启动以初始化。需要注意,该方法是在OnStart之后执行。

    3.3 Activity之间的数据传递

  对于不同Activity之间的数据传递,Intent类提供了多种方式。对简单数据类型,调用内置的PutExtra不会有任何问题。对实例对象或复杂对象,需要将其序列化,在取的时候,反序列化即可。

     而对于同一个Activity不同的活动期间,则无需这么复杂,通过Bundle即可。如OnCreate, OnPause等可重写的方法,通过参数Bundle即可完成生命周期内的数据传递。在实际应用中,OnSaveInstanceState在activity被销毁时保存相应数据或试图状态,在恢复的时候,OnRestoreInstanceState是一种选择,但更多的时候, 通过OnCreate已经足够。

  1. protected override void OnSaveInstanceState (Bundle outState)
  2. {
  3. outState.PutString("UsrCfg", MyStringData);
  4. base.OnSaveInstanceState (outState);
  5. }
OnSaveInstanceState

    3.4 Localization

     如演示程序所示,如果应用需要多语言支持,对本地化策略:

  1. android:text="@string/callhistory"

    以@string或者类似值,将以字面直译的方式处理,涉及的resource在Resources/Values/xx.axml文件中。比如上述代码所演示的,具体的resource资源在Resources/Values/string.axml中。

 

对熟悉.NET平台开发,又想开发Android应用的朋友,希望这篇文章对你有所帮助。

另外,在写这篇文章2天前,我也没有相关的Android开发经验。因为基于项目要求,需要在PDA设备开发相应的程序,于是便有了此文。对于想要了解更详细的知识点,可详见Application Fundamentals

原文链接:http://www.cnblogs.com/huankfy/p/13893738.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号