在Android中使用OSGi框架(Apache Felix)

本文描述了如何在Android中使用Apache Felix

Dalvik VM

Android允许开发者使用Java开发应用,但出于某些原因,代码实际是运行在名为Dalvik的一个针对移动设备平台的虚拟机上,而不是标准的Java虚拟机。Dalvik并不使用标准的Java字节码格式,而是使用Android SDK中的一个工具dx将由Java编译出来的类文件转换为另外一种类文件格式(.dex格式)。这个转换是在编译期完成的。

准备Bundles

虽然Felix从1.0.3开始内置了Android的支持,但是想要成功的让它跑起来还是需要费点力气。我们仍然需要安装Android SDK,并且PATH环境变量中包含Android SDK的工具目录<android_SDK_HOME>/tools

第一步: 每一个用到的Jar文件,无论是Felix库还是你自己写的Bundle,都需要包含对应的DEX。也就说,需要为jar文件创建对应的dex文件:

dx --dex --output=classes.dex JAR_file.jar

然后将这个dex文件加入到jar文件中:

aapt add JAR_file.jar classes.dex

第二步: 将处理过的jar文件传到模拟器(或真机)中:

adb push JAR_file.jar path_emulator/JAR_file.jar

第三步: 以演示代码为例,准备Felix的jar文件和Bundle的jar文件:

目录结构

osgi-android: /
\- bin
\- bundle
\- conf
\- felix.sh

准备Felix jar文件

export PATH=<path-to-android>/tools:$PATH
cd bin
dx --dex --output=classes.dex felix.jar
aapt add felix.jar classes.dex

准备bundle的jar文件

cd bundle
dx --dex --output=classes.dex     org.apache.felix.shell-1.0.0.jar
aapt add org.apache.felix.shell-1.0.0.jar classes.dex
dx --dex --output=classes.dex org.apache.felix.shell.tui-1.0.0.jar
aapt add org.apache.felix.shell.tui-1.0.0.jar classes.dex
dx --dex --output=classes.dex EnglishDictionary.jar
aapt add EnglishDictionary.jar classes.dex
dx --dex --output=classes.dex FrenchDictionary.jar
aapt add FrenchDictionary.jar classes.dex
dx --dex --output=classes.dex SpellChecker.jar
aapt add SpellChecker.jar classes.dex

复制到模拟器中

cd osgi-android
find * -type f -exec adb push {} /data/felix/{} \;

启动Felix

完成上面的步骤之后,现在可以准备在Android上启动Felix和Bundle了

adb shell
cd /data/felix
sh felix.sh

felix.sh是一个shel脚本,用于启动Felix main class。

/system/bin/dalvikvm -Xbootclasspath:/system/framework/core.jar \

-classpath bin/felix.jar org.apache.felix.main.Main

如果一切顺利,现在你应该能看到Felix的命令行shell了。输入help可以看到命令说明。

现在可以安装EnglishDictionary,FrenchDictionary和SpellChecker来试试看Felix是否工作正常。这里有几个Apache Felix的示例:Apache Felix 教程例子2Apache Felix 教程例子2bApache Felix 教程例子5

  • EnglishDictionary - 提供一个字典服务,支持下面几个词"welcome", "to", "the", "osgi", "tutorial"
  • FrenchDictionary - 提供一个字典服务,支持下面几个词"bienvenue", "au", "tutoriel", "osgi"
  • SpellChecker - 提供一个拼写检查服务,可以检查第一个英文此单的几个单词

在Felix Shell中启动Bundle

start file:bundle/EnglishDictionary.jar
start file:bundle/FrenchDictionary.jar
start file:bundle/SpellChecker.jar

嵌入Felix

Apache Felix也可以被集成到Android的应用中。只需要在Activity的onCreate中嵌入Felix,然后用上面的办法启动bundle即可。

下载

上面的演示代码在此下载

via source

统一业务模型(UBM) in ERP5

from http://www.erp5.org/UnifiedBusinessModel

什么是统一业务模型

统一业务模型(Unified Busines Model - UBM)是ERP5系统采用的一个抽象业务模型,也是其精华所在。ERP5的作者Jean-Paul Smets在建立ERP5的一个版本的时候提出了这个创新,并且将这个模型应用到了基于ERP5开发的所有应用中。 由于这个模型是如此的高效和有价值,ERP5的名字也是由此而来,意思是仅通过UBM中的5个概念建立的ERP系统,因此称之为ERP5。

统一业务模型中的五个概念是什么

UBM包含5个概念,分别是节点(Node)、资源(Resource)、迁移(Movement)、物品(Item)和路径(Path)。

节点(Node)表示一个业务流程涉及到的一个关键点,例如一个人、一个组织、一个仓库、一个银行账号等等。这个概念与在图论和数学语言中的"节点"的概念类似。

资源(Resource)表示在业务流程中节点之间流通的一种有形或无形的东西。例如,资源可能是产品、原始材料、服务、现金等等。

迁移(Movement)描述了在节点之间的有关资源的变迁。类似图论中"有向边"的概念。它包含订购、发货、财务结算、付款、生产等等。

物品(Item)的概念使得资源可跟踪。这个概念类似于在面向对象编程中类和实例的关系,如果资源(Resource)对应为"类",那么物品(Item)对应于"实例"。物品可以表示一个条形码、RFID、某种订阅或者一张票据。

路径(Path)表示一种可能的迁移(Movement),在定义交易条件、供应条件、付款模式等时很有用,并且可以为业务逻辑、供应链、定价等提供支持。

例子

提供几个例子可以帮助你更好的理解这个模型。

例一: 假设A公司希望卖给B公司一批照相机,一旦双方达成了交易,A公司会发给B公司10个照相机,每个单价$100. 在这里场景中,A公司和B公司是节点(Node)。商品(照相机)是一种资源。销售本身(订购10个照相机总价$1000)是一个迁移(Movement)。如果这个条件(例如单价)双方都认可,这个条件就是一个路径(Path)。如果A公司希望跟踪照相机,可以在每个照相机上贴一个条形码,这样就产生了10个物品(Item)。

例二: 假设A公司希望对来自B公司的电汇信息记账。B公司发给A公司$1000的应收账款。 在这个场景中,应收账款账户和银行账户是节点(Node)——物理意义上的,A公司和B公司也是节点(Node)——逻辑意义上的。转账是一个迁移(Movement),钱是资源(Resource)。物品和路径在这里没有用到。

例三: 假设A公司希望在工厂中使用零件制造出10个照相机。 在这个场景中,工厂是一个节点(Node),照相机和零件是资源(Resource)。生产由两个迁移(Movement)组成,一个是消耗零件,一个是制造出照相机产品。为了跟踪产品,A公司可以为每个照相机和零件都打上标签,它们就成为了物品(Item)。由零件到产品的转换由路径(Path)描述。

ERP5中如何应用统一业务模型

UBM统一业务模型完全集成在ERP5的实现中。ERP5中的所有文档都基于该模型设计,ERP5中的所有工具也都采用该模型统一实现不同的业务活动,例如交易、生产、客户关系管理、财务和项目管理。 这使得我们可以基于ERP5快速开发新的应用,同时降低维护成本。因为所有的数据都采用统一的设计架构,因此代码量也大幅度的减少。

星际争霸2的大学专业?

不可否认,暴雪的星际争霸2可能是有史以来最流行的即时战略游戏。其中包含了大量的技巧性的东西,比如“如何使用虫族Rush”,“如何在不同情况下以最优化的方式发展经济”。不仅如此,据说它还可能教给你“21世纪的职场中重要的职业技巧”? 福罗里达州立大学的编号为IDS2935名为“21st Century Skills in Starcraft”的课程相信可以做到这一点。在课程介绍中写到:

[This class] does not teach about Starcraft, but rather aims to utilize the game and the complex situations that arise within it to present and develop the important skills professionals will undoubtedly need in the 21st Century workplace. (这个课程)不会教你关于星际争霸的知识,而是利用游戏中出现的各种复杂情况来展现和研究在21世纪的职场中所需要的各种重要的职业技巧。

This course includes required weekly game play, viewing and analysis of recorded matches, written assignments which emphasize analysis and synthesis of real/game-world concepts, and collaboration with other students. 这个课程的内容和要求包含:每周必须玩游戏,观看和分析比赛录像,写论文(着重分析游戏与现实世界中概念的结合),与其它同学的合作。

via crunchgear

10 Ways We Hurt Our Romantic Relationships

10 Ways We Hurt Our Romantic Relationshipsx 幸福爱情的十大忌讳【石榴刺猬全文译】

It's not easy to have a great relationship with your boy/girlfriend, partner, or spouse. But it's not impossible, either — it takes some work, of course, but it's work, work that's a joy when everything comes together.

