在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的源代码