A lot of times, though, the work isn't enough. We get in our own way with ideas and attitudes about relationships that are not only wrong, but often work to undermine our relationships no matter how hard we work at it.

I've watched a lot of breakups (some of them my own). I've seen dramatic flare-ups and drawn-out slow fades, and I've tried to pay attention to what seems to be going on. Here are a few of the things I've seen that cause people to destroy their own relationships.

能够和自己的男友(女友)或伴侣保持一段美好的感情不是一件那么容易的事情,但却并不是不可能。它需要付出一些努力,当然,也会有效。

尽管很多时候,光靠努力是不够的。我们带着自己的观点和态度去对待感情,这些观点和态度可能没错,但不管我们怎么努力,通常却会在无形中伤害到彼此的感情。

我看过太多的分手(包括我自己的)。我看到过矛盾激化而迅速分手,也看到过感情慢慢消磨掉了而分手,我试图去搞明白到底是怎么回事。这里是一些我所看到的,会导致我们毁掉彼此感情的一些东西。

  1. You're playing to win  事事争胜 One of the deadliest killers of relationships is the competitive urge. I don't mean competition in the sense that you can't stand to lose at tennis, I mean the attitude that the relationship itself is a kind of game that you're tying to win. People in competitive relationships are always looking for an advantage, the upper hand, some edge they can hold over their partner's head. If you feel that there are things you can't tell your partner because she or he will use it against you, you're in a competitive relationship — but not for long.

逼迫性的要求是两性关系中最致命的一点。我所说的逼迫性并不是指在俩人发生矛盾的时候不能输给对方,而是指处理感情时就好像要去赢一场比赛一样的那种态度。人们在对抗性的感情中,总是希望获得某种优势、占据上风,或是寻求某种能够牢牢吃定对方的优势。如果你觉得有些事情不能告诉你的伴侣——因为对方可能会以此来对付你,那么你就处于一个对抗性的关系中——但是不会长久这样下去的。

  1. You don't trust  缺乏信任 There are two aspects of trust that are important in relationships. One is trusting your partner enough to know that s/he won't cheat on you or otherwise hurt you — and to know that he or she trusts you that way, too. The other is trusting them enough to know they won't leave you or stop loving you no matter what you do or say. The second that level of trust is gone, whether because one of you takes advantage of that trust and does something horrible or because one of you thinks the other has, the relationship is over — even if it takes 10 more years for you to break up.

感情中的信任有很重要的两个方面。 一个是给对方足够的信任,相信对方不会欺骗或伤害你,同时也相信对方也会用同样的方式对待你;另外一个是充分的相信对方——无论你说了什么或做了什么,对方都不会离开你或者不再爱你。如果失去了这种程度的信任,无论是因为你充分利用了对方的这种信任做了一些很糟糕的事情,还是因为你们中的一个认为已经失去了对方的这种信任,你们的感情算是完蛋了——即使你们已经在一起了十几年。

  1. You don't talk  欠缺沟通  Too many people hold their tongues about things that bother or upset them in their relationship, either because they don't want to hurt their partner, or because they're trying to win. (See #1 above; example: “If you don't know why I'm mad, I'm certainly not going to tell you!”) While this might make things easier in the short term, in the long run it gradually erodes the foundation of the relationship away. Little issues grow into bigger and bigger problems — problems that don't get fixed because your partner is blissfully unaware, or worse, is totally aware of them but thinks they don't really bother you. Ultimately, keeping quiet reflects a lack of trust — and, as I said that's the death of a relationship.

有太多的人在面对感情中会让人心烦意乱或吵架的时候,都会选择回避、不去说。要么是因为不想去伤害对方,要么是因为想赢(参看第一条,比如:“如果你不知道我为什么生气,我更不会告诉你”)。在短期内这样做可以让事情好办一些,但长期来看这样会慢慢的侵蚀掉两人关系的基础,最终导致破裂。小问题会变成越来越大的问题,因为对方总是处于一种幸福的无知状态(掩耳盗铃),问题总是无法得以解决。即使意识到了问题的存在,也总想当然的认为这些问题不会真的给你带来麻烦。最终,这种无言的背后是信任的缺失——或者用我的话来说就是,两人感情的终结。

  1. You don't listen  不会倾听 Listening — really listening — is hard. It's normal to want to defend ourselves when we hear something that seems like criticism, so instead of really hearing someone out, we interrupt to explain or excuse ourselves, or we turn inward to prepare our defense. But your partner deserves your active listening. S/he even deserves you to hear the between-the-lines content of daily chit-chat, to suss out his/her dreams and desires when even s/he doesn't even know exactly what they are. If you can't listen that way, at least to the person you love, there's a problem.

    倾听——真正的倾听——是一件很难的事情。当我们听到对自己的批评或者责难的时候,通常我们都会选择防守来保护自己。因此当听到这些对自己的批评的时候,我们不会等对方说完,而是直接打断对方来为自己解释或者开脱。对方会“理所当然”的认为你“应该”仔细的听这些唠叨,然后明白对方想要的东西——尽管有的时候对方自己也不知道自己想要什么。如果你不能用这样的方式来倾听(至少对你爱的人这样),这就是个问题。

  2. You spend like a single person  自己过自己的 This was a hard lesson for me to learn — until it broke up a 7-year relationship. When you're single, you can buy whatever you want, whenever you want, with little regard for the future. It's not necessarily wise, but you're the only one who has to pay the consequences. When you are with someone in a long-term relationship, that is no longer a possibility. Your partner — and your children, if there are or will be any — will have to bear the brunt of your spending, so you'd better get in the habit of taking care of household necessities first and then, if there's anything left over, of discussing with your partner the best way to use it.

This is an increasing problem these days, because more and more people are opting to keep their finances separate, even when they're married. There's nothing wrong with that kind of arrangement in and of itself, but it demands more communication and involvement between the partners, not less. If you're spending money as if it was your money and nobody else has a right to tell you what to do with it, your relationship is doomed.

对我来说这是一个很沉重的教训,它让我失去了一段7年的感情。当单身的时候,你可以想买什么就买什么,想什么时候买就什么时候买,基本不考虑将来。虽然并不明智,但毕竟只会影响到你自己,一人吃饱全家不饿。但当你和某人开始一段长期的 感情中的时候,就再也不能这样了。你的伴侣——和你的孩子(如果已经有了或将来会有),将不得不去承担你的花费所带来的压力。因此你最好养成一个习惯,先去关注那些日常家用所需要的东西。之后如果还有结余,再来跟对方讨论如何使用这些钱最好。

目前这是一个日益严重的问题,因为现在很多人认为双方的财务应该分开,即使是结婚了也应该如此。这样做本身并没有什么问题,但是这样一来需要和对方有更多的沟通和交流,而不是更少。如果你觉得自己的钱爱怎么花就怎么花,别人谁也管不着,那你的感情基本就算完了。

  1. You're afraid of breaking up  害怕分手 Nobody in a truly happy partnership is afraid of breaking up. If you are, that's a big warning sign that something's wrong. But often, what's wrong is the fear itself. Not only does it betray a lack of trust, but it shows a lack of self-confidence and self-esteem — you're afraid that there's no good reason for someone to want to be with you, and that sooner or later your partner will “wise up” and take off. So you pour more energy into keeping up the appearance of a happy relationships than you do into building yourself up as a person. Quite frankly, this isn't going to be very satisfying for you, and it also isn't going to be very satisfying for your partner.

在一段幸福的感情中,没有人会害怕分手。如果你怕了,那么这就是一个很大的危险信号,这表明出问题了。但是通常,出的问题本身就让人不愿面对。它不仅仅表明你背叛了脆弱的信任(参看第2条信任的定义),也表明缺乏自信和自尊——你怕对方没有什么理由要跟你在一起,或者怕对方早晚都会想明白然后放手。因此你付出更多的精力来保持和维系这种貌似快乐的关系,而不是让自己变的更好。坦白的说,这不会让你觉得舒服,而且也不会让对方觉得很舒服。

  1. You're dependent  依赖性强 There's a thin line between companionship and support and dependency. If you depend on your partner — that is, if you absolutely cannot live without her or him — you've crossed that line. The pressure is now on your partner to fill whatever's missing in you — a pressure s/he will learn to resent. If you expect your partner to bring everything while you bring nothing to your relationship — and I'm talking finances as well as emotional support, here — you're in trouble. (Note: I'm not saying that you need to contribute equally to household finances — what I'm saying is that if you're not contributing to the household budget, and you're not contributing anywhere else, things are out of whack and that's never good.)

在感情、支持和依赖之间,有一条很窄的线。 如果你很依赖对方,如果你无法离开对方自己一个人生活,你就过线了。此时压力在对方身上,他要满足你的要求,这种压力会让对方对你不满。如果你只想对方付出所有,而自己不付出(这里对于感情和财务都一样),你就麻烦了。(注意:我不是说你必须要为家庭财务做出贡献,我是说如果你对于家庭财务或者其它任何方面都没有贡献的话,这绝对不是好事)

  1. You expect Happiness  期望得到快乐 A sign of a bad relationship is that one or both partners expect either to make the other happy or for their partner to make them happy. This is not only an unrealistic expectation to lay on yourself or on them — nobody can “make” you happy, except you — but it's an unrealistic expectation to lay on your relationship. Relationships aren't only about being happy, and there's lots of times when you won't and even shouldn't be. Being able to rely on someone even when you're upset, miserable, depressed, or grieving is a lot more important than being happy all the time. If you expect your partner to make you happy — or worse, you're frustrated because you aren't able to make your partner happy — your relationship isn't going to fare well when it hits a rough spot.

如果你或对方或你们两个都觉得自己应该让对方快乐,或者对方应该让自己快乐,这是感情中的一个很糟糕的现象。 这不仅仅是对你或你们自己的一个不现实的期望——没有人能够“让”你快乐,只有你自己能——这也是对你们感情的一个不现实的期望。感情不仅仅是获得快乐,很多时候你不会、甚至不应该仅仅是获得快乐。能够在心烦、痛苦、绝望或伤心的时候去依赖某个人,比仅仅只是获得快乐要重要的多。如果你希望对方能够“让”你快乐,或者进一步的,你因为无法“让”对方快乐而沮丧,那么当你的感情在遇到坎坷的时候会出问题的。

  1. You never fight  从不吵架 A good argument is essential, every now and then. In part, arguing helps bring out the little stuff before it becomes major, but also, fighting expresses anger which is a perfectly normal part of a human's emotional make-up. Your relationship has to be strong enough to hold all of who you are, not just the sunny stuff.

One reason couples don't fight is that they fear conflict — which reflects a lack of trust and a foundation of fear. That's bad. Another reason couples avoid arguments is that they've learned that anger is unreasonable and unproductive. They've learned that arguing represents a breakdown rather than a natural part of a relationship's development. While an argument isn't pleasant, it can help both partners to articulate issues they may not have even known they had — and help keep them from simmering until you cross a line you can't come back from.

偶尔进行一些良性的争论是件好事。一方面,争论能够让小问题在变成大问题之前暴露出来;同时,争论能够把生气和不满表达出来,这是人类众多情绪中最正常的一种。你们的感情必须足够坚实,这样才能包容你们的所有好的和不好的方面,而不仅仅只是那些美好的事情。

很多人不吵架是因为害怕冲突——觉得这代表了不信任,也是害怕的根本原因。这样不好。还有很多人不吵架是因为他们觉得生气是无理取闹,而且没有什么效果。他们认为吵架意味着感情的倒退,而不是认为这是感情发展中很自然的一部分。虽然吵架并不会让人愉快,但它能让双方把问题说清楚,甚至在此之前双方可能都不知道自己到底有什么问题;同时,吵架也能避免事态在无形中逐步升级,直到某一方做了再也无法挽回的事情。

  1. You expect it to be easy/you expect it to be hard  把爱情想的很轻松或者很难 There are two deeply problematic attitudes about relationships I hear often. One is that a relationship should be easy, that if you really love each other and are meant to be together, it will work itself out. The other is that anything worth having is going to be hard — and that therefore if it's hard, it must be worth having.

The outcome of both views is that you don't work at your relationship. You don't work because it's supposed to be easy and therefore not need any work, or you don't work because it's supposed to be hard and it wouldn't be hard if you worked at it. In both cases, you quickly get burnt out — either because the problems you're ignoring really don't go away just because you think they should. or because the problems you're cultivating are a constant drag on your energy. A relationship that's too much work might be suffering from one of the attitudes above, but a relationship that doesn't seem to need any work isn't any better.

我经常听到对感情的两种很有问题的态度。一个是,感情应该是轻松的,如果你真的爱对方,想跟对方在一起,感情自然就有了。另外一个是,任何值得去拥有的东西都很难得到,因此如果获得感情很难,它一定值得去拥有。

这两种观点表明你并没有为感情付出努力。要么因为如果获得感情是件很容易的事情,那么就并不需要付出什么努力;要么因为获得感情应该是件很难的事情,如果努力了那么它就不难了。这两种情况下,你很快会吃到苦头——要么是你所忽视的问题并没有因为你认为它应该那样而不存在,要么是你所制造出来的问题会一直拖累你。付出过多努力的感情,可能会让人比上面那两种情况更苦恼,但没有付出努力的感情,永远也不会变得更好。

Your choices 你的选择: There isn't any one answer to any of the problems above. There are choices though: you can either seek out an answer, something that addresses why you are hurting your relationship, or you can resign yourself to the failure of your relationship (and maybe the next one, and the next one, and…). Failure doesn't always mean you break up — many people aren't that lucky. But people can live quite unhappily in failed relationships for years and even decades because they're afraid they won't find anything better, or worse, they're afraid they deserve it. Don't you be one of them — if you suffer from any of these problems, figure out how to fix it, whether that means therapy, a solo mountain retreat, or just talking to your partner and committing yourselves to change. 上述问题都没有一个唯一确定的答案,但是你有不同选择:你可以尝试去给自己找一个答案,明白你为什么在伤害你俩的感情,你也可以选择退出这段失败的感情(也许还包括下一段,再下一段……)。失败的感情不一定意味着分手——很多人没有那么幸运。很多人可以一直在失败的感情中不愉快的生活很多年,甚至一辈子。因为他们害怕自己找不到更好的,更糟糕的是一些人认为这是自己应得的。如果你也是如此,不要跟他们一样,从问题中吸取教训,尝试去真正解决问题,例如寻求心理治疗,独自去远足一下,或者直接跟伴侣商量,确确实实的做一些改变……

避免Android开发中的ANR

via:  Writing Zippy Android Apps

ANR是什么

ANRs (“Application Not Responding”),意思是”应用没有响应“。

在如下情况下,Android会报出ANR错误:

– 主线程 (“事件处理线程” / “UI线程”) 在5秒内没有响应输入事件

– BroadcastReceiver 没有在10秒内完成返回

通常情况下,下面这些做法会导致ANR

1、在主线程内进行网络操作

2、在主线程内进行一些缓慢的磁盘操作(例如执行没有优化过的SQL查询)

应用应该在5秒或者10秒内响应,否则用户会觉得“这个应用很垃圾”“烂”“慢”...等等

一些数据(Nexus One为例)

• ~0.04 ms – 通过管道进程从A->B再从B->A写一个字节;或者(从dalvik)读一个简单的/proc文件

• ~0.12 ms – 由A->B 再由B->A 进行一次Binder的RPC调用

• ~5-25 ms – 从未缓冲的flash • ~5-200+(!) ms – 向为缓冲的flash中写点东西(下面是具体数据)

•    16 ms – 60fps的视频中的一帧

•    41 ms – 24fps的视频中的一帧

• 100-200 ms – human perception of slow action

• 108/350/500/800 ms – 3G网络上ping(可变)

• ~1-6+ seconds – 通过HTTP在3G网络上获取6k的数据

android.os.AsyncTask

AsyncTask 可以与UI线程很方便的配合,这个类可以在后台执行一些操作,并在执行结束的时候将结果发布到UI线程中去,并且无需使用线程或handler来控制。

例子:

private class DownloadFilesTask extends AsyncTask {
    protected Long doInBackground(URL... urls) {  // on some background thread
            int count = urls.length;
            long totalSize = 0;
            for (int i = 0; i < count; i++) {
                totalSize += Downloader.downloadFile(urls[i]);
                publishProgress((int) ((i / (float) count) * 100));
            }

            return totalSize;
        } 

        protected void onProgressUpdate(Integer... progress) {  // on UI thread!
        setProgressPercent(progress[0]);
    } 

    protected void onPostExecute(Long result) {  // on UI thread!
        showDialog("Downloaded " + result + " bytes");
    }
} 

new DownloadFilesTask().execute(url1, url2, url3);  // call from UI thread!
private boolean handleWebSearchRequest(final ContentResolver cr) {
            ...
    new AsyncTask() {
        protected Void doInBackground(Void... unused) {
            Browser.updateVisitedHistory(cr, newUrl, false);
            Browser.addSearchUrl(cr, newUrl);
            return null;
        } 

    }.execute()
            ...
    return true; 

}

AsyncTask要点

1、必须从主线程调用,或者线程中有Handler或Looper。

2、不要在一个可能会被另外一个AsyncTask调用的库里面使用AsyncTask(AsyncTask是不可重入的)

3、如果从一个activity中调用,activity进程可能会在AsyncTask结束前退出,例如:

  • 用户退出了activity
  • 系统内存不足
  • 系统暂存了activity的状态留待后用
  • 系统干掉了你的线程

如果AsyncTask中的工作很重要,应该使用......

android.app.IntentService

Eclair(2.0, 2.1)文档中说:

“An abstract Service that serializes the handling of the Intents passed upon service start and handles them on a handler  thread.  To use this class extend it and implement onHandleIntent(Intent). The Service will automatically be  stopped when the last enqueued Intent is handled.” 有点令人困惑,因此...几乎没人用

Froyo (2.2) 的文档, 又澄清了一下....

android.app.IntentService

“IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests  through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself  when it runs out of work.

This 'work queue processor' pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to  simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService  will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but  only one request will be processed at a time.”

IntentService 的好处

  • Acitivity的进程,当处理Intent的时候,会产生一个对应的Service
  • Android的进程处理器现在会尽可能的不kill掉你
  • 非常容易使用

日历中IntentService的应用

public class DismissAllAlarmsService extends IntentService {
    @Override public void onHandleIntent(Intent unusedIntent) {
        ContentResolver resolver = getContentResolver();
        ...
        resolver.update(uri, values, selection, null);
    }
}
in AlertReceiver extends BroadcastReceiver, onReceive():  (main thread)
    Intent intent = new Intent(context, DismissAllAlarmsService.class);
    context.startService(intent);

其它技巧

1、当启动AsyncTask的时候,立刻disable UI元素(按钮等等)。

2、显示一些动画,表示在处理中

3、使用进度条对话框

4、使用一个定时器作为耗时警告,在AsyncTask开始时启动定时器,在AsyncTask的onPostExecute方法中取消定时器。

5、当不确定要耗时多久的时候,组合使用上述所有方法

总结

  • 离开主线程!
  • 磁盘和网络操作不是马上就能完的
  • 了解sqlite在干嘛
  • 进度展示很好

PS,在视频讲座中,作者还提到,Chrome团队为了避免Jank(响应超时而死掉),几乎所有的功能和任务都会在子线程里面去做。这一点也值得在Android中借鉴。

刘金雨译:  避免Android开发中的ANR 全文via:  Writing Zippy Android Apps

在Eclipse中查看Android SDK的源代码

via http://stuffthathappens.com/blog/2008/11/01/browsing-android-source-in-eclipse/ Google的Android SDK中包含一个android.jar文件,里面有Android所有的公开类的API接口。同时,Google还提供了一个Eclipse插件,可以很容易的开始进行开发。但是,这里并没有一个类似于androidSrc.jar的文件,因此当我们试图在Eclipse去查看Android SDK的源代码的时候,会得到下面这样的一个页面: Google已经发布了Android所有的源代码,很大。要在Eclipse中查看Android的源代码,需要去http://source.android.com/(国内需翻墙),Get Source那个页面内按照指示一步步的将所有的东西都通过Git弄下来。很值得抽出一个晚上的时间来做这件事,因为如果能够随时查看源码,对于理解SDK如何工作的是非常有帮助的。

链接到Eclipse

现在我们有了源码,应该可以告诉Eclipse如何找到它了。右键点击android.jar——属性,可是却发现了这样的信息: 嗯....那段话的大意是,当前的class path的设置属于'Android Library',不允许用户修改。好吧,只能去看看ADT的源码了,看能否找到什么办法。

查看ADT源码

当下载完Android源码之后,我们已经得到了所有内容,包括:操作系统、Dalvik虚拟机、Eclipse插件、公开的SDK...等等。 在 com.android.ide.eclipse.adt.project.internal 包里,我找到一个名为 AndroidClassspathContainerInitializer.java 的类,包含如下代码:
IPath android_src = new Path(AdtPlugin.getOsAbsoluteAndroidSources());
好,再来看看 AdtPlugin.java:
/** Returns the absolute android sources path in the sdk */
public static String getOsAbsoluteAndroidSources() {
return getOsSdkFolder() + getOsRelativeAndroidSources();
}

/** Returns the android sources path relative to the sdk folder */
public static String getOsRelativeAndroidSources() {
return AndroidConstants.FD_ANDROID_SOURCES;
}
最后来看看 AndroidConstants.java:
public static final String FD_ANDROID_SOURCES = "sources";
搞定!

解决方案 #1

根据上面的分析,我们可以在android SDK的安装目录内创建一个sources目录,与android.jar位于同一个目录内。之后,我们可以在之前下好的Android源码中找到所有我们需要的代码。SDK的代码在frameworks/base/core/java,在这个目录下有一个android目录,我们需要将这个目录拷贝(链接)到SDK安装目录中的sources目录。你可能需要想想办法,把所有分散在不同Component的源码都弄到一起去。最终我们的目录结构大致如下:
SDK_PATH
  |-- android.jar
  +--docs/...
  +--samples/...
  +--sources
       +--android
       |      ...accounts, annotation, app, bluetooth, etc...
       +--com/android/etc...
       +--dalvik/...
       +--java/...
       +--javax/...
我把所有这样的目录都弄进来了,但是没有详细记录。 译注(也就是我Simon Liu): 上面的代码是适用于以前的老版本的ADT,目前最新版本的ADT已经不适用了。经过查看源代码发现,最新版本的ADT需要在SDK目录下的platforms\android-X对应的目录下建立sources目录,其中X是3、4、7、8之一的数字,对应不同的SDK版本。这也是一个比较合理的方案,毕竟不同版本的SDK的源码还是不一样的。 如果你在Linux或者Mac下工作,sources的源码目录结构可以用我写的如下的一个Shell脚本来完成这个事情,在Android的源码目录下运行这个脚本,然后会在~/workspace/src-tree创建"几乎"所有Java源码的soft symbol link。之后也可以用tar带-h参数打包到windows下使用。你可以根据自己的需求修改一下。
simon@simon-desktop:~/bin$ cat make-src-tree
#!/bin/bash
# Author: Simon Liu , Beijing, China
# Date: 2010-08-27
# License: GPL

curr_dir=$PWD
dest_dir=~/workspace/src-tree
if [ ! -z "$1" ]; then
        dest_dir=$1
fi

rm -rf $dest_dir
mkdir -p $dest_dir

for d in $(find -path .repo -prune \
    -or -path .git -prune \
    -or -path "*/src/com/*" -type d -print \
    -or -path "*/src/org/*" -type d -print \
    -or -path "*/java/com/*" -type d -print \
    -or -path "*/java/org/*" -type d -print \
    -or -path "*/java/android/*" -type d -print \
    -or -path "*/java/javax/*" -type d -print)
do
        sd=$(echo $d | sed 's#.*/src/.*/#\1/#g' | sed 's#.*/java/.*/#\1/#g')
        echo ";; $sd"

        mkdir -p $dest_dir/$sd
        for f in $(cd $d; find . -mindepth 0 -maxdepth 1 -type f | sed 's#^./##g'); do
                echo "        $f"
                ln -s $curr_dir/$d/$f $dest_dir/$sd/$f
        done
done
现在,当我再去查看Android SDK类的时候,可以看到源码了:

解决方案 #2

如果你实在不愿意把所有的Android源码拷贝到SDK目录里面去,也可以创建一个Eclispe User Library并把源码附加上去。

Go 编程语言入门教程

原文:http://golang.org 翻译:刘金雨 http://log4think.com

介绍

本文档是关于Go编程语言基础的一个介绍性的入门教程,偏向于熟悉C或C++的读者。本文并非一份语言的完整指南,如果需要的话可以参考语言规范。读完本教程之后,你可以继续学习Effective Go,这份文档会更深入的挖掘如何使用Go语言。

此外还有一份《三日入门》的教程可供参考:

本文将会以一系列适当的程序来说明语言的一些关键特性。所有的示例程序都是可运行的(在撰写本文时),并且这些程序都会提交到版本库的/doc/progs/目录下。

程序片段都会标注上在源文件中的行号,为了清晰起见,空行前面的行号留空。

Hello World

先从一个最常见的开始:

05    package main

07    import fmt "fmt"  // 本包实现了格式化输入输出

09    func main() {
10        fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界n");
11    }

每份Go的源文件都会使用package语句声明它的包名。同时也可以通过导入其它包来使用其中定义的功能。这段代码导入了包fmt来调用我们的老朋友——现在它的开头字母是大写的,并且前面带有包名限定fmt.Printf

函数的声明使用关键字func,整个程序将会从为main包中的main函数开始(经过初始化之后)。

字符串常量可以包含Unicode字符,采用UTF-8编码(事实上,所有Go程序的源文件都是使用UTF-8编码的)。

注释的方式同C++一样:/* ... */// ...

稍后我们会继续提到print

编译

Go是一个编译型语言。目前有两个编译器,其中gccgo编译器采用了GCC作为后端,此外还有一系列根据其所适用的架构命名的编译器,例如6g适用于64位的x86结构,8g 适用于32位的x86结构,等等。这些编译器比gccgo运行的更快、生成的代码更加有效率。在撰写本文的时候(2009年底),他们还具有一个更加健壮的运行期系统,但是gccgo也正在迎头赶上。

下面来看看如何编译和运行程序。采用6g是这样的

$ 6g helloworld.go  编译; 中间代码位于 helloworld.6 中
$ 6l helloworld.6   链接; 输出至 6.out
$ 6.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$

gccgo的方式看起来更加传统一些。

$ gccgo helloworld.go
$ a.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$

Echo

下一步,来实现一个Unix的传统命令Echo:

05    package main

07    import (
08        "os";
09        "flag";  // command line option parser
10    )

12    var omitNewline = flag.Bool("n", false, "don't print final newline")

14    const (
15        Space = " ";
16        Newline = "n";
17    )

19    func main() {
20        flag.Parse();   // Scans the arg list and sets up flags
21        var s string = "";
22        for i := 0; i < flag.NArg(); i++ {
23            if i &gt; 0 {
24                s += Space
25            }
26            s += flag.Arg(i);
27        }
28        if !*omitNewline {
29            s += Newline
30        }
31        os.Stdout.WriteString(s);
32    }

这段程序很小,但是却有几个新出现的概念。前面这个例子中,我们看到可以使用func来声明一个函数,同时关键字var、consttype目前还没有用到)也可以用于声明,就好像import一样。

注意,我们可以将同一类的声明放到括号中,以分号分隔。例如第7-10行和第14-17行。但也并非一定要如此,例如可以这样写```

const Space = " "
const Newline = "n"

分号在此处并不是必须的。事实上,任何顶层声明后面都不需要分号。但如果要是在一个括号内进行一系列的声明,就需要用分号来分割了。

你可以像在C、C++或Java中那样去使用分号,但如果你愿意的话,在很多情况下都可以省略掉分号。分号是用于表示语句间的分隔,而非表示其中止。因此,对于一个代码块中的最后一条语句来说,有无分号皆可。大括号之后的分号也是可选的,就像C语言中的一样。

比对一下echo的源代码,只有第8、15和21行必须要加分号,当然第22行中的for语句中为了分隔三个表达式也需要加分号。第9、16、26和31行的分号都不是必须的,加上分号只是为了以后再增加语句的时候方便而已。

这个程序导入了os包以访问Stdout变量,Stdout的类型是*os.Fileimport语句实际上是个声明:通常情况下(如hello world程序中那样),它声明了一个标识符fmt用于访问导入的包的成员变量,而包是从当前目录或标准库下的fmt文件中导入的。在这个程序中,我们为导入的包显式的指定了一个名字,默认情况下,包名是采用在导入的包里面已经定义好的名字,通常会与文件名一致。因此在这个“hello world”程序中,可以只写import "fmt"。你可以任意为包指定一个导入名,但通常只有在解决名字冲突的情况下才有必要这样做。

有了os.Stdout,我们就可以用它的WriteString方法打印字符串了。

导入了实 际flag包之后,第12行创建了一个全局变量来保存 echo 的-n选项标志。omitNewline变量的类型是 *bool ——指向bool值的指针。

main.main中进行了参数解析,并创建了一个本地字符串类型的变量用于构造输出的内容。声明语句如下

var s string = "";

这里用到了关键字var,后面跟变量名和数据类型,之后可以继续接=来赋初值。

Go试图尽量保持简洁,这个声明也可以用更短的形式。因为初值是一个字符串类型的常量,没有必要再声明数据类型了,因此这个声明可以写成这样:

var s = "";

或者也可以直接用更短的形式:

s := "";

操作符:=在 Go 语言里经常会用在赋初值的声明中,比如下面这个for语句的声明:

22    for i := 0; i < flag.NArg(); i++ {

flag包会解析命令行参数,并将参数值保存在一个列表中。

Go语言中的for语句和C语言中的有几个不同之处。首先,for是唯一的循环语句,没有while语句或do语句。其次,for语句后面的三个子句不需要圆括号,但大括号是必须的。这一条对ifswitch语句同样适用。稍后还会有几个例子演示for语句的其它用法。

循环体中通过追加(+=)标志和空格构造字符串s。循环之后,如果没有设置-n标志,程序追加一个空行,最后输出结果。

注意,函数main.main没有返回值。它就是这样定义的,如果到达了main.main的末尾就表示“成功”,如果想表明出错并返回,可以调用

os.Exit(1)

os包还包含一些其他的常用功能,例如os.Args会被flag包用于访问命令行参数。

插播:数据类型 Types

Go支持一些常见的数据类型,例如intfloat,其值采用机器“适用”的大小来表示。也有定义了明确大小的数据类型,例如int8float64等,以及无符号整数类型,例如uintuint32等。这些都是完全不同的数据类型,即使intint32都是32位整数,但它们是不同的类型。对于表示字符串元素的类型byteuint8也是同样如此。

说到字符串(string),这也是一个内置的数据类型。字符串的值不仅仅是一个byte的数组,它的值是不可改变的。一旦确定了一个字符串的值,就不能再修改了。但一个字符串变量的值可以通过重新赋值来改变。下面这段来自strings.go的代码是合法的:

11    s := "hello";
12    if s[1] != 'e' { os.Exit(1) }
13    s = "good bye";
14    var p *string = &s;
15    p = "ciao";

然而下面这段代码是非法的,因为它试图修改一个字符串的值:

s[0] = 'x';
(*p)[1] = 'y';

按照C++的说法,Go的字符串有点类似带了const修饰符,指向字符串的指针也类似于一个 const 字符串的引用(reference).

没错,前面看到的那些是指针,然而Go语言中的指针在用法方面有所简化,后文会提到。

数组的声明如下所示:

var arrayOfInt [10]int;

数组同字符串一样是“值”,但是却是可变的。与C不同的是,C语言中arrayOfInt可以当做一个指向int的指针来用。在Go中,因为数组是,因此arrayOfInt被看做(也被用做)指向数组的指针。

数组的大小是其数据类型的一部分。但是,你可以声明一个slice变量,然后可以用一个指向具有相同元素类型的数组指针给它赋值,更常见的是用一个形式为a[low : high]slice表达式,该表达式表示下标从lowhigh-1的子数组。 Slice 类型类似数组,但没有显式指定大小([]之于[10]),用于表示一个隐性(通常是匿名的)数组。如果不同的 slice 都是表示同一个数组中的数据,它们可以共享该数组的内存,但不同的数组则永远不会共享内存数据。

Slice 在 Go 程序中比数组更常见。它更灵活,并且具有引用的语义,效率也更高。其不足之处在于无法像数组一样精确控制存储方式,如果想在一个数据结构中保存一个具有 100个元素的序列,应该采用数组。

当给函数传一个数组参数的时候,绝大多数情况下都会把参数声明为 slice 类型。当调用函数时,先取数组地址,然后Go会创建一个 slice 的引用,然后传这个引用过去。

可以用 slice 来写这个函数(来自sum.go):

09    func sum(a []int) int {   // 返回一个整数
10        s := 0;
11        for i := 0; i < len(a); i++ {
12            s += a[i]
13        }
14        return s
15    }

之后这样来调用:

19    s := sum(&[3]int{1,2,3});  // a slice of the array is passed to sum

注意在sum()的参数列表后面加 int 定义了其返回值类型(int)。[3]int{1,2,3}的形式是一个数据类型后面接一个大括号括起来的表达式,整个这个表达式构造出了一个值,这里是一个包含三个整数的数组。前面的&表示提取这个值的地址。这个地址会被隐性的转为一个 slice 传给sum()

如果想创建一个数组,但希望编译器来帮你确定数组的大小,可以用...作为数组大小:

s := sum(&[...]int{1,2,3});

实际使用中,除非非常在意数据结构的存储方式,否则 slice 本身 (用[]且不带&) 就足够了:

s := sum([]int{1,2,3});

除此之外还有map,可以这样初始化:

m := map[string]int{"one":1 , "two":2}

sum还第一次出现 了内置函数len(),用于返回元素数量。可以用于字符串、数组、slice、map、map和channel.

此外,for循环中的range也可以用于字符串、数组、slice、map、map和channel。例如

for i := 0; i < len(a); i++ { ... }

遍历一个序列的每个元素,可以写成

for i, v := range a { ... }

其中, i 会赋值为下标, v 会赋值为 a 中对应的值,Effective Go中包含了更多的用法演示。

An Interlude about Allocation

Go中的大多数数据类型都是值类型。对intstruct或数组的赋值会拷贝其内容。new()可以分配一个新的变量,并返回其分配的存储空间的地址。例如

type T struct { a, b int }
var t *T = new(T);

或者更常见的写法:

t := new(T);

Some types—maps, slices, and channels (see below)—have reference semantics. If you're holding a slice or a map and you modify its contents, other variables referencing the same underlying data will see the modification. For these three types you want to use the built-in functionmake():

m := make(map[string]int);

This statement initializes a new map ready to store entries. If you just declare the map, as in

var m map[string]int;

it creates anilreference that cannot hold anything. To use the map, you must first initialize the reference usingmake()or by assignment from an existing map.

Note thatnew(T)returns type*Twhilemake(T)returns typeT. If you (mistakenly) allocate a reference object withnew(), you receive a pointer to a nil reference, equivalent to declaring an uninitialized variable and taking its address.

An Interlude about Constants

Although integers come in lots of sizes in Go, integer constants do not. There are no constants like0LLor0x0UL. Instead, integer constants are evaluated as large-precision values that can overflow only when they are assigned to an integer variable with too little precision to represent the value.

const hardEight = (1 << 100) &gt;&gt; 97  // legal

There are nuances that deserve redirection to the legalese of the language specification but here are some illustrative examples:

var a uint64 = 0  // a has type uint64, value 0
a := uint64(0)    // equivalent; uses a "conversion"
i := 0x1234       // i gets default type: int
var j int = 1e6   // legal - 1000000 is representable in an int
x := 1.5          // a float
i3div2 := 3/2     // integer division - result is 1
f3div2 := 3./2.   // floating point division - result is 1.5

Conversions only work for simple cases such as convertingintsof one sign or size to another, and betweenintsandfloats, plus a few other simple cases. There are no automatic numeric conversions of any kind in Go, other than that of making constants have concrete size and type when assigned to a variable.

An I/O Package

Next we'll look at a simple package for doing file I/O with the usual sort of open/close/read/write interface. Here's the start offile.go:

05    package file

07    import  ( 
08        "os"; 
09        "syscall"; 
10    )

12    type File  struct { 
13        fd      int;    // file descriptor number
14        name    string; // file name at Open time 
15    }

The first few lines declare the name of the package—file—and then import two packages. Theospackage hides the differences between various operating systems to give a consistent view of files and so on; here we're going to use its error handling utilities and reproduce the rudiments of its file I/O.

The other item is the low-level, externalsyscallpackage, which provides a primitive interface to the underlying operating system's calls.

Next is a type definition: thetypekeyword introduces a type declaration, in this case a data structure calledFile. To make things a little more interesting, ourFileincludes the name of the file that the file descriptor refers to.

BecauseFilestarts with a capital letter, the type is available outside the package, that is, by users of the package. In Go the rule about visibility of information is simple: if a name (of a top-level type, function, method, constant or variable, or of a structure field or method) is capitalized, users of the package may see it. Otherwise, the name and hence the thing being named is visible only inside the package in which it is declared. This is more than a convention; the rule is enforced by the compiler. In Go, the term for publicly visible names is ''exported''.

In the case ofFile, all its fields are lower case and so invisible to users, but we will soon give it some exported, upper-case methods.

First, though, here is a factory to create aFile:

17    func newFile(fd int, name string) *File {
18        if fd < 0 {
19            return nil
20        }
21        return &File{fd, name}
22    }

This returns a pointer to a newFilestructure with the file descriptor and name filled in. This code uses Go's notion of a ''composite literal'', analogous to the ones used to build maps and arrays, to construct a new heap-allocated object. We could write

n := new(File);
n.fd = fd;
n.name = name;
return n

but for simple structures likeFileit's easier to return the address of a nonce composite literal, as is done here on line 21.

We can use the factory to construct some familiar, exported variables of type*File:

24    var (
25        Stdin  = newFile(0, "/dev/stdin");
26        Stdout = newFile(1, "/dev/stdout");
27        Stderr = newFile(2, "/dev/stderr");
28    )

ThenewFilefunction was not exported because it's internal. The proper, exported factory to use isOpen:

30    func Open(name string, mode int, perm int) (file *File, err os.Error) {
31        r, e := syscall.Open(name, mode, perm);
32        if e != 0 {
33            err = os.Errno(e);
34        }
35        return newFile(r, name), err
36    }

There are a number of new things in these few lines. First,Openreturns multiple values, aFileand an error (more about errors in a moment). We declare the multi-value return as a parenthesized list of declarations; syntactically they look just like a second parameter list. The functionsyscall.Openalso has a multi-value return, which we can grab with the multi-variable declaration on line 31; it declaresrandeto hold the two values, both of typeint(although you'd have to look at thesyscallpackage to see that). Finally, line 35 returns two values: a pointer to the newFileand the error. Ifsyscall.Openfails, the file descriptorrwill be negative andNewFilewill returnnil.

About those errors: Theoslibrary includes a general notion of an error. It's a good idea to use its facility in your own interfaces, as we do here, for consistent error handling throughout Go code. InOpenwe use a conversion to translate Unix's integererrnovalue into the integer typeos.Errno, which implementsos.Error.

Now that we can buildFiles, we can write methods for them. To declare a method of a type, we define a function to have an explicit receiver of that type, placed in parentheses before the function name. Here are some methods for*File, each of which declares a receiver variablefile.

38    func (file *File) Close() os.Error {
39        if file == nil {
40            return os.EINVAL
41        }
42        e := syscall.Close(file.fd);
43        file.fd = -1;  // so it can't be closed again
44        if e != 0 {
45            return os.Errno(e);
46        }
47        return nil
48    }
50    func  (file *File) Read(b []byte) (ret int, err os.Error) {
51        if file  == nil {
52            return -1, os.EINVAL 

53        }
54        r, e  := syscall.Read(file.fd, b);
55        if e != 0 {
56            err =  os.Errno(e);
57        }
58        return int(r), err
59    }

61    func  (file *File) Write(b []byte) (ret int, err os.Error) {
62        if  file == nil {
63            return -1, os.EINVAL 

64        }
65        r, e := syscall.Write(file.fd, b);
66        if e != 0 {
67            err = os.Errno(e);
68        }
69        return int(r),  err
70    }

72    func (file *File) String() string {
73        return file.name
74    }

There is no implicitthisand the receiver variable must be used to access members of the structure. Methods are not declared within thestructdeclaration itself. Thestructdeclaration defines only data members. In fact, methods can be created for almost any type you name, such as an integer or array, not just forstructs. We'll see an example with arrays later.

TheStringmethod is so called because of a printing convention we'll describe later.

The methods use the public variableos.EINVALto return the (os.Errorversion of the) Unix error codeEINVAL. Theoslibrary defines a standard set of such error values.

We can now use our new package:

05    package main
07    import  (
08        "./file";
09        "fmt";
10        "os";
11    )

13    func  main() {
14        hello := []byte{'h', 'e', 'l', 'l', 'o', ',', ' ',  'w', 'o', 'r', 'l', 'd', 'n'};
15        file.Stdout.Write(hello);
16        file, err := file.Open("/does/not/exist",  0,  0);
17        if file == nil {
18            fmt.Printf("can't open file;  err=%sn",  err.String());
19            os.Exit(1);
20        }
21    }

The ''./'' in the import of ''./file'' tells the compiler to use our own package rather than something from the directory of installed packages.

Finally we can run the program:

% helloworld3
hello, world
can't open file; err=No such file or directory
%

Rotting cats

Building on thefilepackage, here's a simple version of the Unix utilitycat(1),progs/cat.go:

05    package main

07    import (
08        "./file"
09        "flag"
10        "fmt"
11        "os"
12    )

14    func cat(f *file.File) {
15        const NBUF = 512
16        var buf [NBUF]byte
17        for {
18            switch nr, er := f.Read(&buf); true {
19            case nr < 0:
20                fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", f.String(), er.String())
21                os.Exit(1)
22            case nr == 0:  // EOF
23                return
24            case nr &gt; 0:
25                if nw, ew := file.Stdout.Write(buf[0:nr]); nw != nr {
26                    fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", f.String(), ew.String())
27                }
28            }
29        }
30    }

32    func main() {
33        flag.Parse()   // Scans the arg list and sets up flags
34        if flag.NArg() == 0 {
35            cat(file.Stdin)
36        }
37        for i := 0; i < flag.NArg(); i++ {
38            f, err := file.Open(flag.Arg(i), 0, 0)
39            if f == nil {
40                fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", flag.Arg(i), err)
41                os.Exit(1)
42            }
43            cat(f)
44            f.Close()
45        }
46    }

By now this should be easy to follow, but theswitchstatement introduces some new features. Like aforloop, aniforswitchcan include an initialization statement. Theswitchon line 18 uses one to create variablesnranderto hold the return values fromf.Read(). (Theifon line 25 has the same idea.) Theswitchstatement is general: it evaluates the cases from top to bottom looking for the first case that matches the value; the case expressions don't need to be constants or even integers, as long as they all have the same type.

Since theswitchvalue is justtrue, we could leave it off—as is also the situation in aforstatement, a missing value meanstrue. In fact, such aswitchis a form ofif-elsechain. While we're here, it should be mentioned that inswitchstatements eachcasehas an implicitbreak.

Line 25 callsWrite()by slicing the incoming buffer, which is itself a slice. Slices provide the standard Go way to handle I/O buffers.

Now let's make a variant ofcatthat optionally doesrot13on its input. It's easy to do by just processing the bytes, but instead we will exploit Go's notion of aninterface.

Thecat()subroutine uses only two methods off:Read()andString(), so let's start by defining an interface that has exactly those two methods. Here is code fromprogs/cat_rot13.go:

26    type reader interface {
27        Read(b []byte) (ret int, err os.Error);
28        String() string;
29    }

Any type that has the two methods ofreader—regardless of whatever other methods the type may also have—is said toimplementthe interface. Sincefile.Fileimplements these methods, it implements thereaderinterface. We could tweak thecatsubroutine to accept areaderinstead of a*file.Fileand it would work just fine, but let's embellish a little first by writing a second type that implementsreader, one that wraps an existingreaderand doesrot13on the data. To do this, we just define the type and implement the methods and with no other bookkeeping, we have a second implementation of thereaderinterface.

31    type rotate13 struct {
32        source    reader
33    }

35    func newRotate13(source reader) *rotate13 {
36        return &rotate13{source}
37    }

39    func (r13 *rotate13) Read(b []byte) (ret int, err os.Error) {
40        r, e := r13.source.Read(b)
41        for i := 0; i < r; i++ {
42            b[i] = rot13(b[i])
43        }
44        return r, e
45    }

47    func (r13 *rotate13) String() string {
48        return r13.source.String()
49    }
50    // end of rotate13 implementation

(Therot13function called on line 42 is trivial and not worth reproducing here.)

To use the new feature, we define a flag:

14    var rot13Flag = flag.Bool("rot13", false, "rot13 the input")

and use it from within a mostly unchangedcat()function:

52    func cat(r reader) {
53        const NBUF = 512
54        var buf [NBUF]byte

56        if *rot13Flag {
57            r = newRotate13(r)
58        }
59        for {
60            switch nr, er := r.Read(&buf); {
61            case nr < 0:
62                fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", r.String(), er.String())
63                os.Exit(1)
64            case nr == 0:  // EOF
65                return
66            case nr &gt; 0:
67                nw, ew := file.Stdout.Write(buf[0:nr])
68                if nw != nr {
69                    fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", r.String(), ew.String())
70                }
71            }
72        }
73    }

(We could also do the wrapping inmainand leavecat()mostly alone, except for changing the type of the argument; consider that an exercise.) Lines 56 through 58 set it all up: If therot13flag is true, wrap thereaderwe received into arotate13and proceed. Note that the interface variables are values, not pointers: the argument is of typereader, not*reader, even though under the covers it holds a pointer to astruct.

Here it is in action:

% echo abcdefghijklmnopqrstuvwxyz | ./cat
abcdefghijklmnopqrstuvwxyz
% echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13
nopqrstuvwxyzabcdefghijklm
%

Fans of dependency injection may take cheer from how easily interfaces allow us to substitute the implementation of a file descriptor.

Interfaces are a distinctive feature of Go. An interface is implemented by a type if the type implements all the methods declared in the interface. This means that a type may implement an arbitrary number of different interfaces. There is no type hierarchy; things can be much moread hoc, as we saw withrot13. The typefile.Fileimplementsreader; it could also implement awriter, or any other interface built from its methods that fits the current situation. Consider theempty interface

type Empty interface {}

Everytype implements the empty interface, which makes it useful for things like containers.

Sorting

Interfaces provide a simple form of polymorphism. They completely separate the definition of what an object does from how it does it, allowing distinct implementations to be represented at different times by the same interface variable.

As an example, consider this simple sort algorithm taken fromprogs/sort.go:

13    func Sort(data Interface) {
14        for i := 1; i < data.Len(); i++ {
15            for j := i; j &gt; 0 && data.Less(j, j-1); j-- {
16                data.Swap(j, j-1)
17            }
18        }
19    }

The code needs only three methods, which we wrap into sort'sInterface:

07    type Interface interface {
08        Len() int;
09        Less(i, j int) bool;
10        Swap(i, j int);
11    }

We can applySortto any type that implementsLen, Less, andSwap. Thesortpackage includes the necessary methods to allow sorting of arrays of integers, strings, etc.; here's the code for arrays ofint

33    type IntArray []int

35    func (p IntArray) Len() int            { return len(p) }
36    func (p IntArray) Less(i, j int) bool  { return p[i] < p[j] }
37    func (p IntArray) Swap(i, j int)       { p[i], p[j] = p[j], p[i] }

Here we see methods defined for non-structtypes. You can define methods for any type you define and name in your package.

And now a routine to test it out, fromprogs/sortmain.go. This uses a function in thesortpackage, omitted here for brevity, to test that the result is sorted.

12    func ints() {
13        data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586};
14        a := sort.IntArray(data);
15        sort.Sort(a);
16        if !sort.IsSorted(a) {
17            panic()
18        }
19    }

If we have a new type we want to be able to sort, all we need to do is to implement the three methods for that type, like this:

30    type day struct {
31        num        int
32        shortName  string
33        longName   string
34    }

36    type dayArray struct {
37        data []*day
38    }

40    func (p *dayArray) Len() int            { return len(p.data) }
41    func (p *dayArray) Less(i, j int) bool  { return p.data[i].num < p.data[j].num }
42    func (p *dayArray) Swap(i, j int)       { p.data[i], p.data[j] = p.data[j], p.data[i] }

Printing

The examples of formatted printing so far have been modest. In this section we'll talk about how formatted I/O can be done well in Go.

We've seen simple uses of the packagefmt, which implementsPrintf, Fprintf, and so on. Within thefmtpackage,Printfis declared with this signature:

Printf(format string, v ...) (n int, errno os.Error)

That ...represents the variadic argument list that in C would be handled using thestdarg.hmacros but in Go is passed using an empty interface variable (interface {}) and then unpacked using the reflection library. It's off topic here but the use of reflection helps explain some of the nice properties of Go'sPrintf, due to the ability ofPrintfto discover the type of its arguments dynamically.

For example, in C each format must correspond to the type of its argument. It's easier in many cases in Go. Instead of%lludyou can just say%d;Printfknows the size and signedness of the integer and can do the right thing for you. The snippet

10    var u64 uint64 = 1<<64-1;
11    fmt.Printf("%d %dn", u64, int64(u64));

prints

 18446744073709551615 -1

In fact, if you're lazy the format%vwill print, in a simple appropriate style, any value, even an array or structure. The output of

14    type T struct { a int; b string };
15    t := T{77, "Sunset Strip"};
16    a := []int{1, 2, 3, 4};
17    fmt.Printf("%v %v %vn", u64, t, a);

is

18446744073709551615 {77 Sunset Strip} [1 2 3 4]

You can drop the formatting altogether if you usePrintorPrintlninstead ofPrintf. Those routines do fully automatic formatting. ThePrintfunction just prints its elements out using the equivalent of%vwhilePrintlninserts spaces between arguments and adds a newline. The output of each of these two lines is identical to that of thePrintfcall above.

18    fmt.Print(u64, " ", t, " ", a, "n");
19    fmt.Println(u64, t, a);

If you have your own type you'd likePrintforPrintto format, just give it aString()method that returns a string. The print routines will examine the value to inquire whether it implements the method and if so, use it rather than some other formatting. Here's a simple example.

09    type testType struct {
10        a int
11        b string
12    }

14    func (t *testType) String() string {
15        return fmt.Sprint(t.a) + " " + t.b
16    }

18    func main() {
19        t := &testType{77, "Sunset Strip"}
20        fmt.Println(t)
21    }

Since*testTypehas aString()method, the default formatter for that type will use it and produce the output

77 Sunset Strip

Observe that theString()method callsSprint(the obvious Go variant that returns a string) to do its formatting; special formatters can use thefmtlibrary recursively.

Another feature ofPrintfis that the format%Twill print a string representation of the type of a value, which can be handy when debugging polymorphic code.

It's possible to write full custom print formats with flags and precisions and such, but that's getting a little off the main thread so we'll leave it as an exploration exercise.

You might ask, though, howPrintfcan tell whether a type implements theString()method. Actually what it does is ask if the value can be converted to an interface variable that implements the method. Schematically, given a valuev, it does this:

type Stringer interface {
    String() string
}

s, ok := v.(Stringer);  // Test whether v implements "String()"
if ok {
    result = s.String()
} else {
    result = defaultOutput(v)
}

The code uses a ``type assertion'' (v.(Stringer)) to test if the value stored invsatisfies theStringerinterface; if it does,swill become an interface variable implementing the method andokwill betrue. We then use the interface variable to call the method. (The ''comma, ok'' pattern is a Go idiom used to test the success of operations such as type conversion, map update, communications, and so on, although this is the only appearance in this tutorial.) If the value does not satisfy the interface,okwill be false.

In this snippet the nameStringerfollows the convention that we add ''[e]r'' to interfaces describing simple method sets like this.

One last wrinkle. To complete the suite, besidesPrintfetc. andSprintfetc., there are alsoFprintfetc. Unlike in C,Fprintf's first argument is not a file. Instead, it is a variable of typeio.Writer, which is an interface type defined in theiolibrary:

type Writer interface {
    Write(p []byte) (n int, err os.Error);
}

(This interface is another conventional name, this time forWrite; there are alsoio.Reader,io.ReadWriter, and so on.) Thus you can callFprintfon any type that implements a standardWrite()method, not just files but also network channels, buffers, whatever you want.

Prime numbers

Now we come to processes and communication—concurrent programming. It's a big subject so to be brief we assume some familiarity with the topic.

A classic program in the style is a prime sieve. (The sieve of Eratosthenes is computationally more efficient than the algorithm presented here, but we are more interested in concurrency than algorithmics at the moment.) It works by taking a stream of all the natural numbers and introducing a sequence of filters, one for each prime, to winnow the multiples of that prime. At each step we have a sequence of filters of the primes so far, and the next number to pop out is the next prime, which triggers the creation of the next filter in the chain.

Here's a flow diagram; each box represents a filter element whose creation is triggered by the first number that flowed from the elements before it.

To create a stream of integers, we use a Gochannel, which, borrowing from CSP's descendants, represents a communications channel that can connect two concurrent computations. In Go, channel variables are references to a run-time object that coordinates the communication; as with maps and slices, usemaketo create a new channel.

Here is the first function inprogs/sieve.go:

09    // Send the sequence 2, 3, 4, ... to channel 'ch'.
10    func generate(ch chan int) {
11        for i := 2; ; i++ {
12            ch <- i  // Send 'i' to channel 'ch'.
13        }
14    }

The generatefunction sends the sequence 2, 3, 4, 5, ... to its argument channel,ch, using the binary communications operator<-. Channel operations block, so if there's no recipient for the value onch, the send operation will wait until one becomes available.

Thefilterfunction has three arguments: an input channel, an output channel, and a prime number. It copies values from the input to the output, discarding anything divisible by the prime. The unary communications operator<-(receive) retrieves the next value on the channel.

16    // Copy the values from channel 'in' to channel 'out',
17    // removing those divisible by 'prime'.
18    func filter(in, out chan int, prime int) {
19        for {
20            i := <-in;  // Receive value of new variable 'i' from 'in'.
21            if i % prime != 0 {
22                out <- i  // Send 'i' to channel 'out'.
23            }
24        }
25    }

The generator and filters execute concurrently. Go has its own model of process/threads/light-weight processes/coroutines, so to avoid notational confusion we call concurrently executing computations in Gogoroutines. To start a goroutine, invoke the function, prefixing the call with the keywordgo; this starts the function running in parallel with the current computation but in the same address space:

go sum(hugeArray); // calculate sum in the background

If you want to know when the calculation is done, pass a channel on which it can report back:

ch := make(chan int);
go sum(hugeArray, ch);
// ... do something else for a while
result := <-ch;  // wait for, and retrieve, result

Back to our prime sieve. Here's how the sieve pipeline is stitched together:

28    func main() {
29        ch := make(chan int);  // Create a new channel.
30        go generate(ch);  // Start generate() as a goroutine.
31        for {
32            prime := <-ch;
33            fmt.Println(prime);
34            ch1 := make(chan int);
35            go filter(ch, ch1, prime);
36            ch = ch1
37        }
38    }

Line 29 creates the initial channel to pass togenerate, which it then starts up. As each prime pops out of the channel, a newfilteris added to the pipeline anditsoutput becomes the new value ofch.

The sieve program can be tweaked to use a pattern common in this style of programming. Here is a variant version ofgenerate, fromprogs/sieve1.go:

10    func generate() chan int {
11        ch := make(chan int);
12        go func(){
13            for i := 2; ; i++ {
14                ch <- i
15            }
16        }();
17        return ch;
18    }

This version does all the setup internally. It creates the output channel, launches a goroutine running a function literal, and returns the channel to the caller. It is a factory for concurrent execution, starting the goroutine and returning its connection.

The function literal notation (lines 12-16) allows us to construct an anonymous function and invoke it on the spot. Notice that the local variablechis available to the function literal and lives on even aftergeneratereturns.

The same change can be made tofilter:

21    func filter(in chan int, prime int) chan int {
22        out := make(chan int);
23        go func() {
24            for {
25                if i := <-in; i % prime != 0 {
26                    out <- i
27                }
28            }
29        }();
30        return out;
31    }

The sievefunction's main loop becomes simpler and clearer as a result, and while we're at it let's turn it into a factory too:

33    func sieve() chan int {
34        out := make(chan int);
35        go func() {
36            ch := generate();
37            for {
38                prime := <-ch;
39                out <- prime;
40                ch = filter(ch, prime);
41            }
42        }();
43        return out;
44    }

Nowmain's interface to the prime sieve is a channel of primes:

46    func main() {
47        primes := sieve();
48        for {
49            fmt.Println(<-primes);
50        }
51    }

Multiplexing

With channels, it's possible to serve multiple independent client goroutines without writing an explicit multiplexer. The trick is to send the server a channel in the message, which it will then use to reply to the original sender. A realistic client-server program is a lot of code, so here is a very simple substitute to illustrate the idea. It starts by defining arequesttype, which embeds a channel that will be used for the reply.

09    type request struct {
10        a, b    int;
11        replyc  chan int;
12    }

The server will be trivial: it will do simple binary operations on integers. Here's the code that invokes the operation and responds to the request:

14    type binOp func(a, b int) int

16    func run(op binOp, req *request) {
17        reply := op(req.a, req.b)
18        req.replyc <- reply
19    }

Line 18 defines the namebinOpto be a function taking two integers and returning a third.

Theserverroutine loops forever, receiving requests and, to avoid blocking due to a long-running operation, starting a goroutine to do the actual work.

21    func server(op binOp, service chan *request) {
22        for {
23            req := <-service;
24            go run(op, req);  // don't wait for it
25        }
26    }

We construct a server in a familiar way, starting it and returning a channel connected to it:

28    func startServer(op binOp) chan *request {
29        req := make(chan *request);
30        go server(op, req);
31        return req;
32    }

Here's a simple test. It starts a server with an addition operator and sends outNrequests without waiting for the replies. Only after all the requests are sent does it check the results.

34    func main() {
35        adder := startServer(func(a, b int) int { return a + b });
36        const N = 100;
37        var reqs [N]request;
38        for i := 0; i < N; i++ {
39            req := &reqs[i];
40            req.a = i;
41            req.b = i + N;
42            req.replyc = make(chan int);
43            adder <- req;
44        }
45        for i := N-1; i &gt;= 0; i-- {   // doesn't matter what order
46            if <-reqs[i].replyc != N + 2*i {
47                fmt.Println("fail at", i);
48            }
49        }
50        fmt.Println("done");
51    }

One annoyance with this program is that it doesn't shut down the server cleanly; whenmainreturns there are a number of lingering goroutines blocked on communication. To solve this, we can provide a second,quitchannel to the server:

32    func startServer(op binOp) (service chan *request, quit chan bool) {
33        service = make(chan *request);
34        quit = make(chan bool);
35        go server(op, service, quit);
36        return service, quit;
37    }

It passes the quit channel to theserverfunction, which uses it like this:

21    func server(op binOp, service chan *request, quit chan bool) {
22        for {
23            select {
24            case req := <-service:
25                go run(op, req);  // don't wait for it
26            case <-quit:
27                return;
28            }
29        }
30    }

Inside server, theselectstatement chooses which of the multiple communications listed by its cases can proceed. If all are blocked, it waits until one can proceed; if multiple can proceed, it chooses one at random. In this instance, theselectallows the server to honor requests until it receives a quit message, at which point it returns, terminating its execution.

All that's left is to strobe thequitchannel at the end of main:

42        adder, quit := startServer(func(a, b int) int { return a + b });
...
55        quit <- true;

关于Go编程和并发程序设计还有许多其它的内容,但这份快速入门教程应该已经给你提供了一点基础知识。